1 /* $OpenBSD: clientloop.c,v 1.311 2018/02/11 21:16:56 dtucker 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;
216 * Signal handler for signals that cause the program to terminate. These
217 * signals must be trapped to restore terminal modes.
221 signal_handler(int sig)
223 received_signal = sig;
228 * Sets control_persist_exit_time to the absolute time when the
229 * backgrounded control master should exit due to expiry of the
230 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
231 * control master process, or if there is no ControlPersist timeout.
234 set_control_persist_exit_time(struct ssh *ssh)
236 if (muxserver_sock == -1 || !options.control_persist
237 || options.control_persist_timeout == 0) {
238 /* not using a ControlPersist timeout */
239 control_persist_exit_time = 0;
240 } else if (channel_still_open(ssh)) {
241 /* some client connections are still open */
242 if (control_persist_exit_time > 0)
243 debug2("%s: cancel scheduled exit", __func__);
244 control_persist_exit_time = 0;
245 } else if (control_persist_exit_time <= 0) {
246 /* a client connection has recently closed */
247 control_persist_exit_time = monotime() +
248 (time_t)options.control_persist_timeout;
249 debug2("%s: schedule exit in %d seconds", __func__,
250 options.control_persist_timeout);
252 /* else we are already counting down to the timeout */
255 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
257 client_x11_display_valid(const char *display)
264 dlen = strlen(display);
265 for (i = 0; i < dlen; i++) {
266 if (!isalnum((u_char)display[i]) &&
267 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
268 debug("Invalid character '%c' in DISPLAY", display[i]);
275 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
276 #define X11_TIMEOUT_SLACK 60
278 client_x11_get_proto(struct ssh *ssh, const char *display,
279 const char *xauth_path, u_int trusted, u_int timeout,
280 char **_proto, char **_data)
282 char cmd[1024], line[512], xdisplay[512];
283 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
284 static char proto[512], data[512];
286 int got_data = 0, generated = 0, do_unlink = 0, r;
288 u_int now, x11_timeout_real;
292 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
294 if (!client_x11_display_valid(display)) {
296 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
300 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
301 debug("No xauth program.");
305 if (xauth_path != NULL) {
307 * Handle FamilyLocal case where $DISPLAY does
308 * not match an authorization entry. For this we
309 * just try "xauth list unix:displaynum.screennum".
310 * XXX: "localhost" match to determine FamilyLocal
313 if (strncmp(display, "localhost:", 10) == 0) {
314 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
315 display + 10)) < 0 ||
316 (size_t)r >= sizeof(xdisplay)) {
317 error("%s: display name too long", __func__);
324 * Generate an untrusted X11 auth cookie.
326 * The authentication cookie should briefly outlive
327 * ssh's willingness to forward X11 connections to
328 * avoid nasty fail-open behaviour in the X server.
330 mktemp_proto(xauthdir, sizeof(xauthdir));
331 if (mkdtemp(xauthdir) == NULL) {
332 error("%s: mkdtemp: %s",
333 __func__, strerror(errno));
337 if ((r = snprintf(xauthfile, sizeof(xauthfile),
338 "%s/xauthfile", xauthdir)) < 0 ||
339 (size_t)r >= sizeof(xauthfile)) {
340 error("%s: xauthfile path too long", __func__);
346 if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
347 x11_timeout_real = UINT_MAX;
349 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
350 if ((r = snprintf(cmd, sizeof(cmd),
351 "%s -f %s generate %s " SSH_X11_PROTO
352 " untrusted timeout %u 2>" _PATH_DEVNULL,
353 xauth_path, xauthfile, display,
354 x11_timeout_real)) < 0 ||
355 (size_t)r >= sizeof(cmd))
356 fatal("%s: cmd too long", __func__);
357 debug2("%s: %s", __func__, cmd);
358 if (x11_refuse_time == 0) {
359 now = monotime() + 1;
360 if (UINT_MAX - timeout < now)
361 x11_refuse_time = UINT_MAX;
363 x11_refuse_time = now + timeout;
364 channel_set_x11_refuse_time(ssh,
367 if (system(cmd) == 0)
372 * When in untrusted mode, we read the cookie only if it was
373 * successfully generated as an untrusted one in the step
376 if (trusted || generated) {
377 snprintf(cmd, sizeof(cmd),
378 "%s %s%s list %s 2>" _PATH_DEVNULL,
380 generated ? "-f " : "" ,
381 generated ? xauthfile : "",
383 debug2("x11_get_proto: %s", cmd);
385 if (f && fgets(line, sizeof(line), f) &&
386 sscanf(line, "%*s %511s %511s", proto, data) == 2)
398 /* Don't fall back to fake X11 data for untrusted forwarding */
399 if (!trusted && !got_data) {
400 error("Warning: untrusted X11 forwarding setup failed: "
401 "xauth key data not generated");
406 * If we didn't get authentication data, just make up some
407 * data. The forwarding code will check the validity of the
408 * response anyway, and substitute this data. The X11
409 * server, however, will ignore this fake data and use
410 * whatever authentication mechanisms it was using otherwise
411 * for the local connection.
417 logit("Warning: No xauth data; "
418 "using fake authentication data for X11 forwarding.");
419 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
420 arc4random_buf(rnd, sizeof(rnd));
421 for (i = 0; i < sizeof(rnd); i++) {
422 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
431 * Checks if the client window has changed, and sends a packet about it to
432 * the server if so. The actual change is detected elsewhere (by a software
433 * interrupt on Unix); this just checks the flag and sends a message if
438 client_check_window_change(struct ssh *ssh)
440 if (!received_window_change_signal)
443 received_window_change_signal = 0;
445 debug2("%s: changed", __func__);
447 channel_send_window_changes(ssh);
451 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
453 struct global_confirm *gc;
455 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
458 gc->cb(ssh, type, seq, gc->ctx);
459 if (--gc->ref_count <= 0) {
460 TAILQ_REMOVE(&global_confirms, gc, entry);
461 explicit_bzero(gc, sizeof(*gc));
465 packet_set_alive_timeouts(0);
470 server_alive_check(void)
472 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
473 logit("Timeout, server %s not responding.", host);
476 packet_start(SSH2_MSG_GLOBAL_REQUEST);
477 packet_put_cstring("keepalive@openssh.com");
478 packet_put_char(1); /* boolean: want reply */
480 /* Insert an empty placeholder to maintain ordering */
481 client_register_global_confirm(NULL, NULL);
485 * Waits until the client can do something (some data becomes available on
486 * one of the file descriptors).
489 client_wait_until_can_do_something(struct ssh *ssh,
490 fd_set **readsetp, fd_set **writesetp,
491 int *maxfdp, u_int *nallocp, int rekeying)
493 struct timeval tv, *tvp;
495 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
498 /* Add any selections by the channel mechanism. */
499 channel_prepare_select(active_state, readsetp, writesetp, maxfdp,
500 nallocp, &minwait_secs);
502 /* channel_prepare_select could have closed the last channel */
503 if (session_closed && !channel_still_open(ssh) &&
504 !packet_have_data_to_write()) {
505 /* clear mask since we did not call select() */
506 memset(*readsetp, 0, *nallocp);
507 memset(*writesetp, 0, *nallocp);
511 FD_SET(connection_in, *readsetp);
513 /* Select server connection if have data to write to the server. */
514 if (packet_have_data_to_write())
515 FD_SET(connection_out, *writesetp);
518 * Wait for something to happen. This will suspend the process until
519 * some selected descriptor can be read, written, or has some other
520 * event pending, or a timeout expires.
523 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
524 if (options.server_alive_interval > 0) {
525 timeout_secs = options.server_alive_interval;
526 server_alive_time = now + options.server_alive_interval;
528 if (options.rekey_interval > 0 && !rekeying)
529 timeout_secs = MINIMUM(timeout_secs, packet_get_rekey_timeout());
530 set_control_persist_exit_time(ssh);
531 if (control_persist_exit_time > 0) {
532 timeout_secs = MINIMUM(timeout_secs,
533 control_persist_exit_time - now);
534 if (timeout_secs < 0)
537 if (minwait_secs != 0)
538 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
539 if (timeout_secs == INT_MAX)
542 tv.tv_sec = timeout_secs;
547 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
552 * We have to clear the select masks, because we return.
553 * We have to return, because the mainloop checks for the flags
554 * set by the signal handlers.
556 memset(*readsetp, 0, *nallocp);
557 memset(*writesetp, 0, *nallocp);
561 /* Note: we might still have data in the buffers. */
562 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
563 buffer_append(&stderr_buffer, buf, strlen(buf));
565 } else if (ret == 0) {
567 * Timeout. Could have been either keepalive or rekeying.
568 * Keepalive we check here, rekeying is checked in clientloop.
570 if (server_alive_time != 0 && server_alive_time <= monotime())
571 server_alive_check();
577 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
579 /* Flush stdout and stderr buffers. */
580 if (buffer_len(bout) > 0)
581 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
583 if (buffer_len(berr) > 0)
584 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
587 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
593 /* Send the suspend signal to the program itself. */
594 kill(getpid(), SIGTSTP);
596 /* Reset window sizes in case they have changed */
597 received_window_change_signal = 1;
599 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
603 client_process_net_input(fd_set *readset)
606 char buf[SSH_IOBUFSZ];
609 * Read input from the server, and add any such data to the buffer of
610 * the packet subsystem.
612 if (FD_ISSET(connection_in, readset)) {
613 /* Read as much as possible. */
614 len = read(connection_in, buf, sizeof(buf));
617 * Received EOF. The remote host has closed the
620 snprintf(buf, sizeof buf,
621 "Connection to %.300s closed by remote host.\r\n",
623 buffer_append(&stderr_buffer, buf, strlen(buf));
628 * There is a kernel bug on Solaris that causes select to
629 * sometimes wake up even though there is no data available.
632 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
637 * An error has encountered. Perhaps there is a
640 snprintf(buf, sizeof buf,
641 "Read from remote host %.300s: %.100s\r\n",
642 host, strerror(errno));
643 buffer_append(&stderr_buffer, buf, strlen(buf));
647 packet_process_incoming(buf, len);
652 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
654 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
659 * If a TTY was explicitly requested, then a failure to allocate
662 if (cr->action == CONFIRM_TTY &&
663 (options.request_tty == REQUEST_TTY_FORCE ||
664 options.request_tty == REQUEST_TTY_YES))
665 cr->action = CONFIRM_CLOSE;
667 /* XXX supress on mux _client_ quietmode */
668 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
669 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
671 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
672 debug2("%s request accepted on channel %d",
673 cr->request_type, c->self);
674 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
676 snprintf(errmsg, sizeof(errmsg),
677 "%s request failed\r\n", cr->request_type);
679 snprintf(errmsg, sizeof(errmsg),
680 "%s request failed on channel %d",
681 cr->request_type, c->self);
683 /* If error occurred on primary session channel, then exit */
684 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
687 * If error occurred on mux client, append to
691 buffer_append(c->extended, errmsg, strlen(errmsg));
694 if (cr->action == CONFIRM_TTY) {
696 * If a TTY allocation error occurred, then arrange
697 * for the correct TTY to leave raw mode.
699 if (c->self == session_ident)
702 mux_tty_alloc_failed(ssh, c);
703 } else if (cr->action == CONFIRM_CLOSE) {
704 chan_read_failed(ssh, c);
705 chan_write_failed(ssh, c);
712 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
718 client_expect_confirm(struct ssh *ssh, int id, const char *request,
719 enum confirm_action action)
721 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
723 cr->request_type = request;
726 channel_register_status_confirm(ssh, id, client_status_confirm,
727 client_abandon_status_confirm, cr);
731 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
733 struct global_confirm *gc, *last_gc;
735 /* Coalesce identical callbacks */
736 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
737 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
738 if (++last_gc->ref_count >= INT_MAX)
739 fatal("%s: last_gc->ref_count = %d",
740 __func__, last_gc->ref_count);
744 gc = xcalloc(1, sizeof(*gc));
748 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
752 process_cmdline(struct ssh *ssh)
754 void (*handler)(int);
756 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
759 memset(&fwd, 0, sizeof(fwd));
761 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
762 handler = signal(SIGINT, SIG_IGN);
763 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
766 while (isspace((u_char)*s))
769 s++; /* Skip cmdline '-', if any */
773 if (*s == 'h' || *s == 'H' || *s == '?') {
775 logit(" -L[bind_address:]port:host:hostport "
776 "Request local forward");
777 logit(" -R[bind_address:]port:host:hostport "
778 "Request remote forward");
779 logit(" -D[bind_address:]port "
780 "Request dynamic forward");
781 logit(" -KL[bind_address:]port "
782 "Cancel local forward");
783 logit(" -KR[bind_address:]port "
784 "Cancel remote forward");
785 logit(" -KD[bind_address:]port "
786 "Cancel dynamic forward");
787 if (!options.permit_local_command)
790 "Execute local command");
794 if (*s == '!' && options.permit_local_command) {
811 logit("Invalid command.");
815 while (isspace((u_char)*++s))
818 /* XXX update list of forwards in options */
820 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
821 if (!parse_forward(&fwd, s, 1, 0)) {
822 logit("Bad forwarding close specification.");
826 ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
828 ok = channel_cancel_lport_listener(ssh, &fwd,
829 0, &options.fwd_opts) > 0;
831 ok = channel_cancel_lport_listener(ssh, &fwd,
832 CHANNEL_CANCEL_PORT_STATIC,
833 &options.fwd_opts) > 0;
835 logit("Unknown port forwarding.");
838 logit("Canceled forwarding.");
840 if (!parse_forward(&fwd, s, dynamic, remote)) {
841 logit("Bad forwarding specification.");
844 if (local || dynamic) {
845 if (!channel_setup_local_fwd_listener(ssh, &fwd,
846 &options.fwd_opts)) {
847 logit("Port forwarding failed.");
851 if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
852 logit("Port forwarding failed.");
856 logit("Forwarding port.");
860 signal(SIGINT, handler);
861 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
863 free(fwd.listen_host);
864 free(fwd.listen_path);
865 free(fwd.connect_host);
866 free(fwd.connect_path);
869 /* reasons to suppress output of an escape command in help output */
870 #define SUPPRESS_NEVER 0 /* never suppress, always show */
871 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
872 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
873 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
874 struct escape_help_text {
879 static struct escape_help_text esc_txt[] = {
880 {".", "terminate session", SUPPRESS_MUXMASTER},
881 {".", "terminate connection (and any multiplexed sessions)",
883 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
884 {"C", "open a command line", SUPPRESS_MUXCLIENT},
885 {"R", "request rekey", SUPPRESS_NEVER},
886 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
887 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
888 {"#", "list forwarded connections", SUPPRESS_NEVER},
889 {"&", "background ssh (when waiting for connections to terminate)",
891 {"?", "this message", SUPPRESS_NEVER},
895 print_escape_help(Buffer *b, int escape_char, int mux_client, int using_stderr)
897 unsigned int i, suppress_flags;
900 snprintf(string, sizeof string, "%c?\r\n"
901 "Supported escape sequences:\r\n", escape_char);
902 buffer_append(b, string, strlen(string));
905 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
906 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
907 (using_stderr ? 0 : SUPPRESS_SYSLOG);
909 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
910 if (esc_txt[i].flags & suppress_flags)
912 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
913 escape_char, esc_txt[i].cmd, esc_txt[i].text);
914 buffer_append(b, string, strlen(string));
917 snprintf(string, sizeof string,
918 " %c%c - send the escape character by typing it twice\r\n"
919 "(Note that escapes are only recognized immediately after "
920 "newline.)\r\n", escape_char, escape_char);
921 buffer_append(b, string, strlen(string));
925 * Process the characters one by one.
928 process_escapes(struct ssh *ssh, Channel *c,
929 Buffer *bin, Buffer *bout, Buffer *berr,
938 struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
939 NULL : (struct escape_filter_ctx *)c->filter_ctx;
941 if (c->filter_ctx == NULL)
947 for (i = 0; i < (u_int)len; i++) {
948 /* Get one character at a time. */
951 if (efc->escape_pending) {
952 /* We have previously seen an escape character. */
953 /* Clear the flag now. */
954 efc->escape_pending = 0;
956 /* Process the escaped character. */
959 /* Terminate the connection. */
960 snprintf(string, sizeof string, "%c.\r\n",
962 buffer_append(berr, string, strlen(string));
964 if (c && c->ctl_chan != -1) {
965 chan_read_failed(ssh, c);
966 chan_write_failed(ssh, c);
967 if (c->detach_user) {
971 c->type = SSH_CHANNEL_ABANDONED;
972 buffer_clear(c->input);
973 chan_ibuf_empty(ssh, c);
980 /* XXX support this for mux clients */
981 if (c && c->ctl_chan != -1) {
985 snprintf(b, sizeof b, "^Z");
987 snprintf(b, sizeof b, "%c", ch);
988 snprintf(string, sizeof string,
989 "%c%s escape not available to "
990 "multiplexed sessions\r\n",
991 efc->escape_char, b);
992 buffer_append(berr, string,
996 /* Suspend the program. Inform the user */
997 snprintf(string, sizeof string,
998 "%c^Z [suspend ssh]\r\n", efc->escape_char);
999 buffer_append(berr, string, strlen(string));
1001 /* Restore terminal modes and suspend. */
1002 client_suspend_self(bin, bout, berr);
1004 /* We have been continued. */
1008 snprintf(string, sizeof string,
1009 "%cB\r\n", efc->escape_char);
1010 buffer_append(berr, string, strlen(string));
1011 channel_request_start(ssh, c->self, "break", 0);
1012 packet_put_int(1000);
1017 if (datafellows & SSH_BUG_NOREKEY)
1018 logit("Server does not "
1019 "support re-keying");
1027 if (c && c->ctl_chan != -1)
1029 if (!log_is_on_stderr()) {
1030 snprintf(string, sizeof string,
1031 "%c%c [Logging to syslog]\r\n",
1032 efc->escape_char, ch);
1033 buffer_append(berr, string,
1037 if (ch == 'V' && options.log_level >
1039 log_change_level(--options.log_level);
1040 if (ch == 'v' && options.log_level <
1041 SYSLOG_LEVEL_DEBUG3)
1042 log_change_level(++options.log_level);
1043 snprintf(string, sizeof string,
1044 "%c%c [LogLevel %s]\r\n",
1045 efc->escape_char, ch,
1046 log_level_name(options.log_level));
1047 buffer_append(berr, string, strlen(string));
1051 if (c && c->ctl_chan != -1)
1054 * Detach the program (continue to serve
1055 * connections, but put in background and no
1056 * more new connections).
1058 /* Restore tty modes. */
1060 options.request_tty == REQUEST_TTY_FORCE);
1062 /* Stop listening for new connections. */
1063 channel_stop_listening(ssh);
1065 snprintf(string, sizeof string,
1066 "%c& [backgrounded]\n", efc->escape_char);
1067 buffer_append(berr, string, strlen(string));
1069 /* Fork into background. */
1072 error("fork: %.100s", strerror(errno));
1075 if (pid != 0) { /* This is the parent. */
1076 /* The parent just exits. */
1079 /* The child continues serving connections. */
1080 buffer_append(bin, "\004", 1);
1081 /* fake EOF on stdin */
1084 print_escape_help(berr, efc->escape_char,
1085 (c && c->ctl_chan != -1),
1086 log_is_on_stderr());
1090 snprintf(string, sizeof string, "%c#\r\n",
1092 buffer_append(berr, string, strlen(string));
1093 s = channel_open_message(ssh);
1094 buffer_append(berr, s, strlen(s));
1099 if (c && c->ctl_chan != -1)
1101 process_cmdline(ssh);
1105 if (ch != efc->escape_char) {
1106 buffer_put_char(bin, efc->escape_char);
1109 /* Escaped characters fall through here */
1114 * The previous character was not an escape char.
1115 * Check if this is an escape.
1117 if (last_was_cr && ch == efc->escape_char) {
1119 * It is. Set the flag and continue to
1122 efc->escape_pending = 1;
1128 * Normal character. Record whether it was a newline,
1129 * and append it to the buffer.
1131 last_was_cr = (ch == '\r' || ch == '\n');
1132 buffer_put_char(bin, ch);
1139 * Get packets from the connection input buffer, and process them as long as
1140 * there are packets available.
1142 * Any unknown packets received during the actual
1143 * session cause the session to terminate. This is
1144 * intended to make debugging easier since no
1145 * confirmations are sent. Any compatible protocol
1146 * extensions must be negotiated during the
1147 * preparatory phase.
1151 client_process_buffered_input_packets(void)
1153 ssh_dispatch_run_fatal(active_state, DISPATCH_NONBLOCK, &quit_pending);
1156 /* scan buf[] for '~' before sending data to the peer */
1158 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1160 client_new_escape_filter_ctx(int escape_char)
1162 struct escape_filter_ctx *ret;
1164 ret = xcalloc(1, sizeof(*ret));
1165 ret->escape_pending = 0;
1166 ret->escape_char = escape_char;
1170 /* Free the escape filter context on channel free */
1172 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1178 client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1180 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1183 return process_escapes(ssh, c, c->input, c->output, c->extended,
1188 client_channel_closed(struct ssh *ssh, int id, void *arg)
1190 channel_cancel_cleanup(ssh, id);
1192 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1196 * Implements the interactive session with the server. This is called after
1197 * the user has been authenticated, and a command has been started on the
1198 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1199 * used as an escape character for terminating or suspending the session.
1202 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1205 fd_set *readset = NULL, *writeset = NULL;
1206 double start_time, total_time;
1207 int r, max_fd = 0, max_fd2 = 0, len;
1208 u_int64_t ibytes, obytes;
1212 debug("Entering interactive session.");
1214 if (options.control_master &&
1215 !option_clear_or_none(options.control_path)) {
1216 debug("pledge: id");
1217 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
1219 fatal("%s pledge(): %s", __func__, strerror(errno));
1221 } else if (options.forward_x11 || options.permit_local_command) {
1222 debug("pledge: exec");
1223 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1225 fatal("%s pledge(): %s", __func__, strerror(errno));
1227 } else if (options.update_hostkeys) {
1228 debug("pledge: filesystem full");
1229 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1231 fatal("%s pledge(): %s", __func__, strerror(errno));
1233 } else if (!option_clear_or_none(options.proxy_command) ||
1234 fork_after_authentication_flag) {
1235 debug("pledge: proc");
1236 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1237 fatal("%s pledge(): %s", __func__, strerror(errno));
1240 debug("pledge: network");
1241 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1242 fatal("%s pledge(): %s", __func__, strerror(errno));
1245 start_time = monotime_double();
1247 /* Initialize variables. */
1250 connection_in = packet_get_connection_in();
1251 connection_out = packet_get_connection_out();
1252 max_fd = MAXIMUM(connection_in, connection_out);
1256 /* Initialize buffers. */
1257 buffer_init(&stderr_buffer);
1259 client_init_dispatch();
1262 * Set signal handlers, (e.g. to restore non-blocking mode)
1263 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1265 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1266 signal(SIGHUP, signal_handler);
1267 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1268 signal(SIGINT, signal_handler);
1269 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1270 signal(SIGQUIT, signal_handler);
1271 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1272 signal(SIGTERM, signal_handler);
1273 signal(SIGWINCH, window_change_handler);
1276 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1278 session_ident = ssh2_chan_id;
1279 if (session_ident != -1) {
1280 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1281 channel_register_filter(ssh, session_ident,
1282 client_simple_escape_filter, NULL,
1283 client_filter_cleanup,
1284 client_new_escape_filter_ctx(
1287 channel_register_cleanup(ssh, session_ident,
1288 client_channel_closed, 0);
1291 /* Main loop of the client for the interactive session mode. */
1292 while (!quit_pending) {
1294 /* Process buffered packets sent by the server. */
1295 client_process_buffered_input_packets();
1297 if (session_closed && !channel_still_open(ssh))
1300 if (ssh_packet_is_rekeying(ssh)) {
1301 debug("rekeying in progress");
1302 } else if (need_rekeying) {
1303 /* manual rekey request */
1304 debug("need rekeying");
1305 if ((r = kex_start_rekex(ssh)) != 0)
1306 fatal("%s: kex_start_rekex: %s", __func__,
1311 * Make packets from buffered channel data, and
1312 * enqueue them for sending to the server.
1314 if (packet_not_very_much_data_to_write())
1315 channel_output_poll(ssh);
1318 * Check if the window size has changed, and buffer a
1319 * message about it to the server if so.
1321 client_check_window_change(ssh);
1327 * Wait until we have something to do (something becomes
1328 * available on one of the descriptors).
1331 client_wait_until_can_do_something(ssh, &readset, &writeset,
1332 &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
1337 /* Do channel operations unless rekeying in progress. */
1338 if (!ssh_packet_is_rekeying(ssh))
1339 channel_after_select(ssh, readset, writeset);
1341 /* Buffer input from the connection. */
1342 client_process_net_input(readset);
1348 * Send as much buffered packet data as possible to the
1351 if (FD_ISSET(connection_out, writeset))
1352 packet_write_poll();
1355 * If we are a backgrounded control master, and the
1356 * timeout has expired without any active client
1357 * connections, then quit.
1359 if (control_persist_exit_time > 0) {
1360 if (monotime() >= control_persist_exit_time) {
1361 debug("ControlPersist timeout expired");
1369 /* Terminate the session. */
1371 /* Stop watching for window change. */
1372 signal(SIGWINCH, SIG_DFL);
1374 packet_start(SSH2_MSG_DISCONNECT);
1375 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1376 packet_put_cstring("disconnected by user");
1377 packet_put_cstring(""); /* language tag */
1379 packet_write_wait();
1381 channel_free_all(ssh);
1384 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1386 /* restore blocking io */
1387 if (!isatty(fileno(stdin)))
1388 unset_nonblock(fileno(stdin));
1389 if (!isatty(fileno(stdout)))
1390 unset_nonblock(fileno(stdout));
1391 if (!isatty(fileno(stderr)))
1392 unset_nonblock(fileno(stderr));
1395 * If there was no shell or command requested, there will be no remote
1396 * exit status to be returned. In that case, clear error code if the
1397 * connection was deliberately terminated at this end.
1399 if (no_shell_flag && received_signal == SIGTERM) {
1400 received_signal = 0;
1404 if (received_signal) {
1405 verbose("Killed by signal %d.", (int) received_signal);
1410 * In interactive mode (with pseudo tty) display a message indicating
1411 * that the connection has been closed.
1413 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1414 snprintf(buf, sizeof buf,
1415 "Connection to %.64s closed.\r\n", host);
1416 buffer_append(&stderr_buffer, buf, strlen(buf));
1419 /* Output any buffered data for stderr. */
1420 if (buffer_len(&stderr_buffer) > 0) {
1421 len = atomicio(vwrite, fileno(stderr),
1422 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1423 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1424 error("Write failed flushing stderr buffer.");
1426 buffer_consume(&stderr_buffer, len);
1429 /* Clear and free any buffers. */
1430 explicit_bzero(buf, sizeof(buf));
1431 buffer_free(&stderr_buffer);
1433 /* Report bytes transferred, and transfer rates. */
1434 total_time = monotime_double() - start_time;
1435 packet_get_bytes(&ibytes, &obytes);
1436 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1437 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1439 verbose("Bytes per second: sent %.1f, received %.1f",
1440 obytes / total_time, ibytes / total_time);
1441 /* Return the exit status of the program. */
1442 debug("Exit status %d", exit_status);
1449 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1450 int rchan, u_int rwindow, u_int rmaxpack)
1453 struct sshbuf *b = NULL;
1454 char *listen_address, *originator_address;
1455 u_short listen_port, originator_port;
1458 /* Get rest of the packet */
1459 listen_address = packet_get_string(NULL);
1460 listen_port = packet_get_int();
1461 originator_address = packet_get_string(NULL);
1462 originator_port = packet_get_int();
1465 debug("%s: listen %s port %d, originator %s port %d", __func__,
1466 listen_address, listen_port, originator_address, originator_port);
1468 c = channel_connect_by_listen_address(ssh, listen_address, listen_port,
1469 "forwarded-tcpip", originator_address);
1471 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1472 if ((b = sshbuf_new()) == NULL) {
1473 error("%s: alloc reply", __func__);
1476 /* reconstruct and send to muxclient */
1477 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1478 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1479 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1480 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1481 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1482 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1483 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1484 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1485 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1486 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1487 (r = sshbuf_put_stringb(c->output, b)) != 0) {
1488 error("%s: compose for muxclient %s", __func__,
1496 free(originator_address);
1497 free(listen_address);
1502 client_request_forwarded_streamlocal(struct ssh *ssh,
1503 const char *request_type, int rchan)
1508 /* Get the remote path. */
1509 listen_path = packet_get_string(NULL);
1510 /* XXX: Skip reserved field for now. */
1511 if (packet_get_string_ptr(NULL) == NULL)
1512 fatal("%s: packet_get_string_ptr failed", __func__);
1515 debug("%s: %s", __func__, listen_path);
1517 c = channel_connect_by_listen_path(ssh, listen_path,
1518 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1524 client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1528 u_short originator_port;
1531 if (!options.forward_x11) {
1532 error("Warning: ssh server tried X11 forwarding.");
1533 error("Warning: this is probably a break-in attempt by a "
1534 "malicious server.");
1537 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1538 verbose("Rejected X11 connection after ForwardX11Timeout "
1542 originator = packet_get_string(NULL);
1543 originator_port = packet_get_int();
1545 /* XXX check permission */
1546 debug("client_request_x11: request from %s %d", originator,
1549 sock = x11_connect_display(ssh);
1552 c = channel_new(ssh, "x11",
1553 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1554 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1560 client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1565 if (!options.forward_agent) {
1566 error("Warning: ssh server tried agent forwarding.");
1567 error("Warning: this is probably a break-in attempt by a "
1568 "malicious server.");
1571 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1572 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1573 debug("%s: ssh_get_authentication_socket: %s",
1574 __func__, ssh_err(r));
1577 c = channel_new(ssh, "authentication agent connection",
1578 SSH_CHANNEL_OPEN, sock, sock, -1,
1579 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1580 "authentication agent connection", 1);
1586 client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1587 int local_tun, int remote_tun)
1591 char *ifname = NULL;
1593 if (tun_mode == SSH_TUNMODE_NO)
1596 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1598 /* Open local tunnel device */
1599 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1600 error("Tunnel device open failed.");
1603 debug("Tunnel forwarding using interface %s", ifname);
1605 c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1606 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1609 #if defined(SSH_TUN_FILTER)
1610 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1611 channel_register_filter(ssh, c->self, sys_tun_infilter,
1612 sys_tun_outfilter, NULL, NULL);
1615 packet_start(SSH2_MSG_CHANNEL_OPEN);
1616 packet_put_cstring("tun@openssh.com");
1617 packet_put_int(c->self);
1618 packet_put_int(c->local_window_max);
1619 packet_put_int(c->local_maxpacket);
1620 packet_put_int(tun_mode);
1621 packet_put_int(remote_tun);
1627 /* XXXX move to generic input handler */
1629 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1634 u_int rmaxpack, rwindow, len;
1636 ctype = packet_get_string(&len);
1637 rchan = packet_get_int();
1638 rwindow = packet_get_int();
1639 rmaxpack = packet_get_int();
1641 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1642 ctype, rchan, rwindow, rmaxpack);
1644 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1645 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1647 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1648 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1649 } else if (strcmp(ctype, "x11") == 0) {
1650 c = client_request_x11(ssh, ctype, rchan);
1651 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1652 c = client_request_agent(ssh, ctype, rchan);
1654 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1655 debug3("proxied to downstream: %s", ctype);
1656 } else if (c != NULL) {
1657 debug("confirm %s", ctype);
1658 c->remote_id = rchan;
1659 c->have_remote_id = 1;
1660 c->remote_window = rwindow;
1661 c->remote_maxpacket = rmaxpack;
1662 if (c->type != SSH_CHANNEL_CONNECTING) {
1663 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1664 packet_put_int(c->remote_id);
1665 packet_put_int(c->self);
1666 packet_put_int(c->local_window);
1667 packet_put_int(c->local_maxpacket);
1671 debug("failure %s", ctype);
1672 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1673 packet_put_int(rchan);
1674 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1675 packet_put_cstring("open failed");
1676 packet_put_cstring("");
1684 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1687 int exitval, id, reply, success = 0;
1690 id = packet_get_int();
1691 c = channel_lookup(ssh, id);
1692 if (channel_proxy_upstream(c, type, seq, ssh))
1694 rtype = packet_get_string(NULL);
1695 reply = packet_get_char();
1697 debug("client_input_channel_req: channel %d rtype %s reply %d",
1701 error("client_input_channel_req: request for channel -1");
1702 } else if (c == NULL) {
1703 error("client_input_channel_req: channel %d: "
1704 "unknown channel", id);
1705 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1707 chan_rcvd_eow(ssh, c);
1708 } else if (strcmp(rtype, "exit-status") == 0) {
1709 exitval = packet_get_int();
1710 if (c->ctl_chan != -1) {
1711 mux_exit_message(ssh, c, exitval);
1713 } else if (id == session_ident) {
1714 /* Record exit value of local session */
1716 exit_status = exitval;
1718 /* Probably for a mux channel that has already closed */
1719 debug("%s: no sink for exit-status on channel %d",
1724 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1725 if (!c->have_remote_id)
1726 fatal("%s: channel %d: no remote_id",
1728 packet_start(success ?
1729 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1730 packet_put_int(c->remote_id);
1737 struct hostkeys_update_ctx {
1738 /* The hostname and (optionally) IP address string for the server */
1739 char *host_str, *ip_str;
1742 * Keys received from the server and a flag for each indicating
1743 * whether they already exist in known_hosts.
1744 * keys_seen is filled in by hostkeys_find() and later (for new
1745 * keys) by client_global_hostkeys_private_confirm().
1747 struct sshkey **keys;
1752 * Keys that are in known_hosts, but were not present in the update
1753 * from the server (i.e. scheduled to be deleted).
1754 * Filled in by hostkeys_find().
1756 struct sshkey **old_keys;
1761 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
1767 for (i = 0; i < ctx->nkeys; i++)
1768 sshkey_free(ctx->keys[i]);
1770 free(ctx->keys_seen);
1771 for (i = 0; i < ctx->nold; i++)
1772 sshkey_free(ctx->old_keys[i]);
1773 free(ctx->old_keys);
1774 free(ctx->host_str);
1780 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
1782 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1784 struct sshkey **tmp;
1786 if (l->status != HKF_STATUS_MATCHED || l->key == NULL)
1789 /* Mark off keys we've already seen for this host */
1790 for (i = 0; i < ctx->nkeys; i++) {
1791 if (sshkey_equal(l->key, ctx->keys[i])) {
1792 debug3("%s: found %s key at %s:%ld", __func__,
1793 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
1794 ctx->keys_seen[i] = 1;
1798 /* This line contained a key that not offered by the server */
1799 debug3("%s: deprecated %s key at %s:%ld", __func__,
1800 sshkey_ssh_name(l->key), l->path, l->linenum);
1801 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1802 sizeof(*ctx->old_keys))) == NULL)
1803 fatal("%s: recallocarray failed nold = %zu",
1804 __func__, ctx->nold);
1805 ctx->old_keys = tmp;
1806 ctx->old_keys[ctx->nold++] = l->key;
1813 update_known_hosts(struct hostkeys_update_ctx *ctx)
1816 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
1817 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1818 char *fp, *response;
1821 for (i = 0; i < ctx->nkeys; i++) {
1822 if (ctx->keys_seen[i] != 2)
1824 if ((fp = sshkey_fingerprint(ctx->keys[i],
1825 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1826 fatal("%s: sshkey_fingerprint failed", __func__);
1827 do_log2(loglevel, "Learned new hostkey: %s %s",
1828 sshkey_type(ctx->keys[i]), fp);
1831 for (i = 0; i < ctx->nold; i++) {
1832 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
1833 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1834 fatal("%s: sshkey_fingerprint failed", __func__);
1835 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
1836 sshkey_type(ctx->old_keys[i]), fp);
1839 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1840 if (get_saved_tio() != NULL) {
1845 for (i = 0; !quit_pending && i < 3; i++) {
1847 response = read_passphrase("Accept updated hostkeys? "
1848 "(yes/no): ", RP_ECHO);
1849 if (strcasecmp(response, "yes") == 0)
1851 else if (quit_pending || response == NULL ||
1852 strcasecmp(response, "no") == 0) {
1853 options.update_hostkeys = 0;
1856 do_log2(loglevel, "Please enter "
1857 "\"yes\" or \"no\"");
1860 if (quit_pending || i >= 3 || response == NULL)
1861 options.update_hostkeys = 0;
1868 * Now that all the keys are verified, we can go ahead and replace
1869 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
1870 * cancel the operation).
1872 if (options.update_hostkeys != 0 &&
1873 (r = hostfile_replace_entries(options.user_hostfiles[0],
1874 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
1875 options.hash_known_hosts, 0,
1876 options.fingerprint_hash)) != 0)
1877 error("%s: hostfile_replace_entries failed: %s",
1878 __func__, ssh_err(r));
1882 client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
1883 u_int32_t seq, void *_ctx)
1885 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1887 struct sshbuf *signdata;
1888 int r, kexsigtype, use_kexsigtype;
1893 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
1894 if (type != SSH2_MSG_REQUEST_SUCCESS) {
1895 error("Server failed to confirm ownership of "
1896 "private host keys");
1897 hostkeys_update_ctx_free(ctx);
1900 kexsigtype = sshkey_type_plain(
1901 sshkey_type_from_name(ssh->kex->hostkey_alg));
1903 if ((signdata = sshbuf_new()) == NULL)
1904 fatal("%s: sshbuf_new failed", __func__);
1905 /* Don't want to accidentally accept an unbound signature */
1906 if (ssh->kex->session_id_len == 0)
1907 fatal("%s: ssh->kex->session_id_len == 0", __func__);
1909 * Expect a signature for each of the ctx->nnew private keys we
1910 * haven't seen before. They will be in the same order as the
1911 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
1913 for (ndone = i = 0; i < ctx->nkeys; i++) {
1914 if (ctx->keys_seen[i])
1916 /* Prepare data to be signed: session ID, unique string, key */
1917 sshbuf_reset(signdata);
1918 if ( (r = sshbuf_put_cstring(signdata,
1919 "hostkeys-prove-00@openssh.com")) != 0 ||
1920 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
1921 ssh->kex->session_id_len)) != 0 ||
1922 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1923 fatal("%s: failed to prepare signature: %s",
1924 __func__, ssh_err(r));
1925 /* Extract and verify signature */
1926 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1927 error("%s: couldn't parse message: %s",
1928 __func__, ssh_err(r));
1932 * For RSA keys, prefer to use the signature type negotiated
1933 * during KEX to the default (SHA1).
1935 use_kexsigtype = kexsigtype == KEY_RSA &&
1936 sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA;
1937 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1938 sshbuf_ptr(signdata), sshbuf_len(signdata),
1939 use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0)) != 0) {
1940 error("%s: server gave bad signature for %s key %zu",
1941 __func__, sshkey_type(ctx->keys[i]), i);
1944 /* Key is good. Mark it as 'seen' */
1945 ctx->keys_seen[i] = 2;
1948 if (ndone != ctx->nnew)
1949 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
1950 ndone, ctx->nnew); /* Shouldn't happen */
1951 ssh_packet_check_eom(ssh);
1953 /* Make the edits to known_hosts */
1954 update_known_hosts(ctx);
1956 hostkeys_update_ctx_free(ctx);
1960 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
1961 * Made slightly less trivial by the multiple RSA signature algorithm names.
1964 key_accepted_by_hostkeyalgs(const struct sshkey *key)
1966 const char *ktype = sshkey_ssh_name(key);
1967 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
1968 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
1970 if (key == NULL || key->type == KEY_UNSPEC)
1972 if (key->type == KEY_RSA &&
1973 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
1974 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
1976 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
1980 * Handle hostkeys-00@openssh.com global request to inform the client of all
1981 * the server's hostkeys. The keys are checked against the user's
1982 * HostkeyAlgorithms preference before they are accepted.
1985 client_input_hostkeys(void)
1987 struct ssh *ssh = active_state; /* XXX */
1988 const u_char *blob = NULL;
1990 struct sshbuf *buf = NULL;
1991 struct sshkey *key = NULL, **tmp;
1994 static int hostkeys_seen = 0; /* XXX use struct ssh */
1995 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
1996 struct hostkeys_update_ctx *ctx = NULL;
1999 fatal("%s: server already sent hostkeys", __func__);
2000 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2002 return 1; /* won't ask in batchmode, so don't even try */
2003 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2006 ctx = xcalloc(1, sizeof(*ctx));
2007 while (ssh_packet_remaining(ssh) > 0) {
2010 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2011 error("%s: couldn't parse message: %s",
2012 __func__, ssh_err(r));
2015 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2016 error("%s: parse key: %s", __func__, ssh_err(r));
2019 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2021 debug3("%s: received %s key %s", __func__,
2022 sshkey_type(key), fp);
2025 if (!key_accepted_by_hostkeyalgs(key)) {
2026 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2027 __func__, sshkey_ssh_name(key));
2031 if (sshkey_is_cert(key)) {
2032 debug3("%s: %s key is a certificate; skipping",
2033 __func__, sshkey_ssh_name(key));
2036 /* Ensure keys are unique */
2037 for (i = 0; i < ctx->nkeys; i++) {
2038 if (sshkey_equal(key, ctx->keys[i])) {
2039 error("%s: received duplicated %s host key",
2040 __func__, sshkey_ssh_name(key));
2044 /* Key is good, record it */
2045 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2046 sizeof(*ctx->keys))) == NULL)
2047 fatal("%s: recallocarray failed nkeys = %zu",
2048 __func__, ctx->nkeys);
2050 ctx->keys[ctx->nkeys++] = key;
2054 if (ctx->nkeys == 0) {
2055 debug("%s: server sent no hostkeys", __func__);
2059 if ((ctx->keys_seen = calloc(ctx->nkeys,
2060 sizeof(*ctx->keys_seen))) == NULL)
2061 fatal("%s: calloc failed", __func__);
2063 get_hostfile_hostname_ipaddr(host,
2064 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2065 options.port, &ctx->host_str,
2066 options.check_host_ip ? &ctx->ip_str : NULL);
2068 /* Find which keys we already know about. */
2069 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2070 ctx, ctx->host_str, ctx->ip_str,
2071 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2072 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2076 /* Figure out if we have any new keys to add */
2078 for (i = 0; i < ctx->nkeys; i++) {
2079 if (!ctx->keys_seen[i])
2083 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2084 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2086 if (ctx->nnew == 0 && ctx->nold != 0) {
2087 /* We have some keys to remove. Just do it. */
2088 update_known_hosts(ctx);
2089 } else if (ctx->nnew != 0) {
2091 * We have received hitherto-unseen keys from the server.
2092 * Ask the server to confirm ownership of the private halves.
2094 debug3("%s: asking server to prove ownership for %zu keys",
2095 __func__, ctx->nnew);
2096 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2097 (r = sshpkt_put_cstring(ssh,
2098 "hostkeys-prove-00@openssh.com")) != 0 ||
2099 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2100 fatal("%s: cannot prepare packet: %s",
2101 __func__, ssh_err(r));
2102 if ((buf = sshbuf_new()) == NULL)
2103 fatal("%s: sshbuf_new", __func__);
2104 for (i = 0; i < ctx->nkeys; i++) {
2105 if (ctx->keys_seen[i])
2108 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2109 fatal("%s: sshkey_putb: %s",
2110 __func__, ssh_err(r));
2111 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2112 fatal("%s: sshpkt_put_string: %s",
2113 __func__, ssh_err(r));
2115 if ((r = sshpkt_send(ssh)) != 0)
2116 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2117 client_register_global_confirm(
2118 client_global_hostkeys_private_confirm, ctx);
2119 ctx = NULL; /* will be freed in callback */
2124 hostkeys_update_ctx_free(ctx);
2128 * NB. Return success for all cases. The server doesn't need to know
2129 * what the client does with its hosts file.
2135 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2141 rtype = packet_get_cstring(NULL);
2142 want_reply = packet_get_char();
2143 debug("client_input_global_request: rtype %s want_reply %d",
2145 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2146 success = client_input_hostkeys();
2148 packet_start(success ?
2149 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2151 packet_write_wait();
2158 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2159 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2164 debug2("%s: id %d", __func__, id);
2166 if ((c = channel_lookup(ssh, id)) == NULL)
2167 fatal("%s: channel %d: unknown channel", __func__, id);
2169 packet_set_interactive(want_tty,
2170 options.ip_qos_interactive, options.ip_qos_bulk);
2175 /* Store window size in the packet. */
2176 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2177 memset(&ws, 0, sizeof(ws));
2179 channel_request_start(ssh, id, "pty-req", 1);
2180 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2181 packet_put_cstring(term != NULL ? term : "");
2182 packet_put_int((u_int)ws.ws_col);
2183 packet_put_int((u_int)ws.ws_row);
2184 packet_put_int((u_int)ws.ws_xpixel);
2185 packet_put_int((u_int)ws.ws_ypixel);
2187 tiop = get_saved_tio();
2188 tty_make_modes(-1, tiop);
2190 /* XXX wait for reply */
2194 /* Transfer any environment variables from client to server */
2195 if (options.num_send_env != 0 && env != NULL) {
2199 debug("Sending environment.");
2200 for (i = 0; env[i] != NULL; i++) {
2202 name = xstrdup(env[i]);
2203 if ((val = strchr(name, '=')) == NULL) {
2210 for (j = 0; j < options.num_send_env; j++) {
2211 if (match_pattern(name, options.send_env[j])) {
2217 debug3("Ignored env %s", name);
2222 debug("Sending env %s = %s", name, val);
2223 channel_request_start(ssh, id, "env", 0);
2224 packet_put_cstring(name);
2225 packet_put_cstring(val);
2231 len = buffer_len(cmd);
2235 if (want_subsystem) {
2236 debug("Sending subsystem: %.*s",
2237 len, (u_char*)buffer_ptr(cmd));
2238 channel_request_start(ssh, id, "subsystem", 1);
2239 client_expect_confirm(ssh, id, "subsystem",
2242 debug("Sending command: %.*s",
2243 len, (u_char*)buffer_ptr(cmd));
2244 channel_request_start(ssh, id, "exec", 1);
2245 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2247 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2250 channel_request_start(ssh, id, "shell", 1);
2251 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2257 client_init_dispatch(void)
2259 dispatch_init(&dispatch_protocol_error);
2261 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2262 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2263 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2264 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2265 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2266 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2267 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2268 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2269 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2270 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2271 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2272 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2275 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2277 /* global request reply messages */
2278 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2279 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2283 client_stop_mux(void)
2285 if (options.control_path != NULL && muxserver_sock != -1)
2286 unlink(options.control_path);
2288 * If we are in persist mode, or don't have a shell, signal that we
2289 * should close when all active channels are closed.
2291 if (options.control_persist || no_shell_flag) {
2293 setproctitle("[stopped mux]");
2297 /* client specific fatal cleanup */
2301 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2302 leave_non_blocking();
2303 if (options.control_path != NULL && muxserver_sock != -1)
2304 unlink(options.control_path);
2305 ssh_kill_proxy_command();