1 /* $OpenBSD: clientloop.c,v 1.305 2017/09/19 04:24:22 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 #ifdef HAVE_SYS_STAT_H
67 # include <sys/stat.h>
69 #ifdef HAVE_SYS_TIME_H
70 # include <sys/time.h>
72 #include <sys/socket.h>
89 #include "openbsd-compat/sys-queue.h"
101 #include "myproposal.h"
104 #include "readconf.h"
105 #include "clientloop.h"
106 #include "sshconnect.h"
108 #include "atomicio.h"
113 #include "hostfile.h"
116 extern Options options;
118 /* Flag indicating that stdin should be redirected from /dev/null. */
119 extern int stdin_null_flag;
121 /* Flag indicating that no shell has been requested */
122 extern int no_shell_flag;
124 /* Flag indicating that ssh should daemonise after authentication is complete */
125 extern int fork_after_authentication_flag;
128 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
131 * Name of the host we are connecting to. This is the name given on the
132 * command line, or the HostName specified for the user-supplied name in a
133 * configuration file.
138 * Flag to indicate that we have received a window change signal which has
139 * not yet been processed. This will cause a message indicating the new
140 * window size to be sent to the server a little later. This is volatile
141 * because this is updated in a signal handler.
143 static volatile sig_atomic_t received_window_change_signal = 0;
144 static volatile sig_atomic_t received_signal = 0;
146 /* Flag indicating whether the user's terminal is in non-blocking mode. */
147 static int in_non_blocking_mode = 0;
149 /* Time when backgrounded control master using ControlPersist should exit */
150 static time_t control_persist_exit_time = 0;
152 /* Common data for the client loop code. */
153 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
154 static int last_was_cr; /* Last character was a newline. */
155 static int exit_status; /* Used to store the command exit status. */
156 static Buffer stderr_buffer; /* Used for final exit message. */
157 static int connection_in; /* Connection to server (input). */
158 static int connection_out; /* Connection to server (output). */
159 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
160 static int session_closed; /* In SSH2: login session closed. */
161 static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
163 static void client_init_dispatch(void);
164 int session_ident = -1;
166 /* Track escape per proto2 channel */
167 struct escape_filter_ctx {
172 /* Context for channel confirmation replies */
173 struct channel_reply_ctx {
174 const char *request_type;
176 enum confirm_action action;
179 /* Global request success/failure callbacks */
180 /* XXX move to struct ssh? */
181 struct global_confirm {
182 TAILQ_ENTRY(global_confirm) entry;
183 global_confirm_cb *cb;
187 TAILQ_HEAD(global_confirms, global_confirm);
188 static struct global_confirms global_confirms =
189 TAILQ_HEAD_INITIALIZER(global_confirms);
191 void ssh_process_session2_setup(int, int, int, Buffer *);
193 /* Restores stdin to blocking mode. */
196 leave_non_blocking(void)
198 if (in_non_blocking_mode) {
199 unset_nonblock(fileno(stdin));
200 in_non_blocking_mode = 0;
205 * Signal handler for the window change signal (SIGWINCH). This just sets a
206 * flag indicating that the window has changed.
210 window_change_handler(int sig)
212 received_window_change_signal = 1;
213 signal(SIGWINCH, window_change_handler);
217 * Signal handler for signals that cause the program to terminate. These
218 * signals must be trapped to restore terminal modes.
222 signal_handler(int sig)
224 received_signal = sig;
229 * Returns current time in seconds from Jan 1, 1970 with the maximum
230 * available resolution.
234 get_current_time(void)
237 gettimeofday(&tv, NULL);
238 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
242 * Sets control_persist_exit_time to the absolute time when the
243 * backgrounded control master should exit due to expiry of the
244 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
245 * control master process, or if there is no ControlPersist timeout.
248 set_control_persist_exit_time(struct ssh *ssh)
250 if (muxserver_sock == -1 || !options.control_persist
251 || options.control_persist_timeout == 0) {
252 /* not using a ControlPersist timeout */
253 control_persist_exit_time = 0;
254 } else if (channel_still_open(ssh)) {
255 /* some client connections are still open */
256 if (control_persist_exit_time > 0)
257 debug2("%s: cancel scheduled exit", __func__);
258 control_persist_exit_time = 0;
259 } else if (control_persist_exit_time <= 0) {
260 /* a client connection has recently closed */
261 control_persist_exit_time = monotime() +
262 (time_t)options.control_persist_timeout;
263 debug2("%s: schedule exit in %d seconds", __func__,
264 options.control_persist_timeout);
266 /* else we are already counting down to the timeout */
269 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
271 client_x11_display_valid(const char *display)
278 dlen = strlen(display);
279 for (i = 0; i < dlen; i++) {
280 if (!isalnum((u_char)display[i]) &&
281 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
282 debug("Invalid character '%c' in DISPLAY", display[i]);
289 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
290 #define X11_TIMEOUT_SLACK 60
292 client_x11_get_proto(struct ssh *ssh, const char *display,
293 const char *xauth_path, u_int trusted, u_int timeout,
294 char **_proto, char **_data)
296 char cmd[1024], line[512], xdisplay[512];
297 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
298 static char proto[512], data[512];
300 int got_data = 0, generated = 0, do_unlink = 0, r;
302 u_int now, x11_timeout_real;
306 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
308 if (!client_x11_display_valid(display)) {
310 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
314 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
315 debug("No xauth program.");
319 if (xauth_path != NULL) {
321 * Handle FamilyLocal case where $DISPLAY does
322 * not match an authorization entry. For this we
323 * just try "xauth list unix:displaynum.screennum".
324 * XXX: "localhost" match to determine FamilyLocal
327 if (strncmp(display, "localhost:", 10) == 0) {
328 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
329 display + 10)) < 0 ||
330 (size_t)r >= sizeof(xdisplay)) {
331 error("%s: display name too long", __func__);
338 * Generate an untrusted X11 auth cookie.
340 * The authentication cookie should briefly outlive
341 * ssh's willingness to forward X11 connections to
342 * avoid nasty fail-open behaviour in the X server.
344 mktemp_proto(xauthdir, sizeof(xauthdir));
345 if (mkdtemp(xauthdir) == NULL) {
346 error("%s: mkdtemp: %s",
347 __func__, strerror(errno));
351 if ((r = snprintf(xauthfile, sizeof(xauthfile),
352 "%s/xauthfile", xauthdir)) < 0 ||
353 (size_t)r >= sizeof(xauthfile)) {
354 error("%s: xauthfile path too long", __func__);
360 if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
361 x11_timeout_real = UINT_MAX;
363 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
364 if ((r = snprintf(cmd, sizeof(cmd),
365 "%s -f %s generate %s " SSH_X11_PROTO
366 " untrusted timeout %u 2>" _PATH_DEVNULL,
367 xauth_path, xauthfile, display,
368 x11_timeout_real)) < 0 ||
369 (size_t)r >= sizeof(cmd))
370 fatal("%s: cmd too long", __func__);
371 debug2("%s: %s", __func__, cmd);
372 if (x11_refuse_time == 0) {
373 now = monotime() + 1;
374 if (UINT_MAX - timeout < now)
375 x11_refuse_time = UINT_MAX;
377 x11_refuse_time = now + timeout;
378 channel_set_x11_refuse_time(ssh,
381 if (system(cmd) == 0)
386 * When in untrusted mode, we read the cookie only if it was
387 * successfully generated as an untrusted one in the step
390 if (trusted || generated) {
391 snprintf(cmd, sizeof(cmd),
392 "%s %s%s list %s 2>" _PATH_DEVNULL,
394 generated ? "-f " : "" ,
395 generated ? xauthfile : "",
397 debug2("x11_get_proto: %s", cmd);
399 if (f && fgets(line, sizeof(line), f) &&
400 sscanf(line, "%*s %511s %511s", proto, data) == 2)
412 /* Don't fall back to fake X11 data for untrusted forwarding */
413 if (!trusted && !got_data) {
414 error("Warning: untrusted X11 forwarding setup failed: "
415 "xauth key data not generated");
420 * If we didn't get authentication data, just make up some
421 * data. The forwarding code will check the validity of the
422 * response anyway, and substitute this data. The X11
423 * server, however, will ignore this fake data and use
424 * whatever authentication mechanisms it was using otherwise
425 * for the local connection.
431 logit("Warning: No xauth data; "
432 "using fake authentication data for X11 forwarding.");
433 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
434 arc4random_buf(rnd, sizeof(rnd));
435 for (i = 0; i < sizeof(rnd); i++) {
436 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
445 * Checks if the client window has changed, and sends a packet about it to
446 * the server if so. The actual change is detected elsewhere (by a software
447 * interrupt on Unix); this just checks the flag and sends a message if
452 client_check_window_change(struct ssh *ssh)
454 if (!received_window_change_signal)
457 received_window_change_signal = 0;
459 debug2("%s: changed", __func__);
461 channel_send_window_changes(ssh);
465 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
467 struct global_confirm *gc;
469 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
472 gc->cb(ssh, type, seq, gc->ctx);
473 if (--gc->ref_count <= 0) {
474 TAILQ_REMOVE(&global_confirms, gc, entry);
475 explicit_bzero(gc, sizeof(*gc));
479 packet_set_alive_timeouts(0);
484 server_alive_check(void)
486 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
487 logit("Timeout, server %s not responding.", host);
490 packet_start(SSH2_MSG_GLOBAL_REQUEST);
491 packet_put_cstring("keepalive@openssh.com");
492 packet_put_char(1); /* boolean: want reply */
494 /* Insert an empty placeholder to maintain ordering */
495 client_register_global_confirm(NULL, NULL);
499 * Waits until the client can do something (some data becomes available on
500 * one of the file descriptors).
503 client_wait_until_can_do_something(struct ssh *ssh,
504 fd_set **readsetp, fd_set **writesetp,
505 int *maxfdp, u_int *nallocp, int rekeying)
507 struct timeval tv, *tvp;
509 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
512 /* Add any selections by the channel mechanism. */
513 channel_prepare_select(active_state, readsetp, writesetp, maxfdp,
514 nallocp, &minwait_secs);
516 /* channel_prepare_select could have closed the last channel */
517 if (session_closed && !channel_still_open(ssh) &&
518 !packet_have_data_to_write()) {
519 /* clear mask since we did not call select() */
520 memset(*readsetp, 0, *nallocp);
521 memset(*writesetp, 0, *nallocp);
525 FD_SET(connection_in, *readsetp);
527 /* Select server connection if have data to write to the server. */
528 if (packet_have_data_to_write())
529 FD_SET(connection_out, *writesetp);
532 * Wait for something to happen. This will suspend the process until
533 * some selected descriptor can be read, written, or has some other
534 * event pending, or a timeout expires.
537 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
538 if (options.server_alive_interval > 0) {
539 timeout_secs = options.server_alive_interval;
540 server_alive_time = now + options.server_alive_interval;
542 if (options.rekey_interval > 0 && !rekeying)
543 timeout_secs = MINIMUM(timeout_secs, packet_get_rekey_timeout());
544 set_control_persist_exit_time(ssh);
545 if (control_persist_exit_time > 0) {
546 timeout_secs = MINIMUM(timeout_secs,
547 control_persist_exit_time - now);
548 if (timeout_secs < 0)
551 if (minwait_secs != 0)
552 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
553 if (timeout_secs == INT_MAX)
556 tv.tv_sec = timeout_secs;
561 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
566 * We have to clear the select masks, because we return.
567 * We have to return, because the mainloop checks for the flags
568 * set by the signal handlers.
570 memset(*readsetp, 0, *nallocp);
571 memset(*writesetp, 0, *nallocp);
575 /* Note: we might still have data in the buffers. */
576 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
577 buffer_append(&stderr_buffer, buf, strlen(buf));
579 } else if (ret == 0) {
581 * Timeout. Could have been either keepalive or rekeying.
582 * Keepalive we check here, rekeying is checked in clientloop.
584 if (server_alive_time != 0 && server_alive_time <= monotime())
585 server_alive_check();
591 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
593 /* Flush stdout and stderr buffers. */
594 if (buffer_len(bout) > 0)
595 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
597 if (buffer_len(berr) > 0)
598 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
601 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
607 /* Send the suspend signal to the program itself. */
608 kill(getpid(), SIGTSTP);
610 /* Reset window sizes in case they have changed */
611 received_window_change_signal = 1;
613 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
617 client_process_net_input(fd_set *readset)
620 char buf[SSH_IOBUFSZ];
623 * Read input from the server, and add any such data to the buffer of
624 * the packet subsystem.
626 if (FD_ISSET(connection_in, readset)) {
627 /* Read as much as possible. */
628 len = read(connection_in, buf, sizeof(buf));
631 * Received EOF. The remote host has closed the
634 snprintf(buf, sizeof buf,
635 "Connection to %.300s closed by remote host.\r\n",
637 buffer_append(&stderr_buffer, buf, strlen(buf));
642 * There is a kernel bug on Solaris that causes select to
643 * sometimes wake up even though there is no data available.
646 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
651 * An error has encountered. Perhaps there is a
654 snprintf(buf, sizeof buf,
655 "Read from remote host %.300s: %.100s\r\n",
656 host, strerror(errno));
657 buffer_append(&stderr_buffer, buf, strlen(buf));
661 packet_process_incoming(buf, len);
666 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
668 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
673 * If a TTY was explicitly requested, then a failure to allocate
676 if (cr->action == CONFIRM_TTY &&
677 (options.request_tty == REQUEST_TTY_FORCE ||
678 options.request_tty == REQUEST_TTY_YES))
679 cr->action = CONFIRM_CLOSE;
681 /* XXX supress on mux _client_ quietmode */
682 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
683 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
685 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
686 debug2("%s request accepted on channel %d",
687 cr->request_type, c->self);
688 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
690 snprintf(errmsg, sizeof(errmsg),
691 "%s request failed\r\n", cr->request_type);
693 snprintf(errmsg, sizeof(errmsg),
694 "%s request failed on channel %d",
695 cr->request_type, c->self);
697 /* If error occurred on primary session channel, then exit */
698 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
701 * If error occurred on mux client, append to
705 buffer_append(c->extended, errmsg, strlen(errmsg));
708 if (cr->action == CONFIRM_TTY) {
710 * If a TTY allocation error occurred, then arrange
711 * for the correct TTY to leave raw mode.
713 if (c->self == session_ident)
716 mux_tty_alloc_failed(ssh, c);
717 } else if (cr->action == CONFIRM_CLOSE) {
718 chan_read_failed(ssh, c);
719 chan_write_failed(ssh, c);
726 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
732 client_expect_confirm(struct ssh *ssh, int id, const char *request,
733 enum confirm_action action)
735 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
737 cr->request_type = request;
740 channel_register_status_confirm(ssh, id, client_status_confirm,
741 client_abandon_status_confirm, cr);
745 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
747 struct global_confirm *gc, *last_gc;
749 /* Coalesce identical callbacks */
750 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
751 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
752 if (++last_gc->ref_count >= INT_MAX)
753 fatal("%s: last_gc->ref_count = %d",
754 __func__, last_gc->ref_count);
758 gc = xcalloc(1, sizeof(*gc));
762 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
766 process_cmdline(struct ssh *ssh)
768 void (*handler)(int);
770 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
773 memset(&fwd, 0, sizeof(fwd));
775 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
776 handler = signal(SIGINT, SIG_IGN);
777 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
780 while (isspace((u_char)*s))
783 s++; /* Skip cmdline '-', if any */
787 if (*s == 'h' || *s == 'H' || *s == '?') {
789 logit(" -L[bind_address:]port:host:hostport "
790 "Request local forward");
791 logit(" -R[bind_address:]port:host:hostport "
792 "Request remote forward");
793 logit(" -D[bind_address:]port "
794 "Request dynamic forward");
795 logit(" -KL[bind_address:]port "
796 "Cancel local forward");
797 logit(" -KR[bind_address:]port "
798 "Cancel remote forward");
799 logit(" -KD[bind_address:]port "
800 "Cancel dynamic forward");
801 if (!options.permit_local_command)
804 "Execute local command");
808 if (*s == '!' && options.permit_local_command) {
825 logit("Invalid command.");
829 while (isspace((u_char)*++s))
832 /* XXX update list of forwards in options */
834 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
835 if (!parse_forward(&fwd, s, 1, 0)) {
836 logit("Bad forwarding close specification.");
840 ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
842 ok = channel_cancel_lport_listener(ssh, &fwd,
843 0, &options.fwd_opts) > 0;
845 ok = channel_cancel_lport_listener(ssh, &fwd,
846 CHANNEL_CANCEL_PORT_STATIC,
847 &options.fwd_opts) > 0;
849 logit("Unknown port forwarding.");
852 logit("Canceled forwarding.");
854 if (!parse_forward(&fwd, s, dynamic, remote)) {
855 logit("Bad forwarding specification.");
858 if (local || dynamic) {
859 if (!channel_setup_local_fwd_listener(ssh, &fwd,
860 &options.fwd_opts)) {
861 logit("Port forwarding failed.");
865 if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
866 logit("Port forwarding failed.");
870 logit("Forwarding port.");
874 signal(SIGINT, handler);
875 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
877 free(fwd.listen_host);
878 free(fwd.listen_path);
879 free(fwd.connect_host);
880 free(fwd.connect_path);
883 /* reasons to suppress output of an escape command in help output */
884 #define SUPPRESS_NEVER 0 /* never suppress, always show */
885 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
886 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
887 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
888 struct escape_help_text {
893 static struct escape_help_text esc_txt[] = {
894 {".", "terminate session", SUPPRESS_MUXMASTER},
895 {".", "terminate connection (and any multiplexed sessions)",
897 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
898 {"C", "open a command line", SUPPRESS_MUXCLIENT},
899 {"R", "request rekey", SUPPRESS_NEVER},
900 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
901 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
902 {"#", "list forwarded connections", SUPPRESS_NEVER},
903 {"&", "background ssh (when waiting for connections to terminate)",
905 {"?", "this message", SUPPRESS_NEVER},
909 print_escape_help(Buffer *b, int escape_char, int mux_client, int using_stderr)
911 unsigned int i, suppress_flags;
914 snprintf(string, sizeof string, "%c?\r\n"
915 "Supported escape sequences:\r\n", escape_char);
916 buffer_append(b, string, strlen(string));
919 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
920 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
921 (using_stderr ? 0 : SUPPRESS_SYSLOG);
923 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
924 if (esc_txt[i].flags & suppress_flags)
926 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
927 escape_char, esc_txt[i].cmd, esc_txt[i].text);
928 buffer_append(b, string, strlen(string));
931 snprintf(string, sizeof string,
932 " %c%c - send the escape character by typing it twice\r\n"
933 "(Note that escapes are only recognized immediately after "
934 "newline.)\r\n", escape_char, escape_char);
935 buffer_append(b, string, strlen(string));
939 * Process the characters one by one.
942 process_escapes(struct ssh *ssh, Channel *c,
943 Buffer *bin, Buffer *bout, Buffer *berr,
952 struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
953 NULL : (struct escape_filter_ctx *)c->filter_ctx;
955 if (c->filter_ctx == NULL)
961 for (i = 0; i < (u_int)len; i++) {
962 /* Get one character at a time. */
965 if (efc->escape_pending) {
966 /* We have previously seen an escape character. */
967 /* Clear the flag now. */
968 efc->escape_pending = 0;
970 /* Process the escaped character. */
973 /* Terminate the connection. */
974 snprintf(string, sizeof string, "%c.\r\n",
976 buffer_append(berr, string, strlen(string));
978 if (c && c->ctl_chan != -1) {
979 chan_read_failed(ssh, c);
980 chan_write_failed(ssh, c);
981 if (c->detach_user) {
985 c->type = SSH_CHANNEL_ABANDONED;
986 buffer_clear(c->input);
987 chan_ibuf_empty(ssh, c);
994 /* XXX support this for mux clients */
995 if (c && c->ctl_chan != -1) {
999 snprintf(b, sizeof b, "^Z");
1001 snprintf(b, sizeof b, "%c", ch);
1002 snprintf(string, sizeof string,
1003 "%c%s escape not available to "
1004 "multiplexed sessions\r\n",
1005 efc->escape_char, b);
1006 buffer_append(berr, string,
1010 /* Suspend the program. Inform the user */
1011 snprintf(string, sizeof string,
1012 "%c^Z [suspend ssh]\r\n", efc->escape_char);
1013 buffer_append(berr, string, strlen(string));
1015 /* Restore terminal modes and suspend. */
1016 client_suspend_self(bin, bout, berr);
1018 /* We have been continued. */
1022 snprintf(string, sizeof string,
1023 "%cB\r\n", efc->escape_char);
1024 buffer_append(berr, string, strlen(string));
1025 channel_request_start(ssh, c->self, "break", 0);
1026 packet_put_int(1000);
1031 if (datafellows & SSH_BUG_NOREKEY)
1032 logit("Server does not "
1033 "support re-keying");
1041 if (c && c->ctl_chan != -1)
1043 if (!log_is_on_stderr()) {
1044 snprintf(string, sizeof string,
1045 "%c%c [Logging to syslog]\r\n",
1046 efc->escape_char, ch);
1047 buffer_append(berr, string,
1051 if (ch == 'V' && options.log_level >
1053 log_change_level(--options.log_level);
1054 if (ch == 'v' && options.log_level <
1055 SYSLOG_LEVEL_DEBUG3)
1056 log_change_level(++options.log_level);
1057 snprintf(string, sizeof string,
1058 "%c%c [LogLevel %s]\r\n",
1059 efc->escape_char, ch,
1060 log_level_name(options.log_level));
1061 buffer_append(berr, string, strlen(string));
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(ssh);
1079 snprintf(string, sizeof string,
1080 "%c& [backgrounded]\n", efc->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. */
1094 buffer_append(bin, "\004", 1);
1095 /* fake EOF on stdin */
1098 print_escape_help(berr, efc->escape_char,
1099 (c && c->ctl_chan != -1),
1100 log_is_on_stderr());
1104 snprintf(string, sizeof string, "%c#\r\n",
1106 buffer_append(berr, string, strlen(string));
1107 s = channel_open_message(ssh);
1108 buffer_append(berr, s, strlen(s));
1113 if (c && c->ctl_chan != -1)
1115 process_cmdline(ssh);
1119 if (ch != efc->escape_char) {
1120 buffer_put_char(bin, efc->escape_char);
1123 /* Escaped characters fall through here */
1128 * The previous character was not an escape char.
1129 * Check if this is an escape.
1131 if (last_was_cr && ch == efc->escape_char) {
1133 * It is. Set the flag and continue to
1136 efc->escape_pending = 1;
1142 * Normal character. Record whether it was a newline,
1143 * and append it to the buffer.
1145 last_was_cr = (ch == '\r' || ch == '\n');
1146 buffer_put_char(bin, ch);
1153 * Get packets from the connection input buffer, and process them as long as
1154 * there are packets available.
1156 * Any unknown packets received during the actual
1157 * session cause the session to terminate. This is
1158 * intended to make debugging easier since no
1159 * confirmations are sent. Any compatible protocol
1160 * extensions must be negotiated during the
1161 * preparatory phase.
1165 client_process_buffered_input_packets(void)
1167 ssh_dispatch_run_fatal(active_state, DISPATCH_NONBLOCK, &quit_pending);
1170 /* scan buf[] for '~' before sending data to the peer */
1172 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1174 client_new_escape_filter_ctx(int escape_char)
1176 struct escape_filter_ctx *ret;
1178 ret = xcalloc(1, sizeof(*ret));
1179 ret->escape_pending = 0;
1180 ret->escape_char = escape_char;
1184 /* Free the escape filter context on channel free */
1186 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1192 client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1194 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1197 return process_escapes(ssh, c, c->input, c->output, c->extended,
1202 client_channel_closed(struct ssh *ssh, int id, void *arg)
1204 channel_cancel_cleanup(ssh, id);
1206 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1210 * Implements the interactive session with the server. This is called after
1211 * the user has been authenticated, and a command has been started on the
1212 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1213 * used as an escape character for terminating or suspending the session.
1216 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1219 fd_set *readset = NULL, *writeset = NULL;
1220 double start_time, total_time;
1221 int r, max_fd = 0, max_fd2 = 0, len;
1222 u_int64_t ibytes, obytes;
1226 debug("Entering interactive session.");
1228 if (options.control_master &&
1229 !option_clear_or_none(options.control_path)) {
1230 debug("pledge: id");
1231 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
1233 fatal("%s pledge(): %s", __func__, strerror(errno));
1235 } else if (options.forward_x11 || options.permit_local_command) {
1236 debug("pledge: exec");
1237 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1239 fatal("%s pledge(): %s", __func__, strerror(errno));
1241 } else if (options.update_hostkeys) {
1242 debug("pledge: filesystem full");
1243 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1245 fatal("%s pledge(): %s", __func__, strerror(errno));
1247 } else if (!option_clear_or_none(options.proxy_command) ||
1248 fork_after_authentication_flag) {
1249 debug("pledge: proc");
1250 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1251 fatal("%s pledge(): %s", __func__, strerror(errno));
1254 debug("pledge: network");
1255 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1256 fatal("%s pledge(): %s", __func__, strerror(errno));
1259 start_time = get_current_time();
1261 /* Initialize variables. */
1264 connection_in = packet_get_connection_in();
1265 connection_out = packet_get_connection_out();
1266 max_fd = MAXIMUM(connection_in, connection_out);
1270 /* Initialize buffers. */
1271 buffer_init(&stderr_buffer);
1273 client_init_dispatch();
1276 * Set signal handlers, (e.g. to restore non-blocking mode)
1277 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1279 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1280 signal(SIGHUP, signal_handler);
1281 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1282 signal(SIGINT, signal_handler);
1283 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1284 signal(SIGQUIT, signal_handler);
1285 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1286 signal(SIGTERM, signal_handler);
1287 signal(SIGWINCH, window_change_handler);
1290 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1292 session_ident = ssh2_chan_id;
1293 if (session_ident != -1) {
1294 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1295 channel_register_filter(ssh, session_ident,
1296 client_simple_escape_filter, NULL,
1297 client_filter_cleanup,
1298 client_new_escape_filter_ctx(
1301 channel_register_cleanup(ssh, session_ident,
1302 client_channel_closed, 0);
1305 /* Main loop of the client for the interactive session mode. */
1306 while (!quit_pending) {
1308 /* Process buffered packets sent by the server. */
1309 client_process_buffered_input_packets();
1311 if (session_closed && !channel_still_open(ssh))
1314 if (ssh_packet_is_rekeying(ssh)) {
1315 debug("rekeying in progress");
1316 } else if (need_rekeying) {
1317 /* manual rekey request */
1318 debug("need rekeying");
1319 if ((r = kex_start_rekex(ssh)) != 0)
1320 fatal("%s: kex_start_rekex: %s", __func__,
1325 * Make packets from buffered channel data, and
1326 * enqueue them for sending to the server.
1328 if (packet_not_very_much_data_to_write())
1329 channel_output_poll(ssh);
1332 * Check if the window size has changed, and buffer a
1333 * message about it to the server if so.
1335 client_check_window_change(ssh);
1341 * Wait until we have something to do (something becomes
1342 * available on one of the descriptors).
1345 client_wait_until_can_do_something(ssh, &readset, &writeset,
1346 &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
1351 /* Do channel operations unless rekeying in progress. */
1352 if (!ssh_packet_is_rekeying(ssh))
1353 channel_after_select(ssh, readset, writeset);
1355 /* Buffer input from the connection. */
1356 client_process_net_input(readset);
1362 * Send as much buffered packet data as possible to the
1365 if (FD_ISSET(connection_out, writeset))
1366 packet_write_poll();
1369 * If we are a backgrounded control master, and the
1370 * timeout has expired without any active client
1371 * connections, then quit.
1373 if (control_persist_exit_time > 0) {
1374 if (monotime() >= control_persist_exit_time) {
1375 debug("ControlPersist timeout expired");
1383 /* Terminate the session. */
1385 /* Stop watching for window change. */
1386 signal(SIGWINCH, SIG_DFL);
1388 packet_start(SSH2_MSG_DISCONNECT);
1389 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1390 packet_put_cstring("disconnected by user");
1391 packet_put_cstring(""); /* language tag */
1393 packet_write_wait();
1395 channel_free_all(ssh);
1398 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1400 /* restore blocking io */
1401 if (!isatty(fileno(stdin)))
1402 unset_nonblock(fileno(stdin));
1403 if (!isatty(fileno(stdout)))
1404 unset_nonblock(fileno(stdout));
1405 if (!isatty(fileno(stderr)))
1406 unset_nonblock(fileno(stderr));
1409 * If there was no shell or command requested, there will be no remote
1410 * exit status to be returned. In that case, clear error code if the
1411 * connection was deliberately terminated at this end.
1413 if (no_shell_flag && received_signal == SIGTERM) {
1414 received_signal = 0;
1418 if (received_signal) {
1419 verbose("Killed by signal %d.", (int) received_signal);
1424 * In interactive mode (with pseudo tty) display a message indicating
1425 * that the connection has been closed.
1427 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1428 snprintf(buf, sizeof buf,
1429 "Connection to %.64s closed.\r\n", host);
1430 buffer_append(&stderr_buffer, buf, strlen(buf));
1433 /* Output any buffered data for stderr. */
1434 if (buffer_len(&stderr_buffer) > 0) {
1435 len = atomicio(vwrite, fileno(stderr),
1436 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1437 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1438 error("Write failed flushing stderr buffer.");
1440 buffer_consume(&stderr_buffer, len);
1443 /* Clear and free any buffers. */
1444 explicit_bzero(buf, sizeof(buf));
1445 buffer_free(&stderr_buffer);
1447 /* Report bytes transferred, and transfer rates. */
1448 total_time = get_current_time() - start_time;
1449 packet_get_bytes(&ibytes, &obytes);
1450 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1451 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1453 verbose("Bytes per second: sent %.1f, received %.1f",
1454 obytes / total_time, ibytes / total_time);
1455 /* Return the exit status of the program. */
1456 debug("Exit status %d", exit_status);
1463 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1464 int rchan, u_int rwindow, u_int rmaxpack)
1467 struct sshbuf *b = NULL;
1468 char *listen_address, *originator_address;
1469 u_short listen_port, originator_port;
1472 /* Get rest of the packet */
1473 listen_address = packet_get_string(NULL);
1474 listen_port = packet_get_int();
1475 originator_address = packet_get_string(NULL);
1476 originator_port = packet_get_int();
1479 debug("%s: listen %s port %d, originator %s port %d", __func__,
1480 listen_address, listen_port, originator_address, originator_port);
1482 c = channel_connect_by_listen_address(ssh, listen_address, listen_port,
1483 "forwarded-tcpip", originator_address);
1485 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1486 if ((b = sshbuf_new()) == NULL) {
1487 error("%s: alloc reply", __func__);
1490 /* reconstruct and send to muxclient */
1491 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1492 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1493 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1494 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1495 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1496 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1497 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1498 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1499 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1500 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1501 (r = sshbuf_put_stringb(c->output, b)) != 0) {
1502 error("%s: compose for muxclient %s", __func__,
1510 free(originator_address);
1511 free(listen_address);
1516 client_request_forwarded_streamlocal(struct ssh *ssh,
1517 const char *request_type, int rchan)
1522 /* Get the remote path. */
1523 listen_path = packet_get_string(NULL);
1524 /* XXX: Skip reserved field for now. */
1525 if (packet_get_string_ptr(NULL) == NULL)
1526 fatal("%s: packet_get_string_ptr failed", __func__);
1529 debug("%s: %s", __func__, listen_path);
1531 c = channel_connect_by_listen_path(ssh, listen_path,
1532 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1538 client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1542 u_short originator_port;
1545 if (!options.forward_x11) {
1546 error("Warning: ssh server tried X11 forwarding.");
1547 error("Warning: this is probably a break-in attempt by a "
1548 "malicious server.");
1551 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1552 verbose("Rejected X11 connection after ForwardX11Timeout "
1556 originator = packet_get_string(NULL);
1557 if (datafellows & SSH_BUG_X11FWD) {
1558 debug2("buggy server: x11 request w/o originator_port");
1559 originator_port = 0;
1561 originator_port = packet_get_int();
1564 /* XXX check permission */
1565 debug("client_request_x11: request from %s %d", originator,
1568 sock = x11_connect_display(ssh);
1571 c = channel_new(ssh, "x11",
1572 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1573 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1579 client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1584 if (!options.forward_agent) {
1585 error("Warning: ssh server tried agent forwarding.");
1586 error("Warning: this is probably a break-in attempt by a "
1587 "malicious server.");
1590 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1591 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1592 debug("%s: ssh_get_authentication_socket: %s",
1593 __func__, ssh_err(r));
1596 c = channel_new(ssh, "authentication agent connection",
1597 SSH_CHANNEL_OPEN, sock, sock, -1,
1598 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1599 "authentication agent connection", 1);
1605 client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1606 int local_tun, int remote_tun)
1611 if (tun_mode == SSH_TUNMODE_NO)
1614 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1616 /* Open local tunnel device */
1617 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1618 error("Tunnel device open failed.");
1622 c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1623 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1626 #if defined(SSH_TUN_FILTER)
1627 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1628 channel_register_filter(ssh, c->self, sys_tun_infilter,
1629 sys_tun_outfilter, NULL, NULL);
1632 packet_start(SSH2_MSG_CHANNEL_OPEN);
1633 packet_put_cstring("tun@openssh.com");
1634 packet_put_int(c->self);
1635 packet_put_int(c->local_window_max);
1636 packet_put_int(c->local_maxpacket);
1637 packet_put_int(tun_mode);
1638 packet_put_int(remote_tun);
1644 /* XXXX move to generic input handler */
1646 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1651 u_int rmaxpack, rwindow, len;
1653 ctype = packet_get_string(&len);
1654 rchan = packet_get_int();
1655 rwindow = packet_get_int();
1656 rmaxpack = packet_get_int();
1658 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1659 ctype, rchan, rwindow, rmaxpack);
1661 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1662 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1664 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1665 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1666 } else if (strcmp(ctype, "x11") == 0) {
1667 c = client_request_x11(ssh, ctype, rchan);
1668 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1669 c = client_request_agent(ssh, ctype, rchan);
1671 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1672 debug3("proxied to downstream: %s", ctype);
1673 } else if (c != NULL) {
1674 debug("confirm %s", ctype);
1675 c->remote_id = rchan;
1676 c->have_remote_id = 1;
1677 c->remote_window = rwindow;
1678 c->remote_maxpacket = rmaxpack;
1679 if (c->type != SSH_CHANNEL_CONNECTING) {
1680 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1681 packet_put_int(c->remote_id);
1682 packet_put_int(c->self);
1683 packet_put_int(c->local_window);
1684 packet_put_int(c->local_maxpacket);
1688 debug("failure %s", ctype);
1689 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1690 packet_put_int(rchan);
1691 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1692 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1693 packet_put_cstring("open failed");
1694 packet_put_cstring("");
1703 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1706 int exitval, id, reply, success = 0;
1709 id = packet_get_int();
1710 c = channel_lookup(ssh, id);
1711 if (channel_proxy_upstream(c, type, seq, ssh))
1713 rtype = packet_get_string(NULL);
1714 reply = packet_get_char();
1716 debug("client_input_channel_req: channel %d rtype %s reply %d",
1720 error("client_input_channel_req: request for channel -1");
1721 } else if (c == NULL) {
1722 error("client_input_channel_req: channel %d: "
1723 "unknown channel", id);
1724 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1726 chan_rcvd_eow(ssh, c);
1727 } else if (strcmp(rtype, "exit-status") == 0) {
1728 exitval = packet_get_int();
1729 if (c->ctl_chan != -1) {
1730 mux_exit_message(ssh, c, exitval);
1732 } else if (id == session_ident) {
1733 /* Record exit value of local session */
1735 exit_status = exitval;
1737 /* Probably for a mux channel that has already closed */
1738 debug("%s: no sink for exit-status on channel %d",
1743 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1744 if (!c->have_remote_id)
1745 fatal("%s: channel %d: no remote_id",
1747 packet_start(success ?
1748 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1749 packet_put_int(c->remote_id);
1756 struct hostkeys_update_ctx {
1757 /* The hostname and (optionally) IP address string for the server */
1758 char *host_str, *ip_str;
1761 * Keys received from the server and a flag for each indicating
1762 * whether they already exist in known_hosts.
1763 * keys_seen is filled in by hostkeys_find() and later (for new
1764 * keys) by client_global_hostkeys_private_confirm().
1766 struct sshkey **keys;
1771 * Keys that are in known_hosts, but were not present in the update
1772 * from the server (i.e. scheduled to be deleted).
1773 * Filled in by hostkeys_find().
1775 struct sshkey **old_keys;
1780 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
1786 for (i = 0; i < ctx->nkeys; i++)
1787 sshkey_free(ctx->keys[i]);
1789 free(ctx->keys_seen);
1790 for (i = 0; i < ctx->nold; i++)
1791 sshkey_free(ctx->old_keys[i]);
1792 free(ctx->old_keys);
1793 free(ctx->host_str);
1799 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
1801 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1803 struct sshkey **tmp;
1805 if (l->status != HKF_STATUS_MATCHED || l->key == NULL)
1808 /* Mark off keys we've already seen for this host */
1809 for (i = 0; i < ctx->nkeys; i++) {
1810 if (sshkey_equal(l->key, ctx->keys[i])) {
1811 debug3("%s: found %s key at %s:%ld", __func__,
1812 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
1813 ctx->keys_seen[i] = 1;
1817 /* This line contained a key that not offered by the server */
1818 debug3("%s: deprecated %s key at %s:%ld", __func__,
1819 sshkey_ssh_name(l->key), l->path, l->linenum);
1820 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1821 sizeof(*ctx->old_keys))) == NULL)
1822 fatal("%s: recallocarray failed nold = %zu",
1823 __func__, ctx->nold);
1824 ctx->old_keys = tmp;
1825 ctx->old_keys[ctx->nold++] = l->key;
1832 update_known_hosts(struct hostkeys_update_ctx *ctx)
1835 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
1836 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1837 char *fp, *response;
1840 for (i = 0; i < ctx->nkeys; i++) {
1841 if (ctx->keys_seen[i] != 2)
1843 if ((fp = sshkey_fingerprint(ctx->keys[i],
1844 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1845 fatal("%s: sshkey_fingerprint failed", __func__);
1846 do_log2(loglevel, "Learned new hostkey: %s %s",
1847 sshkey_type(ctx->keys[i]), fp);
1850 for (i = 0; i < ctx->nold; i++) {
1851 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
1852 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1853 fatal("%s: sshkey_fingerprint failed", __func__);
1854 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
1855 sshkey_type(ctx->old_keys[i]), fp);
1858 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1859 if (get_saved_tio() != NULL) {
1864 for (i = 0; !quit_pending && i < 3; i++) {
1866 response = read_passphrase("Accept updated hostkeys? "
1867 "(yes/no): ", RP_ECHO);
1868 if (strcasecmp(response, "yes") == 0)
1870 else if (quit_pending || response == NULL ||
1871 strcasecmp(response, "no") == 0) {
1872 options.update_hostkeys = 0;
1875 do_log2(loglevel, "Please enter "
1876 "\"yes\" or \"no\"");
1879 if (quit_pending || i >= 3 || response == NULL)
1880 options.update_hostkeys = 0;
1887 * Now that all the keys are verified, we can go ahead and replace
1888 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
1889 * cancel the operation).
1891 if (options.update_hostkeys != 0 &&
1892 (r = hostfile_replace_entries(options.user_hostfiles[0],
1893 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
1894 options.hash_known_hosts, 0,
1895 options.fingerprint_hash)) != 0)
1896 error("%s: hostfile_replace_entries failed: %s",
1897 __func__, ssh_err(r));
1901 client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
1902 u_int32_t seq, void *_ctx)
1904 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1906 struct sshbuf *signdata;
1912 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
1913 if (type != SSH2_MSG_REQUEST_SUCCESS) {
1914 error("Server failed to confirm ownership of "
1915 "private host keys");
1916 hostkeys_update_ctx_free(ctx);
1919 if ((signdata = sshbuf_new()) == NULL)
1920 fatal("%s: sshbuf_new failed", __func__);
1921 /* Don't want to accidentally accept an unbound signature */
1922 if (ssh->kex->session_id_len == 0)
1923 fatal("%s: ssh->kex->session_id_len == 0", __func__);
1925 * Expect a signature for each of the ctx->nnew private keys we
1926 * haven't seen before. They will be in the same order as the
1927 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
1929 for (ndone = i = 0; i < ctx->nkeys; i++) {
1930 if (ctx->keys_seen[i])
1932 /* Prepare data to be signed: session ID, unique string, key */
1933 sshbuf_reset(signdata);
1934 if ( (r = sshbuf_put_cstring(signdata,
1935 "hostkeys-prove-00@openssh.com")) != 0 ||
1936 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
1937 ssh->kex->session_id_len)) != 0 ||
1938 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1939 fatal("%s: failed to prepare signature: %s",
1940 __func__, ssh_err(r));
1941 /* Extract and verify signature */
1942 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1943 error("%s: couldn't parse message: %s",
1944 __func__, ssh_err(r));
1947 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1948 sshbuf_ptr(signdata), sshbuf_len(signdata), 0)) != 0) {
1949 error("%s: server gave bad signature for %s key %zu",
1950 __func__, sshkey_type(ctx->keys[i]), i);
1953 /* Key is good. Mark it as 'seen' */
1954 ctx->keys_seen[i] = 2;
1957 if (ndone != ctx->nnew)
1958 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
1959 ndone, ctx->nnew); /* Shouldn't happen */
1960 ssh_packet_check_eom(ssh);
1962 /* Make the edits to known_hosts */
1963 update_known_hosts(ctx);
1965 hostkeys_update_ctx_free(ctx);
1969 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
1970 * Made slightly less trivial by the multiple RSA signature algorithm names.
1973 key_accepted_by_hostkeyalgs(const struct sshkey *key)
1975 const char *ktype = sshkey_ssh_name(key);
1976 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
1977 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
1979 if (key == NULL || key->type == KEY_UNSPEC)
1981 if (key->type == KEY_RSA &&
1982 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
1983 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
1985 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
1989 * Handle hostkeys-00@openssh.com global request to inform the client of all
1990 * the server's hostkeys. The keys are checked against the user's
1991 * HostkeyAlgorithms preference before they are accepted.
1994 client_input_hostkeys(void)
1996 struct ssh *ssh = active_state; /* XXX */
1997 const u_char *blob = NULL;
1999 struct sshbuf *buf = NULL;
2000 struct sshkey *key = NULL, **tmp;
2003 static int hostkeys_seen = 0; /* XXX use struct ssh */
2004 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2005 struct hostkeys_update_ctx *ctx = NULL;
2008 fatal("%s: server already sent hostkeys", __func__);
2009 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2011 return 1; /* won't ask in batchmode, so don't even try */
2012 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2015 ctx = xcalloc(1, sizeof(*ctx));
2016 while (ssh_packet_remaining(ssh) > 0) {
2019 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2020 error("%s: couldn't parse message: %s",
2021 __func__, ssh_err(r));
2024 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2025 error("%s: parse key: %s", __func__, ssh_err(r));
2028 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2030 debug3("%s: received %s key %s", __func__,
2031 sshkey_type(key), fp);
2034 if (!key_accepted_by_hostkeyalgs(key)) {
2035 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2036 __func__, sshkey_ssh_name(key));
2040 if (sshkey_is_cert(key)) {
2041 debug3("%s: %s key is a certificate; skipping",
2042 __func__, sshkey_ssh_name(key));
2045 /* Ensure keys are unique */
2046 for (i = 0; i < ctx->nkeys; i++) {
2047 if (sshkey_equal(key, ctx->keys[i])) {
2048 error("%s: received duplicated %s host key",
2049 __func__, sshkey_ssh_name(key));
2053 /* Key is good, record it */
2054 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2055 sizeof(*ctx->keys))) == NULL)
2056 fatal("%s: recallocarray failed nkeys = %zu",
2057 __func__, ctx->nkeys);
2059 ctx->keys[ctx->nkeys++] = key;
2063 if (ctx->nkeys == 0) {
2064 debug("%s: server sent no hostkeys", __func__);
2068 if ((ctx->keys_seen = calloc(ctx->nkeys,
2069 sizeof(*ctx->keys_seen))) == NULL)
2070 fatal("%s: calloc failed", __func__);
2072 get_hostfile_hostname_ipaddr(host,
2073 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2074 options.port, &ctx->host_str,
2075 options.check_host_ip ? &ctx->ip_str : NULL);
2077 /* Find which keys we already know about. */
2078 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2079 ctx, ctx->host_str, ctx->ip_str,
2080 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2081 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2085 /* Figure out if we have any new keys to add */
2087 for (i = 0; i < ctx->nkeys; i++) {
2088 if (!ctx->keys_seen[i])
2092 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2093 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2095 if (ctx->nnew == 0 && ctx->nold != 0) {
2096 /* We have some keys to remove. Just do it. */
2097 update_known_hosts(ctx);
2098 } else if (ctx->nnew != 0) {
2100 * We have received hitherto-unseen keys from the server.
2101 * Ask the server to confirm ownership of the private halves.
2103 debug3("%s: asking server to prove ownership for %zu keys",
2104 __func__, ctx->nnew);
2105 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2106 (r = sshpkt_put_cstring(ssh,
2107 "hostkeys-prove-00@openssh.com")) != 0 ||
2108 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2109 fatal("%s: cannot prepare packet: %s",
2110 __func__, ssh_err(r));
2111 if ((buf = sshbuf_new()) == NULL)
2112 fatal("%s: sshbuf_new", __func__);
2113 for (i = 0; i < ctx->nkeys; i++) {
2114 if (ctx->keys_seen[i])
2117 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2118 fatal("%s: sshkey_putb: %s",
2119 __func__, ssh_err(r));
2120 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2121 fatal("%s: sshpkt_put_string: %s",
2122 __func__, ssh_err(r));
2124 if ((r = sshpkt_send(ssh)) != 0)
2125 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2126 client_register_global_confirm(
2127 client_global_hostkeys_private_confirm, ctx);
2128 ctx = NULL; /* will be freed in callback */
2133 hostkeys_update_ctx_free(ctx);
2137 * NB. Return success for all cases. The server doesn't need to know
2138 * what the client does with its hosts file.
2144 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2150 rtype = packet_get_cstring(NULL);
2151 want_reply = packet_get_char();
2152 debug("client_input_global_request: rtype %s want_reply %d",
2154 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2155 success = client_input_hostkeys();
2157 packet_start(success ?
2158 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2160 packet_write_wait();
2167 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2168 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2173 debug2("%s: id %d", __func__, id);
2175 if ((c = channel_lookup(ssh, id)) == NULL)
2176 fatal("%s: channel %d: unknown channel", __func__, id);
2178 packet_set_interactive(want_tty,
2179 options.ip_qos_interactive, options.ip_qos_bulk);
2184 /* Store window size in the packet. */
2185 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2186 memset(&ws, 0, sizeof(ws));
2188 channel_request_start(ssh, id, "pty-req", 1);
2189 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2190 packet_put_cstring(term != NULL ? term : "");
2191 packet_put_int((u_int)ws.ws_col);
2192 packet_put_int((u_int)ws.ws_row);
2193 packet_put_int((u_int)ws.ws_xpixel);
2194 packet_put_int((u_int)ws.ws_ypixel);
2196 tiop = get_saved_tio();
2197 tty_make_modes(-1, tiop);
2199 /* XXX wait for reply */
2203 /* Transfer any environment variables from client to server */
2204 if (options.num_send_env != 0 && env != NULL) {
2208 debug("Sending environment.");
2209 for (i = 0; env[i] != NULL; i++) {
2211 name = xstrdup(env[i]);
2212 if ((val = strchr(name, '=')) == NULL) {
2219 for (j = 0; j < options.num_send_env; j++) {
2220 if (match_pattern(name, options.send_env[j])) {
2226 debug3("Ignored env %s", name);
2231 debug("Sending env %s = %s", name, val);
2232 channel_request_start(ssh, id, "env", 0);
2233 packet_put_cstring(name);
2234 packet_put_cstring(val);
2240 len = buffer_len(cmd);
2244 if (want_subsystem) {
2245 debug("Sending subsystem: %.*s",
2246 len, (u_char*)buffer_ptr(cmd));
2247 channel_request_start(ssh, id, "subsystem", 1);
2248 client_expect_confirm(ssh, id, "subsystem",
2251 debug("Sending command: %.*s",
2252 len, (u_char*)buffer_ptr(cmd));
2253 channel_request_start(ssh, id, "exec", 1);
2254 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2256 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2259 channel_request_start(ssh, id, "shell", 1);
2260 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2266 client_init_dispatch(void)
2268 dispatch_init(&dispatch_protocol_error);
2270 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2271 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2272 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2273 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2274 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2275 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2276 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2277 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2278 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2279 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2280 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2281 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2284 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2286 /* global request reply messages */
2287 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2288 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2292 client_stop_mux(void)
2294 if (options.control_path != NULL && muxserver_sock != -1)
2295 unlink(options.control_path);
2297 * If we are in persist mode, or don't have a shell, signal that we
2298 * should close when all active channels are closed.
2300 if (options.control_persist || no_shell_flag) {
2302 setproctitle("[stopped mux]");
2306 /* client specific fatal cleanup */
2310 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2311 leave_non_blocking();
2312 if (options.control_path != NULL && muxserver_sock != -1)
2313 unlink(options.control_path);
2314 ssh_kill_proxy_command();