1 /* $OpenBSD: clientloop.c,v 1.317 2018/07/11 18:53:29 markus 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 struct sshbuf *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, struct sshbuf *);
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);
550 * We have to clear the select masks, because we return.
551 * We have to return, because the mainloop checks for the flags
552 * set by the signal handlers.
554 memset(*readsetp, 0, *nallocp);
555 memset(*writesetp, 0, *nallocp);
559 /* Note: we might still have data in the buffers. */
560 if ((r = sshbuf_putf(stderr_buffer,
561 "select: %s\r\n", strerror(errno))) != 0)
562 fatal("%s: buffer error: %s", __func__, ssh_err(r));
564 } else if (ret == 0) {
566 * Timeout. Could have been either keepalive or rekeying.
567 * Keepalive we check here, rekeying is checked in clientloop.
569 if (server_alive_time != 0 && server_alive_time <= monotime())
570 server_alive_check();
576 client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
578 /* Flush stdout and stderr buffers. */
579 if (sshbuf_len(bout) > 0)
580 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
582 if (sshbuf_len(berr) > 0)
583 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
586 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
592 /* Send the suspend signal to the program itself. */
593 kill(getpid(), SIGTSTP);
595 /* Reset window sizes in case they have changed */
596 received_window_change_signal = 1;
598 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
602 client_process_net_input(fd_set *readset)
604 char buf[SSH_IOBUFSZ];
608 * Read input from the server, and add any such data to the buffer of
609 * the packet subsystem.
611 if (FD_ISSET(connection_in, readset)) {
612 /* Read as much as possible. */
613 len = read(connection_in, buf, sizeof(buf));
616 * Received EOF. The remote host has closed the
619 if ((r = sshbuf_putf(stderr_buffer,
620 "Connection to %.300s closed by remote host.\r\n",
622 fatal("%s: buffer error: %s",
623 __func__, ssh_err(r));
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 if ((r = sshbuf_putf(stderr_buffer,
641 "Read from remote host %.300s: %.100s\r\n",
642 host, strerror(errno))) != 0)
643 fatal("%s: buffer error: %s",
644 __func__, ssh_err(r));
648 packet_process_incoming(buf, len);
653 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
655 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
660 * If a TTY was explicitly requested, then a failure to allocate
663 if (cr->action == CONFIRM_TTY &&
664 (options.request_tty == REQUEST_TTY_FORCE ||
665 options.request_tty == REQUEST_TTY_YES))
666 cr->action = CONFIRM_CLOSE;
668 /* XXX suppress on mux _client_ quietmode */
669 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
670 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
672 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
673 debug2("%s request accepted on channel %d",
674 cr->request_type, c->self);
675 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
677 snprintf(errmsg, sizeof(errmsg),
678 "%s request failed\r\n", cr->request_type);
680 snprintf(errmsg, sizeof(errmsg),
681 "%s request failed on channel %d",
682 cr->request_type, c->self);
684 /* If error occurred on primary session channel, then exit */
685 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
688 * If error occurred on mux client, append to
692 if ((r = sshbuf_put(c->extended, errmsg,
693 strlen(errmsg))) != 0)
694 fatal("%s: buffer error %s", __func__,
698 if (cr->action == CONFIRM_TTY) {
700 * If a TTY allocation error occurred, then arrange
701 * for the correct TTY to leave raw mode.
703 if (c->self == session_ident)
706 mux_tty_alloc_failed(ssh, c);
707 } else if (cr->action == CONFIRM_CLOSE) {
708 chan_read_failed(ssh, c);
709 chan_write_failed(ssh, c);
716 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
722 client_expect_confirm(struct ssh *ssh, int id, const char *request,
723 enum confirm_action action)
725 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
727 cr->request_type = request;
730 channel_register_status_confirm(ssh, id, client_status_confirm,
731 client_abandon_status_confirm, cr);
735 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
737 struct global_confirm *gc, *last_gc;
739 /* Coalesce identical callbacks */
740 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
741 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
742 if (++last_gc->ref_count >= INT_MAX)
743 fatal("%s: last_gc->ref_count = %d",
744 __func__, last_gc->ref_count);
748 gc = xcalloc(1, sizeof(*gc));
752 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
756 process_cmdline(struct ssh *ssh)
758 void (*handler)(int);
760 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
763 memset(&fwd, 0, sizeof(fwd));
765 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
766 handler = signal(SIGINT, SIG_IGN);
767 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
770 while (isspace((u_char)*s))
773 s++; /* Skip cmdline '-', if any */
777 if (*s == 'h' || *s == 'H' || *s == '?') {
779 logit(" -L[bind_address:]port:host:hostport "
780 "Request local forward");
781 logit(" -R[bind_address:]port:host:hostport "
782 "Request remote forward");
783 logit(" -D[bind_address:]port "
784 "Request dynamic forward");
785 logit(" -KL[bind_address:]port "
786 "Cancel local forward");
787 logit(" -KR[bind_address:]port "
788 "Cancel remote forward");
789 logit(" -KD[bind_address:]port "
790 "Cancel dynamic forward");
791 if (!options.permit_local_command)
794 "Execute local command");
798 if (*s == '!' && options.permit_local_command) {
815 logit("Invalid command.");
819 while (isspace((u_char)*++s))
822 /* XXX update list of forwards in options */
824 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
825 if (!parse_forward(&fwd, s, 1, 0)) {
826 logit("Bad forwarding close specification.");
830 ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
832 ok = channel_cancel_lport_listener(ssh, &fwd,
833 0, &options.fwd_opts) > 0;
835 ok = channel_cancel_lport_listener(ssh, &fwd,
836 CHANNEL_CANCEL_PORT_STATIC,
837 &options.fwd_opts) > 0;
839 logit("Unknown port forwarding.");
842 logit("Canceled forwarding.");
844 if (!parse_forward(&fwd, s, dynamic, remote)) {
845 logit("Bad forwarding specification.");
848 if (local || dynamic) {
849 if (!channel_setup_local_fwd_listener(ssh, &fwd,
850 &options.fwd_opts)) {
851 logit("Port forwarding failed.");
855 if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
856 logit("Port forwarding failed.");
860 logit("Forwarding port.");
864 signal(SIGINT, handler);
865 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
867 free(fwd.listen_host);
868 free(fwd.listen_path);
869 free(fwd.connect_host);
870 free(fwd.connect_path);
873 /* reasons to suppress output of an escape command in help output */
874 #define SUPPRESS_NEVER 0 /* never suppress, always show */
875 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
876 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
877 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
878 struct escape_help_text {
883 static struct escape_help_text esc_txt[] = {
884 {".", "terminate session", SUPPRESS_MUXMASTER},
885 {".", "terminate connection (and any multiplexed sessions)",
887 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
888 {"C", "open a command line", SUPPRESS_MUXCLIENT},
889 {"R", "request rekey", SUPPRESS_NEVER},
890 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
891 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
892 {"#", "list forwarded connections", SUPPRESS_NEVER},
893 {"&", "background ssh (when waiting for connections to terminate)",
895 {"?", "this message", SUPPRESS_NEVER},
899 print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
902 unsigned int i, suppress_flags;
905 if ((r = sshbuf_putf(b,
906 "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
907 fatal("%s: buffer error: %s", __func__, ssh_err(r));
910 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
911 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
912 (using_stderr ? 0 : SUPPRESS_SYSLOG);
914 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
915 if (esc_txt[i].flags & suppress_flags)
917 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
918 escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
919 fatal("%s: buffer error: %s", __func__, ssh_err(r));
922 if ((r = sshbuf_putf(b,
923 " %c%c - send the escape character by typing it twice\r\n"
924 "(Note that escapes are only recognized immediately after "
925 "newline.)\r\n", escape_char, escape_char)) != 0)
926 fatal("%s: buffer error: %s", __func__, ssh_err(r));
930 * Process the characters one by one.
933 process_escapes(struct ssh *ssh, Channel *c,
934 struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
942 struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
943 NULL : (struct escape_filter_ctx *)c->filter_ctx;
945 if (c->filter_ctx == NULL)
951 for (i = 0; i < (u_int)len; i++) {
952 /* Get one character at a time. */
955 if (efc->escape_pending) {
956 /* We have previously seen an escape character. */
957 /* Clear the flag now. */
958 efc->escape_pending = 0;
960 /* Process the escaped character. */
963 /* Terminate the connection. */
964 if ((r = sshbuf_putf(berr, "%c.\r\n",
965 efc->escape_char)) != 0)
966 fatal("%s: buffer error: %s",
967 __func__, ssh_err(r));
968 if (c && c->ctl_chan != -1) {
969 chan_read_failed(ssh, c);
970 chan_write_failed(ssh, c);
971 if (c->detach_user) {
975 c->type = SSH_CHANNEL_ABANDONED;
976 sshbuf_reset(c->input);
977 chan_ibuf_empty(ssh, c);
984 /* XXX support this for mux clients */
985 if (c && c->ctl_chan != -1) {
989 snprintf(b, sizeof b, "^Z");
991 snprintf(b, sizeof b, "%c", ch);
992 if ((r = sshbuf_putf(berr,
993 "%c%s escape not available to "
994 "multiplexed sessions\r\n",
995 efc->escape_char, b)) != 0)
996 fatal("%s: buffer error: %s",
997 __func__, ssh_err(r));
1000 /* Suspend the program. Inform the user */
1001 if ((r = sshbuf_putf(berr,
1002 "%c^Z [suspend ssh]\r\n",
1003 efc->escape_char)) != 0)
1004 fatal("%s: buffer error: %s",
1005 __func__, ssh_err(r));
1007 /* Restore terminal modes and suspend. */
1008 client_suspend_self(bin, bout, berr);
1010 /* We have been continued. */
1014 if ((r = sshbuf_putf(berr,
1015 "%cB\r\n", efc->escape_char)) != 0)
1016 fatal("%s: buffer error: %s",
1017 __func__, ssh_err(r));
1018 channel_request_start(ssh, c->self, "break", 0);
1019 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1020 (r = sshpkt_send(ssh)) != 0)
1021 fatal("%s: %s", __func__,
1026 if (datafellows & SSH_BUG_NOREKEY)
1027 logit("Server does not "
1028 "support re-keying");
1036 if (c && c->ctl_chan != -1)
1038 if (!log_is_on_stderr()) {
1039 if ((r = sshbuf_putf(berr,
1040 "%c%c [Logging to syslog]\r\n",
1041 efc->escape_char, ch)) != 0)
1042 fatal("%s: buffer error: %s",
1043 __func__, ssh_err(r));
1046 if (ch == 'V' && options.log_level >
1048 log_change_level(--options.log_level);
1049 if (ch == 'v' && options.log_level <
1050 SYSLOG_LEVEL_DEBUG3)
1051 log_change_level(++options.log_level);
1052 if ((r = sshbuf_putf(berr,
1053 "%c%c [LogLevel %s]\r\n",
1054 efc->escape_char, ch,
1055 log_level_name(options.log_level))) != 0)
1056 fatal("%s: buffer error: %s",
1057 __func__, ssh_err(r));
1061 if (c && c->ctl_chan != -1)
1064 * Detach the program (continue to serve
1065 * connections, but put in background and no
1066 * more new connections).
1068 /* Restore tty modes. */
1070 options.request_tty == REQUEST_TTY_FORCE);
1072 /* Stop listening for new connections. */
1073 channel_stop_listening(ssh);
1075 if ((r = sshbuf_putf(berr,
1076 "%c& [backgrounded]\n", efc->escape_char))
1078 fatal("%s: buffer error: %s",
1079 __func__, ssh_err(r));
1081 /* Fork into background. */
1084 error("fork: %.100s", strerror(errno));
1087 if (pid != 0) { /* This is the parent. */
1088 /* The parent just exits. */
1091 /* The child continues serving connections. */
1092 /* fake EOF on stdin */
1093 if ((r = sshbuf_put_u8(bin, 4)) != 0)
1094 fatal("%s: buffer error: %s",
1095 __func__, ssh_err(r));
1098 print_escape_help(berr, efc->escape_char,
1099 (c && c->ctl_chan != -1),
1100 log_is_on_stderr());
1104 if ((r = sshbuf_putf(berr, "%c#\r\n",
1105 efc->escape_char)) != 0)
1106 fatal("%s: buffer error: %s",
1107 __func__, ssh_err(r));
1108 s = channel_open_message(ssh);
1109 if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1110 fatal("%s: buffer error: %s",
1111 __func__, ssh_err(r));
1116 if (c && c->ctl_chan != -1)
1118 process_cmdline(ssh);
1122 if (ch != efc->escape_char) {
1123 if ((r = sshbuf_put_u8(bin,
1124 efc->escape_char)) != 0)
1125 fatal("%s: buffer error: %s",
1126 __func__, ssh_err(r));
1129 /* Escaped characters fall through here */
1134 * The previous character was not an escape char.
1135 * Check if this is an escape.
1137 if (last_was_cr && ch == efc->escape_char) {
1139 * It is. Set the flag and continue to
1142 efc->escape_pending = 1;
1148 * Normal character. Record whether it was a newline,
1149 * and append it to the buffer.
1151 last_was_cr = (ch == '\r' || ch == '\n');
1152 if ((r = sshbuf_put_u8(bin, ch)) != 0)
1153 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1160 * Get packets from the connection input buffer, and process them as long as
1161 * there are packets available.
1163 * Any unknown packets received during the actual
1164 * session cause the session to terminate. This is
1165 * intended to make debugging easier since no
1166 * confirmations are sent. Any compatible protocol
1167 * extensions must be negotiated during the
1168 * preparatory phase.
1172 client_process_buffered_input_packets(void)
1174 ssh_dispatch_run_fatal(active_state, DISPATCH_NONBLOCK, &quit_pending);
1177 /* scan buf[] for '~' before sending data to the peer */
1179 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1181 client_new_escape_filter_ctx(int escape_char)
1183 struct escape_filter_ctx *ret;
1185 ret = xcalloc(1, sizeof(*ret));
1186 ret->escape_pending = 0;
1187 ret->escape_char = escape_char;
1191 /* Free the escape filter context on channel free */
1193 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1199 client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1201 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1204 return process_escapes(ssh, c, c->input, c->output, c->extended,
1209 client_channel_closed(struct ssh *ssh, int id, void *arg)
1211 channel_cancel_cleanup(ssh, id);
1213 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1217 * Implements the interactive session with the server. This is called after
1218 * the user has been authenticated, and a command has been started on the
1219 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1220 * used as an escape character for terminating or suspending the session.
1223 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1226 fd_set *readset = NULL, *writeset = NULL;
1227 double start_time, total_time;
1228 int r, max_fd = 0, max_fd2 = 0, len;
1229 u_int64_t ibytes, obytes;
1233 debug("Entering interactive session.");
1235 if (options.control_master &&
1236 !option_clear_or_none(options.control_path)) {
1237 debug("pledge: id");
1238 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
1240 fatal("%s pledge(): %s", __func__, strerror(errno));
1242 } else if (options.forward_x11 || options.permit_local_command) {
1243 debug("pledge: exec");
1244 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1246 fatal("%s pledge(): %s", __func__, strerror(errno));
1248 } else if (options.update_hostkeys) {
1249 debug("pledge: filesystem full");
1250 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1252 fatal("%s pledge(): %s", __func__, strerror(errno));
1254 } else if (!option_clear_or_none(options.proxy_command) ||
1255 fork_after_authentication_flag) {
1256 debug("pledge: proc");
1257 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1258 fatal("%s pledge(): %s", __func__, strerror(errno));
1261 debug("pledge: network");
1262 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1263 fatal("%s pledge(): %s", __func__, strerror(errno));
1266 start_time = monotime_double();
1268 /* Initialize variables. */
1271 connection_in = packet_get_connection_in();
1272 connection_out = packet_get_connection_out();
1273 max_fd = MAXIMUM(connection_in, connection_out);
1277 /* Initialize buffer. */
1278 if ((stderr_buffer = sshbuf_new()) == NULL)
1279 fatal("%s: sshbuf_new failed", __func__);
1281 client_init_dispatch();
1284 * Set signal handlers, (e.g. to restore non-blocking mode)
1285 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1287 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1288 signal(SIGHUP, signal_handler);
1289 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1290 signal(SIGINT, signal_handler);
1291 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1292 signal(SIGQUIT, signal_handler);
1293 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1294 signal(SIGTERM, signal_handler);
1295 signal(SIGWINCH, window_change_handler);
1298 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1300 session_ident = ssh2_chan_id;
1301 if (session_ident != -1) {
1302 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1303 channel_register_filter(ssh, session_ident,
1304 client_simple_escape_filter, NULL,
1305 client_filter_cleanup,
1306 client_new_escape_filter_ctx(
1309 channel_register_cleanup(ssh, session_ident,
1310 client_channel_closed, 0);
1313 /* Main loop of the client for the interactive session mode. */
1314 while (!quit_pending) {
1316 /* Process buffered packets sent by the server. */
1317 client_process_buffered_input_packets();
1319 if (session_closed && !channel_still_open(ssh))
1322 if (ssh_packet_is_rekeying(ssh)) {
1323 debug("rekeying in progress");
1324 } else if (need_rekeying) {
1325 /* manual rekey request */
1326 debug("need rekeying");
1327 if ((r = kex_start_rekex(ssh)) != 0)
1328 fatal("%s: kex_start_rekex: %s", __func__,
1333 * Make packets from buffered channel data, and
1334 * enqueue them for sending to the server.
1336 if (packet_not_very_much_data_to_write())
1337 channel_output_poll(ssh);
1340 * Check if the window size has changed, and buffer a
1341 * message about it to the server if so.
1343 client_check_window_change(ssh);
1349 * Wait until we have something to do (something becomes
1350 * available on one of the descriptors).
1353 client_wait_until_can_do_something(ssh, &readset, &writeset,
1354 &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
1359 /* Do channel operations unless rekeying in progress. */
1360 if (!ssh_packet_is_rekeying(ssh))
1361 channel_after_select(ssh, readset, writeset);
1363 /* Buffer input from the connection. */
1364 client_process_net_input(readset);
1370 * Send as much buffered packet data as possible to the
1373 if (FD_ISSET(connection_out, writeset))
1374 packet_write_poll();
1377 * If we are a backgrounded control master, and the
1378 * timeout has expired without any active client
1379 * connections, then quit.
1381 if (control_persist_exit_time > 0) {
1382 if (monotime() >= control_persist_exit_time) {
1383 debug("ControlPersist timeout expired");
1391 /* Terminate the session. */
1393 /* Stop watching for window change. */
1394 signal(SIGWINCH, SIG_DFL);
1396 packet_start(SSH2_MSG_DISCONNECT);
1397 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1398 packet_put_cstring("disconnected by user");
1399 packet_put_cstring(""); /* language tag */
1401 packet_write_wait();
1403 channel_free_all(ssh);
1406 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1408 /* restore blocking io */
1409 if (!isatty(fileno(stdin)))
1410 unset_nonblock(fileno(stdin));
1411 if (!isatty(fileno(stdout)))
1412 unset_nonblock(fileno(stdout));
1413 if (!isatty(fileno(stderr)))
1414 unset_nonblock(fileno(stderr));
1417 * If there was no shell or command requested, there will be no remote
1418 * exit status to be returned. In that case, clear error code if the
1419 * connection was deliberately terminated at this end.
1421 if (no_shell_flag && received_signal == SIGTERM) {
1422 received_signal = 0;
1426 if (received_signal) {
1427 verbose("Killed by signal %d.", (int) received_signal);
1432 * In interactive mode (with pseudo tty) display a message indicating
1433 * that the connection has been closed.
1435 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1436 if ((r = sshbuf_putf(stderr_buffer,
1437 "Connection to %.64s closed.\r\n", host)) != 0)
1438 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1441 /* Output any buffered data for stderr. */
1442 if (sshbuf_len(stderr_buffer) > 0) {
1443 len = atomicio(vwrite, fileno(stderr),
1444 (u_char *)sshbuf_ptr(stderr_buffer),
1445 sshbuf_len(stderr_buffer));
1446 if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
1447 error("Write failed flushing stderr buffer.");
1448 else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
1449 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1452 /* Clear and free any buffers. */
1453 explicit_bzero(buf, sizeof(buf));
1454 sshbuf_free(stderr_buffer);
1456 /* Report bytes transferred, and transfer rates. */
1457 total_time = monotime_double() - start_time;
1458 packet_get_bytes(&ibytes, &obytes);
1459 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1460 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1462 verbose("Bytes per second: sent %.1f, received %.1f",
1463 obytes / total_time, ibytes / total_time);
1464 /* Return the exit status of the program. */
1465 debug("Exit status %d", exit_status);
1472 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1473 int rchan, u_int rwindow, u_int rmaxpack)
1476 struct sshbuf *b = NULL;
1477 char *listen_address, *originator_address;
1478 u_short listen_port, originator_port;
1481 /* Get rest of the packet */
1482 listen_address = packet_get_string(NULL);
1483 listen_port = packet_get_int();
1484 originator_address = packet_get_string(NULL);
1485 originator_port = packet_get_int();
1488 debug("%s: listen %s port %d, originator %s port %d", __func__,
1489 listen_address, listen_port, originator_address, originator_port);
1491 c = channel_connect_by_listen_address(ssh, listen_address, listen_port,
1492 "forwarded-tcpip", originator_address);
1494 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1495 if ((b = sshbuf_new()) == NULL) {
1496 error("%s: alloc reply", __func__);
1499 /* reconstruct and send to muxclient */
1500 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1501 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1502 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1503 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1504 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1505 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1506 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1507 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1508 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1509 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1510 (r = sshbuf_put_stringb(c->output, b)) != 0) {
1511 error("%s: compose for muxclient %s", __func__,
1519 free(originator_address);
1520 free(listen_address);
1525 client_request_forwarded_streamlocal(struct ssh *ssh,
1526 const char *request_type, int rchan)
1531 /* Get the remote path. */
1532 listen_path = packet_get_string(NULL);
1533 /* XXX: Skip reserved field for now. */
1534 if (packet_get_string_ptr(NULL) == NULL)
1535 fatal("%s: packet_get_string_ptr failed", __func__);
1538 debug("%s: %s", __func__, listen_path);
1540 c = channel_connect_by_listen_path(ssh, listen_path,
1541 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1547 client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1551 u_short originator_port;
1554 if (!options.forward_x11) {
1555 error("Warning: ssh server tried X11 forwarding.");
1556 error("Warning: this is probably a break-in attempt by a "
1557 "malicious server.");
1560 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1561 verbose("Rejected X11 connection after ForwardX11Timeout "
1565 originator = packet_get_string(NULL);
1566 originator_port = packet_get_int();
1568 /* XXX check permission */
1569 debug("client_request_x11: request from %s %d", originator,
1572 sock = x11_connect_display(ssh);
1575 c = channel_new(ssh, "x11",
1576 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1577 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1583 client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1588 if (!options.forward_agent) {
1589 error("Warning: ssh server tried agent forwarding.");
1590 error("Warning: this is probably a break-in attempt by a "
1591 "malicious server.");
1594 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1595 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1596 debug("%s: ssh_get_authentication_socket: %s",
1597 __func__, ssh_err(r));
1600 c = channel_new(ssh, "authentication agent connection",
1601 SSH_CHANNEL_OPEN, sock, sock, -1,
1602 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1603 "authentication agent connection", 1);
1609 client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1610 int local_tun, int remote_tun)
1614 char *ifname = NULL;
1616 if (tun_mode == SSH_TUNMODE_NO)
1619 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1621 /* Open local tunnel device */
1622 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1623 error("Tunnel device open failed.");
1626 debug("Tunnel forwarding using interface %s", ifname);
1628 c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1629 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1632 #if defined(SSH_TUN_FILTER)
1633 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1634 channel_register_filter(ssh, c->self, sys_tun_infilter,
1635 sys_tun_outfilter, NULL, NULL);
1638 packet_start(SSH2_MSG_CHANNEL_OPEN);
1639 packet_put_cstring("tun@openssh.com");
1640 packet_put_int(c->self);
1641 packet_put_int(c->local_window_max);
1642 packet_put_int(c->local_maxpacket);
1643 packet_put_int(tun_mode);
1644 packet_put_int(remote_tun);
1650 /* XXXX move to generic input handler */
1652 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1657 u_int rmaxpack, rwindow, len;
1659 ctype = packet_get_string(&len);
1660 rchan = packet_get_int();
1661 rwindow = packet_get_int();
1662 rmaxpack = packet_get_int();
1664 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1665 ctype, rchan, rwindow, rmaxpack);
1667 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1668 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1670 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1671 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1672 } else if (strcmp(ctype, "x11") == 0) {
1673 c = client_request_x11(ssh, ctype, rchan);
1674 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1675 c = client_request_agent(ssh, ctype, rchan);
1677 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1678 debug3("proxied to downstream: %s", ctype);
1679 } else if (c != NULL) {
1680 debug("confirm %s", ctype);
1681 c->remote_id = rchan;
1682 c->have_remote_id = 1;
1683 c->remote_window = rwindow;
1684 c->remote_maxpacket = rmaxpack;
1685 if (c->type != SSH_CHANNEL_CONNECTING) {
1686 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1687 packet_put_int(c->remote_id);
1688 packet_put_int(c->self);
1689 packet_put_int(c->local_window);
1690 packet_put_int(c->local_maxpacket);
1694 debug("failure %s", ctype);
1695 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1696 packet_put_int(rchan);
1697 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1698 packet_put_cstring("open failed");
1699 packet_put_cstring("");
1707 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1710 int exitval, id, reply, success = 0;
1713 id = packet_get_int();
1714 c = channel_lookup(ssh, id);
1715 if (channel_proxy_upstream(c, type, seq, ssh))
1717 rtype = packet_get_string(NULL);
1718 reply = packet_get_char();
1720 debug("client_input_channel_req: channel %d rtype %s reply %d",
1724 error("client_input_channel_req: request for channel -1");
1725 } else if (c == NULL) {
1726 error("client_input_channel_req: channel %d: "
1727 "unknown channel", id);
1728 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1730 chan_rcvd_eow(ssh, c);
1731 } else if (strcmp(rtype, "exit-status") == 0) {
1732 exitval = packet_get_int();
1733 if (c->ctl_chan != -1) {
1734 mux_exit_message(ssh, c, exitval);
1736 } else if (id == session_ident) {
1737 /* Record exit value of local session */
1739 exit_status = exitval;
1741 /* Probably for a mux channel that has already closed */
1742 debug("%s: no sink for exit-status on channel %d",
1747 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1748 if (!c->have_remote_id)
1749 fatal("%s: channel %d: no remote_id",
1751 packet_start(success ?
1752 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1753 packet_put_int(c->remote_id);
1760 struct hostkeys_update_ctx {
1761 /* The hostname and (optionally) IP address string for the server */
1762 char *host_str, *ip_str;
1765 * Keys received from the server and a flag for each indicating
1766 * whether they already exist in known_hosts.
1767 * keys_seen is filled in by hostkeys_find() and later (for new
1768 * keys) by client_global_hostkeys_private_confirm().
1770 struct sshkey **keys;
1775 * Keys that are in known_hosts, but were not present in the update
1776 * from the server (i.e. scheduled to be deleted).
1777 * Filled in by hostkeys_find().
1779 struct sshkey **old_keys;
1784 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
1790 for (i = 0; i < ctx->nkeys; i++)
1791 sshkey_free(ctx->keys[i]);
1793 free(ctx->keys_seen);
1794 for (i = 0; i < ctx->nold; i++)
1795 sshkey_free(ctx->old_keys[i]);
1796 free(ctx->old_keys);
1797 free(ctx->host_str);
1803 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
1805 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1807 struct sshkey **tmp;
1809 if (l->status != HKF_STATUS_MATCHED || l->key == NULL)
1812 /* Mark off keys we've already seen for this host */
1813 for (i = 0; i < ctx->nkeys; i++) {
1814 if (sshkey_equal(l->key, ctx->keys[i])) {
1815 debug3("%s: found %s key at %s:%ld", __func__,
1816 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
1817 ctx->keys_seen[i] = 1;
1821 /* This line contained a key that not offered by the server */
1822 debug3("%s: deprecated %s key at %s:%ld", __func__,
1823 sshkey_ssh_name(l->key), l->path, l->linenum);
1824 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1825 sizeof(*ctx->old_keys))) == NULL)
1826 fatal("%s: recallocarray failed nold = %zu",
1827 __func__, ctx->nold);
1828 ctx->old_keys = tmp;
1829 ctx->old_keys[ctx->nold++] = l->key;
1836 update_known_hosts(struct hostkeys_update_ctx *ctx)
1839 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
1840 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1841 char *fp, *response;
1844 for (i = 0; i < ctx->nkeys; i++) {
1845 if (ctx->keys_seen[i] != 2)
1847 if ((fp = sshkey_fingerprint(ctx->keys[i],
1848 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1849 fatal("%s: sshkey_fingerprint failed", __func__);
1850 do_log2(loglevel, "Learned new hostkey: %s %s",
1851 sshkey_type(ctx->keys[i]), fp);
1854 for (i = 0; i < ctx->nold; i++) {
1855 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
1856 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1857 fatal("%s: sshkey_fingerprint failed", __func__);
1858 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
1859 sshkey_type(ctx->old_keys[i]), fp);
1862 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1863 if (get_saved_tio() != NULL) {
1868 for (i = 0; !quit_pending && i < 3; i++) {
1870 response = read_passphrase("Accept updated hostkeys? "
1871 "(yes/no): ", RP_ECHO);
1872 if (strcasecmp(response, "yes") == 0)
1874 else if (quit_pending || response == NULL ||
1875 strcasecmp(response, "no") == 0) {
1876 options.update_hostkeys = 0;
1879 do_log2(loglevel, "Please enter "
1880 "\"yes\" or \"no\"");
1883 if (quit_pending || i >= 3 || response == NULL)
1884 options.update_hostkeys = 0;
1891 * Now that all the keys are verified, we can go ahead and replace
1892 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
1893 * cancel the operation).
1895 if (options.update_hostkeys != 0 &&
1896 (r = hostfile_replace_entries(options.user_hostfiles[0],
1897 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
1898 options.hash_known_hosts, 0,
1899 options.fingerprint_hash)) != 0)
1900 error("%s: hostfile_replace_entries failed: %s",
1901 __func__, ssh_err(r));
1905 client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
1906 u_int32_t seq, void *_ctx)
1908 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1910 struct sshbuf *signdata;
1911 int r, kexsigtype, use_kexsigtype;
1916 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
1917 if (type != SSH2_MSG_REQUEST_SUCCESS) {
1918 error("Server failed to confirm ownership of "
1919 "private host keys");
1920 hostkeys_update_ctx_free(ctx);
1923 kexsigtype = sshkey_type_plain(
1924 sshkey_type_from_name(ssh->kex->hostkey_alg));
1926 if ((signdata = sshbuf_new()) == NULL)
1927 fatal("%s: sshbuf_new failed", __func__);
1928 /* Don't want to accidentally accept an unbound signature */
1929 if (ssh->kex->session_id_len == 0)
1930 fatal("%s: ssh->kex->session_id_len == 0", __func__);
1932 * Expect a signature for each of the ctx->nnew private keys we
1933 * haven't seen before. They will be in the same order as the
1934 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
1936 for (ndone = i = 0; i < ctx->nkeys; i++) {
1937 if (ctx->keys_seen[i])
1939 /* Prepare data to be signed: session ID, unique string, key */
1940 sshbuf_reset(signdata);
1941 if ( (r = sshbuf_put_cstring(signdata,
1942 "hostkeys-prove-00@openssh.com")) != 0 ||
1943 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
1944 ssh->kex->session_id_len)) != 0 ||
1945 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1946 fatal("%s: failed to prepare signature: %s",
1947 __func__, ssh_err(r));
1948 /* Extract and verify signature */
1949 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1950 error("%s: couldn't parse message: %s",
1951 __func__, ssh_err(r));
1955 * For RSA keys, prefer to use the signature type negotiated
1956 * during KEX to the default (SHA1).
1958 use_kexsigtype = kexsigtype == KEY_RSA &&
1959 sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA;
1960 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1961 sshbuf_ptr(signdata), sshbuf_len(signdata),
1962 use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0)) != 0) {
1963 error("%s: server gave bad signature for %s key %zu",
1964 __func__, sshkey_type(ctx->keys[i]), i);
1967 /* Key is good. Mark it as 'seen' */
1968 ctx->keys_seen[i] = 2;
1971 if (ndone != ctx->nnew)
1972 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
1973 ndone, ctx->nnew); /* Shouldn't happen */
1974 ssh_packet_check_eom(ssh);
1976 /* Make the edits to known_hosts */
1977 update_known_hosts(ctx);
1979 hostkeys_update_ctx_free(ctx);
1983 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
1984 * Made slightly less trivial by the multiple RSA signature algorithm names.
1987 key_accepted_by_hostkeyalgs(const struct sshkey *key)
1989 const char *ktype = sshkey_ssh_name(key);
1990 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
1991 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
1993 if (key == NULL || key->type == KEY_UNSPEC)
1995 if (key->type == KEY_RSA &&
1996 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
1997 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
1999 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
2003 * Handle hostkeys-00@openssh.com global request to inform the client of all
2004 * the server's hostkeys. The keys are checked against the user's
2005 * HostkeyAlgorithms preference before they are accepted.
2008 client_input_hostkeys(void)
2010 struct ssh *ssh = active_state; /* XXX */
2011 const u_char *blob = NULL;
2013 struct sshbuf *buf = NULL;
2014 struct sshkey *key = NULL, **tmp;
2017 static int hostkeys_seen = 0; /* XXX use struct ssh */
2018 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2019 struct hostkeys_update_ctx *ctx = NULL;
2022 fatal("%s: server already sent hostkeys", __func__);
2023 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2025 return 1; /* won't ask in batchmode, so don't even try */
2026 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2029 ctx = xcalloc(1, sizeof(*ctx));
2030 while (ssh_packet_remaining(ssh) > 0) {
2033 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2034 error("%s: couldn't parse message: %s",
2035 __func__, ssh_err(r));
2038 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2039 error("%s: parse key: %s", __func__, ssh_err(r));
2042 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2044 debug3("%s: received %s key %s", __func__,
2045 sshkey_type(key), fp);
2048 if (!key_accepted_by_hostkeyalgs(key)) {
2049 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2050 __func__, sshkey_ssh_name(key));
2054 if (sshkey_is_cert(key)) {
2055 debug3("%s: %s key is a certificate; skipping",
2056 __func__, sshkey_ssh_name(key));
2059 /* Ensure keys are unique */
2060 for (i = 0; i < ctx->nkeys; i++) {
2061 if (sshkey_equal(key, ctx->keys[i])) {
2062 error("%s: received duplicated %s host key",
2063 __func__, sshkey_ssh_name(key));
2067 /* Key is good, record it */
2068 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2069 sizeof(*ctx->keys))) == NULL)
2070 fatal("%s: recallocarray failed nkeys = %zu",
2071 __func__, ctx->nkeys);
2073 ctx->keys[ctx->nkeys++] = key;
2077 if (ctx->nkeys == 0) {
2078 debug("%s: server sent no hostkeys", __func__);
2082 if ((ctx->keys_seen = calloc(ctx->nkeys,
2083 sizeof(*ctx->keys_seen))) == NULL)
2084 fatal("%s: calloc failed", __func__);
2086 get_hostfile_hostname_ipaddr(host,
2087 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2088 options.port, &ctx->host_str,
2089 options.check_host_ip ? &ctx->ip_str : NULL);
2091 /* Find which keys we already know about. */
2092 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2093 ctx, ctx->host_str, ctx->ip_str,
2094 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2095 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2099 /* Figure out if we have any new keys to add */
2101 for (i = 0; i < ctx->nkeys; i++) {
2102 if (!ctx->keys_seen[i])
2106 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2107 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2109 if (ctx->nnew == 0 && ctx->nold != 0) {
2110 /* We have some keys to remove. Just do it. */
2111 update_known_hosts(ctx);
2112 } else if (ctx->nnew != 0) {
2114 * We have received hitherto-unseen keys from the server.
2115 * Ask the server to confirm ownership of the private halves.
2117 debug3("%s: asking server to prove ownership for %zu keys",
2118 __func__, ctx->nnew);
2119 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2120 (r = sshpkt_put_cstring(ssh,
2121 "hostkeys-prove-00@openssh.com")) != 0 ||
2122 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2123 fatal("%s: cannot prepare packet: %s",
2124 __func__, ssh_err(r));
2125 if ((buf = sshbuf_new()) == NULL)
2126 fatal("%s: sshbuf_new", __func__);
2127 for (i = 0; i < ctx->nkeys; i++) {
2128 if (ctx->keys_seen[i])
2131 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2132 fatal("%s: sshkey_putb: %s",
2133 __func__, ssh_err(r));
2134 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2135 fatal("%s: sshpkt_put_string: %s",
2136 __func__, ssh_err(r));
2138 if ((r = sshpkt_send(ssh)) != 0)
2139 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2140 client_register_global_confirm(
2141 client_global_hostkeys_private_confirm, ctx);
2142 ctx = NULL; /* will be freed in callback */
2147 hostkeys_update_ctx_free(ctx);
2151 * NB. Return success for all cases. The server doesn't need to know
2152 * what the client does with its hosts file.
2158 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2164 rtype = packet_get_cstring(NULL);
2165 want_reply = packet_get_char();
2166 debug("client_input_global_request: rtype %s want_reply %d",
2168 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2169 success = client_input_hostkeys();
2171 packet_start(success ?
2172 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2174 packet_write_wait();
2181 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2182 const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2185 int i, j, matched, len;
2189 debug2("%s: id %d", __func__, id);
2191 if ((c = channel_lookup(ssh, id)) == NULL)
2192 fatal("%s: channel %d: unknown channel", __func__, id);
2194 packet_set_interactive(want_tty,
2195 options.ip_qos_interactive, options.ip_qos_bulk);
2200 /* Store window size in the packet. */
2201 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2202 memset(&ws, 0, sizeof(ws));
2204 channel_request_start(ssh, id, "pty-req", 1);
2205 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2206 packet_put_cstring(term != NULL ? term : "");
2207 packet_put_int((u_int)ws.ws_col);
2208 packet_put_int((u_int)ws.ws_row);
2209 packet_put_int((u_int)ws.ws_xpixel);
2210 packet_put_int((u_int)ws.ws_ypixel);
2212 tiop = get_saved_tio();
2213 ssh_tty_make_modes(ssh, -1, tiop);
2215 /* XXX wait for reply */
2219 /* Transfer any environment variables from client to server */
2220 if (options.num_send_env != 0 && env != NULL) {
2221 debug("Sending environment.");
2222 for (i = 0; env[i] != NULL; i++) {
2224 name = xstrdup(env[i]);
2225 if ((val = strchr(name, '=')) == NULL) {
2232 for (j = 0; j < options.num_send_env; j++) {
2233 if (match_pattern(name, options.send_env[j])) {
2239 debug3("Ignored env %s", name);
2244 debug("Sending env %s = %s", name, val);
2245 channel_request_start(ssh, id, "env", 0);
2246 packet_put_cstring(name);
2247 packet_put_cstring(val);
2252 for (i = 0; i < options.num_setenv; i++) {
2254 name = xstrdup(options.setenv[i]);
2255 if ((val = strchr(name, '=')) == NULL) {
2261 debug("Setting env %s = %s", name, val);
2262 channel_request_start(ssh, id, "env", 0);
2263 packet_put_cstring(name);
2264 packet_put_cstring(val);
2269 len = sshbuf_len(cmd);
2273 if (want_subsystem) {
2274 debug("Sending subsystem: %.*s",
2275 len, (const u_char*)sshbuf_ptr(cmd));
2276 channel_request_start(ssh, id, "subsystem", 1);
2277 client_expect_confirm(ssh, id, "subsystem",
2280 debug("Sending command: %.*s",
2281 len, (const u_char*)sshbuf_ptr(cmd));
2282 channel_request_start(ssh, id, "exec", 1);
2283 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2285 packet_put_string(sshbuf_ptr(cmd), sshbuf_len(cmd));
2288 channel_request_start(ssh, id, "shell", 1);
2289 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2295 client_init_dispatch(void)
2297 dispatch_init(&dispatch_protocol_error);
2299 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2300 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2301 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2302 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2303 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2304 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2305 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2306 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2307 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2308 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2309 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2310 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2313 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2315 /* global request reply messages */
2316 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2317 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2321 client_stop_mux(void)
2323 if (options.control_path != NULL && muxserver_sock != -1)
2324 unlink(options.control_path);
2326 * If we are in persist mode, or don't have a shell, signal that we
2327 * should close when all active channels are closed.
2329 if (options.control_persist || no_shell_flag) {
2331 setproctitle("[stopped mux]");
2335 /* client specific fatal cleanup */
2339 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2340 leave_non_blocking();
2341 if (options.control_path != NULL && muxserver_sock != -1)
2342 unlink(options.control_path);
2343 ssh_kill_proxy_command();