1 /* $OpenBSD: clientloop.c,v 1.318 2018/09/21 12:46:22 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The main loop for the interactive session (client side).
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * SSH2 support added by Markus Friedl.
39 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
50 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64 #include <sys/types.h>
65 #include <sys/ioctl.h>
66 #ifdef HAVE_SYS_STAT_H
67 # include <sys/stat.h>
69 #ifdef HAVE_SYS_TIME_H
70 # include <sys/time.h>
72 #include <sys/socket.h>
89 #include "openbsd-compat/sys-queue.h"
101 #include "myproposal.h"
104 #include "readconf.h"
105 #include "clientloop.h"
106 #include "sshconnect.h"
108 #include "atomicio.h"
113 #include "hostfile.h"
116 extern Options options;
118 /* Flag indicating that stdin should be redirected from /dev/null. */
119 extern int stdin_null_flag;
121 /* Flag indicating that no shell has been requested */
122 extern int no_shell_flag;
124 /* Flag indicating that ssh should daemonise after authentication is complete */
125 extern int fork_after_authentication_flag;
128 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
131 * Name of the host we are connecting to. This is the name given on the
132 * command line, or the HostName specified for the user-supplied name in a
133 * configuration file.
138 * Flag to indicate that we have received a window change signal which has
139 * not yet been processed. This will cause a message indicating the new
140 * window size to be sent to the server a little later. This is volatile
141 * because this is updated in a signal handler.
143 static volatile sig_atomic_t received_window_change_signal = 0;
144 static volatile sig_atomic_t received_signal = 0;
146 /* Flag indicating whether the user's terminal is in non-blocking mode. */
147 static int in_non_blocking_mode = 0;
149 /* Time when backgrounded control master using ControlPersist should exit */
150 static time_t control_persist_exit_time = 0;
152 /* Common data for the client loop code. */
153 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
154 static int last_was_cr; /* Last character was a newline. */
155 static int exit_status; /* Used to store the command exit status. */
156 static 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, 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__);
347 /* auth doesn't time out */
348 xasprintf(&cmd, "%s -f %s generate %s %s "
350 xauth_path, xauthfile, display,
351 SSH_X11_PROTO, _PATH_DEVNULL);
353 /* Add some slack to requested expiry */
354 if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
355 x11_timeout_real = timeout +
358 /* Don't overflow on long timeouts */
359 x11_timeout_real = UINT_MAX;
361 xasprintf(&cmd, "%s -f %s generate %s %s "
362 "untrusted timeout %u 2>%s",
363 xauth_path, xauthfile, display,
364 SSH_X11_PROTO, x11_timeout_real,
367 debug2("%s: %s", __func__, cmd);
369 if (timeout != 0 && x11_refuse_time == 0) {
370 now = monotime() + 1;
371 if (UINT_MAX - timeout < now)
372 x11_refuse_time = UINT_MAX;
374 x11_refuse_time = now + timeout;
375 channel_set_x11_refuse_time(ssh,
378 if (system(cmd) == 0)
384 * When in untrusted mode, we read the cookie only if it was
385 * successfully generated as an untrusted one in the step
388 if (trusted || generated) {
390 "%s %s%s list %s 2>" _PATH_DEVNULL,
392 generated ? "-f " : "" ,
393 generated ? xauthfile : "",
395 debug2("x11_get_proto: %s", cmd);
397 if (f && fgets(line, sizeof(line), f) &&
398 sscanf(line, "%*s %511s %511s", proto, data) == 2)
411 /* Don't fall back to fake X11 data for untrusted forwarding */
412 if (!trusted && !got_data) {
413 error("Warning: untrusted X11 forwarding setup failed: "
414 "xauth key data not generated");
419 * If we didn't get authentication data, just make up some
420 * data. The forwarding code will check the validity of the
421 * response anyway, and substitute this data. The X11
422 * server, however, will ignore this fake data and use
423 * whatever authentication mechanisms it was using otherwise
424 * for the local connection.
430 logit("Warning: No xauth data; "
431 "using fake authentication data for X11 forwarding.");
432 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
433 arc4random_buf(rnd, sizeof(rnd));
434 for (i = 0; i < sizeof(rnd); i++) {
435 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
444 * Checks if the client window has changed, and sends a packet about it to
445 * the server if so. The actual change is detected elsewhere (by a software
446 * interrupt on Unix); this just checks the flag and sends a message if
451 client_check_window_change(struct ssh *ssh)
453 if (!received_window_change_signal)
456 received_window_change_signal = 0;
458 debug2("%s: changed", __func__);
460 channel_send_window_changes(ssh);
464 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
466 struct global_confirm *gc;
468 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
471 gc->cb(ssh, type, seq, gc->ctx);
472 if (--gc->ref_count <= 0) {
473 TAILQ_REMOVE(&global_confirms, gc, entry);
474 explicit_bzero(gc, sizeof(*gc));
478 packet_set_alive_timeouts(0);
483 server_alive_check(void)
485 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
486 logit("Timeout, server %s not responding.", host);
489 packet_start(SSH2_MSG_GLOBAL_REQUEST);
490 packet_put_cstring("keepalive@openssh.com");
491 packet_put_char(1); /* boolean: want reply */
493 /* Insert an empty placeholder to maintain ordering */
494 client_register_global_confirm(NULL, NULL);
498 * Waits until the client can do something (some data becomes available on
499 * one of the file descriptors).
502 client_wait_until_can_do_something(struct ssh *ssh,
503 fd_set **readsetp, fd_set **writesetp,
504 int *maxfdp, u_int *nallocp, int rekeying)
506 struct timeval tv, *tvp;
508 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
511 /* Add any selections by the channel mechanism. */
512 channel_prepare_select(active_state, readsetp, writesetp, maxfdp,
513 nallocp, &minwait_secs);
515 /* channel_prepare_select could have closed the last channel */
516 if (session_closed && !channel_still_open(ssh) &&
517 !packet_have_data_to_write()) {
518 /* clear mask since we did not call select() */
519 memset(*readsetp, 0, *nallocp);
520 memset(*writesetp, 0, *nallocp);
524 FD_SET(connection_in, *readsetp);
526 /* Select server connection if have data to write to the server. */
527 if (packet_have_data_to_write())
528 FD_SET(connection_out, *writesetp);
531 * Wait for something to happen. This will suspend the process until
532 * some selected descriptor can be read, written, or has some other
533 * event pending, or a timeout expires.
536 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
537 if (options.server_alive_interval > 0) {
538 timeout_secs = options.server_alive_interval;
539 server_alive_time = now + options.server_alive_interval;
541 if (options.rekey_interval > 0 && !rekeying)
542 timeout_secs = MINIMUM(timeout_secs, packet_get_rekey_timeout());
543 set_control_persist_exit_time(ssh);
544 if (control_persist_exit_time > 0) {
545 timeout_secs = MINIMUM(timeout_secs,
546 control_persist_exit_time - now);
547 if (timeout_secs < 0)
550 if (minwait_secs != 0)
551 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
552 if (timeout_secs == INT_MAX)
555 tv.tv_sec = timeout_secs;
560 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
563 * We have to clear the select masks, because we return.
564 * We have to return, because the mainloop checks for the flags
565 * set by the signal handlers.
567 memset(*readsetp, 0, *nallocp);
568 memset(*writesetp, 0, *nallocp);
572 /* Note: we might still have data in the buffers. */
573 if ((r = sshbuf_putf(stderr_buffer,
574 "select: %s\r\n", strerror(errno))) != 0)
575 fatal("%s: buffer error: %s", __func__, ssh_err(r));
577 } else if (ret == 0) {
579 * Timeout. Could have been either keepalive or rekeying.
580 * Keepalive we check here, rekeying is checked in clientloop.
582 if (server_alive_time != 0 && server_alive_time <= monotime())
583 server_alive_check();
589 client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
591 /* Flush stdout and stderr buffers. */
592 if (sshbuf_len(bout) > 0)
593 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
595 if (sshbuf_len(berr) > 0)
596 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
599 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
605 /* Send the suspend signal to the program itself. */
606 kill(getpid(), SIGTSTP);
608 /* Reset window sizes in case they have changed */
609 received_window_change_signal = 1;
611 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
615 client_process_net_input(fd_set *readset)
617 char buf[SSH_IOBUFSZ];
621 * Read input from the server, and add any such data to the buffer of
622 * the packet subsystem.
624 if (FD_ISSET(connection_in, readset)) {
625 /* Read as much as possible. */
626 len = read(connection_in, buf, sizeof(buf));
629 * Received EOF. The remote host has closed the
632 if ((r = sshbuf_putf(stderr_buffer,
633 "Connection to %.300s closed by remote host.\r\n",
635 fatal("%s: buffer error: %s",
636 __func__, ssh_err(r));
641 * There is a kernel bug on Solaris that causes select to
642 * sometimes wake up even though there is no data available.
645 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
650 * An error has encountered. Perhaps there is a
653 if ((r = sshbuf_putf(stderr_buffer,
654 "Read from remote host %.300s: %.100s\r\n",
655 host, strerror(errno))) != 0)
656 fatal("%s: buffer error: %s",
657 __func__, ssh_err(r));
661 packet_process_incoming(buf, len);
666 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
668 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
673 * If a TTY was explicitly requested, then a failure to allocate
676 if (cr->action == CONFIRM_TTY &&
677 (options.request_tty == REQUEST_TTY_FORCE ||
678 options.request_tty == REQUEST_TTY_YES))
679 cr->action = CONFIRM_CLOSE;
681 /* XXX suppress on mux _client_ quietmode */
682 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
683 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
685 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
686 debug2("%s request accepted on channel %d",
687 cr->request_type, c->self);
688 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
690 snprintf(errmsg, sizeof(errmsg),
691 "%s request failed\r\n", cr->request_type);
693 snprintf(errmsg, sizeof(errmsg),
694 "%s request failed on channel %d",
695 cr->request_type, c->self);
697 /* If error occurred on primary session channel, then exit */
698 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
701 * If error occurred on mux client, append to
705 if ((r = sshbuf_put(c->extended, errmsg,
706 strlen(errmsg))) != 0)
707 fatal("%s: buffer error %s", __func__,
711 if (cr->action == CONFIRM_TTY) {
713 * If a TTY allocation error occurred, then arrange
714 * for the correct TTY to leave raw mode.
716 if (c->self == session_ident)
719 mux_tty_alloc_failed(ssh, c);
720 } else if (cr->action == CONFIRM_CLOSE) {
721 chan_read_failed(ssh, c);
722 chan_write_failed(ssh, c);
729 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
735 client_expect_confirm(struct ssh *ssh, int id, const char *request,
736 enum confirm_action action)
738 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
740 cr->request_type = request;
743 channel_register_status_confirm(ssh, id, client_status_confirm,
744 client_abandon_status_confirm, cr);
748 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
750 struct global_confirm *gc, *last_gc;
752 /* Coalesce identical callbacks */
753 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
754 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
755 if (++last_gc->ref_count >= INT_MAX)
756 fatal("%s: last_gc->ref_count = %d",
757 __func__, last_gc->ref_count);
761 gc = xcalloc(1, sizeof(*gc));
765 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
769 process_cmdline(struct ssh *ssh)
771 void (*handler)(int);
773 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
776 memset(&fwd, 0, sizeof(fwd));
778 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
779 handler = signal(SIGINT, SIG_IGN);
780 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
783 while (isspace((u_char)*s))
786 s++; /* Skip cmdline '-', if any */
790 if (*s == 'h' || *s == 'H' || *s == '?') {
792 logit(" -L[bind_address:]port:host:hostport "
793 "Request local forward");
794 logit(" -R[bind_address:]port:host:hostport "
795 "Request remote forward");
796 logit(" -D[bind_address:]port "
797 "Request dynamic forward");
798 logit(" -KL[bind_address:]port "
799 "Cancel local forward");
800 logit(" -KR[bind_address:]port "
801 "Cancel remote forward");
802 logit(" -KD[bind_address:]port "
803 "Cancel dynamic forward");
804 if (!options.permit_local_command)
807 "Execute local command");
811 if (*s == '!' && options.permit_local_command) {
828 logit("Invalid command.");
832 while (isspace((u_char)*++s))
835 /* XXX update list of forwards in options */
837 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
838 if (!parse_forward(&fwd, s, 1, 0)) {
839 logit("Bad forwarding close specification.");
843 ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
845 ok = channel_cancel_lport_listener(ssh, &fwd,
846 0, &options.fwd_opts) > 0;
848 ok = channel_cancel_lport_listener(ssh, &fwd,
849 CHANNEL_CANCEL_PORT_STATIC,
850 &options.fwd_opts) > 0;
852 logit("Unknown port forwarding.");
855 logit("Canceled forwarding.");
857 if (!parse_forward(&fwd, s, dynamic, remote)) {
858 logit("Bad forwarding specification.");
861 if (local || dynamic) {
862 if (!channel_setup_local_fwd_listener(ssh, &fwd,
863 &options.fwd_opts)) {
864 logit("Port forwarding failed.");
868 if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
869 logit("Port forwarding failed.");
873 logit("Forwarding port.");
877 signal(SIGINT, handler);
878 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
880 free(fwd.listen_host);
881 free(fwd.listen_path);
882 free(fwd.connect_host);
883 free(fwd.connect_path);
886 /* reasons to suppress output of an escape command in help output */
887 #define SUPPRESS_NEVER 0 /* never suppress, always show */
888 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
889 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
890 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
891 struct escape_help_text {
896 static struct escape_help_text esc_txt[] = {
897 {".", "terminate session", SUPPRESS_MUXMASTER},
898 {".", "terminate connection (and any multiplexed sessions)",
900 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
901 {"C", "open a command line", SUPPRESS_MUXCLIENT},
902 {"R", "request rekey", SUPPRESS_NEVER},
903 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
904 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
905 {"#", "list forwarded connections", SUPPRESS_NEVER},
906 {"&", "background ssh (when waiting for connections to terminate)",
908 {"?", "this message", SUPPRESS_NEVER},
912 print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
915 unsigned int i, suppress_flags;
918 if ((r = sshbuf_putf(b,
919 "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
920 fatal("%s: buffer error: %s", __func__, ssh_err(r));
923 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
924 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
925 (using_stderr ? 0 : SUPPRESS_SYSLOG);
927 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
928 if (esc_txt[i].flags & suppress_flags)
930 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
931 escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
932 fatal("%s: buffer error: %s", __func__, ssh_err(r));
935 if ((r = sshbuf_putf(b,
936 " %c%c - send the escape character by typing it twice\r\n"
937 "(Note that escapes are only recognized immediately after "
938 "newline.)\r\n", escape_char, escape_char)) != 0)
939 fatal("%s: buffer error: %s", __func__, ssh_err(r));
943 * Process the characters one by one.
946 process_escapes(struct ssh *ssh, Channel *c,
947 struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
955 struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
956 NULL : (struct escape_filter_ctx *)c->filter_ctx;
958 if (c->filter_ctx == NULL)
964 for (i = 0; i < (u_int)len; i++) {
965 /* Get one character at a time. */
968 if (efc->escape_pending) {
969 /* We have previously seen an escape character. */
970 /* Clear the flag now. */
971 efc->escape_pending = 0;
973 /* Process the escaped character. */
976 /* Terminate the connection. */
977 if ((r = sshbuf_putf(berr, "%c.\r\n",
978 efc->escape_char)) != 0)
979 fatal("%s: buffer error: %s",
980 __func__, ssh_err(r));
981 if (c && c->ctl_chan != -1) {
982 chan_read_failed(ssh, c);
983 chan_write_failed(ssh, c);
984 if (c->detach_user) {
988 c->type = SSH_CHANNEL_ABANDONED;
989 sshbuf_reset(c->input);
990 chan_ibuf_empty(ssh, c);
997 /* XXX support this for mux clients */
998 if (c && c->ctl_chan != -1) {
1002 snprintf(b, sizeof b, "^Z");
1004 snprintf(b, sizeof b, "%c", ch);
1005 if ((r = sshbuf_putf(berr,
1006 "%c%s escape not available to "
1007 "multiplexed sessions\r\n",
1008 efc->escape_char, b)) != 0)
1009 fatal("%s: buffer error: %s",
1010 __func__, ssh_err(r));
1013 /* Suspend the program. Inform the user */
1014 if ((r = sshbuf_putf(berr,
1015 "%c^Z [suspend ssh]\r\n",
1016 efc->escape_char)) != 0)
1017 fatal("%s: buffer error: %s",
1018 __func__, ssh_err(r));
1020 /* Restore terminal modes and suspend. */
1021 client_suspend_self(bin, bout, berr);
1023 /* We have been continued. */
1027 if ((r = sshbuf_putf(berr,
1028 "%cB\r\n", efc->escape_char)) != 0)
1029 fatal("%s: buffer error: %s",
1030 __func__, ssh_err(r));
1031 channel_request_start(ssh, c->self, "break", 0);
1032 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1033 (r = sshpkt_send(ssh)) != 0)
1034 fatal("%s: %s", __func__,
1039 if (datafellows & SSH_BUG_NOREKEY)
1040 logit("Server does not "
1041 "support re-keying");
1049 if (c && c->ctl_chan != -1)
1051 if (!log_is_on_stderr()) {
1052 if ((r = sshbuf_putf(berr,
1053 "%c%c [Logging to syslog]\r\n",
1054 efc->escape_char, ch)) != 0)
1055 fatal("%s: buffer error: %s",
1056 __func__, ssh_err(r));
1059 if (ch == 'V' && options.log_level >
1061 log_change_level(--options.log_level);
1062 if (ch == 'v' && options.log_level <
1063 SYSLOG_LEVEL_DEBUG3)
1064 log_change_level(++options.log_level);
1065 if ((r = sshbuf_putf(berr,
1066 "%c%c [LogLevel %s]\r\n",
1067 efc->escape_char, ch,
1068 log_level_name(options.log_level))) != 0)
1069 fatal("%s: buffer error: %s",
1070 __func__, ssh_err(r));
1074 if (c && c->ctl_chan != -1)
1077 * Detach the program (continue to serve
1078 * connections, but put in background and no
1079 * more new connections).
1081 /* Restore tty modes. */
1083 options.request_tty == REQUEST_TTY_FORCE);
1085 /* Stop listening for new connections. */
1086 channel_stop_listening(ssh);
1088 if ((r = sshbuf_putf(berr,
1089 "%c& [backgrounded]\n", efc->escape_char))
1091 fatal("%s: buffer error: %s",
1092 __func__, ssh_err(r));
1094 /* Fork into background. */
1097 error("fork: %.100s", strerror(errno));
1100 if (pid != 0) { /* This is the parent. */
1101 /* The parent just exits. */
1104 /* The child continues serving connections. */
1105 /* fake EOF on stdin */
1106 if ((r = sshbuf_put_u8(bin, 4)) != 0)
1107 fatal("%s: buffer error: %s",
1108 __func__, ssh_err(r));
1111 print_escape_help(berr, efc->escape_char,
1112 (c && c->ctl_chan != -1),
1113 log_is_on_stderr());
1117 if ((r = sshbuf_putf(berr, "%c#\r\n",
1118 efc->escape_char)) != 0)
1119 fatal("%s: buffer error: %s",
1120 __func__, ssh_err(r));
1121 s = channel_open_message(ssh);
1122 if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1123 fatal("%s: buffer error: %s",
1124 __func__, ssh_err(r));
1129 if (c && c->ctl_chan != -1)
1131 process_cmdline(ssh);
1135 if (ch != efc->escape_char) {
1136 if ((r = sshbuf_put_u8(bin,
1137 efc->escape_char)) != 0)
1138 fatal("%s: buffer error: %s",
1139 __func__, ssh_err(r));
1142 /* Escaped characters fall through here */
1147 * The previous character was not an escape char.
1148 * Check if this is an escape.
1150 if (last_was_cr && ch == efc->escape_char) {
1152 * It is. Set the flag and continue to
1155 efc->escape_pending = 1;
1161 * Normal character. Record whether it was a newline,
1162 * and append it to the buffer.
1164 last_was_cr = (ch == '\r' || ch == '\n');
1165 if ((r = sshbuf_put_u8(bin, ch)) != 0)
1166 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1173 * Get packets from the connection input buffer, and process them as long as
1174 * there are packets available.
1176 * Any unknown packets received during the actual
1177 * session cause the session to terminate. This is
1178 * intended to make debugging easier since no
1179 * confirmations are sent. Any compatible protocol
1180 * extensions must be negotiated during the
1181 * preparatory phase.
1185 client_process_buffered_input_packets(void)
1187 ssh_dispatch_run_fatal(active_state, DISPATCH_NONBLOCK, &quit_pending);
1190 /* scan buf[] for '~' before sending data to the peer */
1192 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1194 client_new_escape_filter_ctx(int escape_char)
1196 struct escape_filter_ctx *ret;
1198 ret = xcalloc(1, sizeof(*ret));
1199 ret->escape_pending = 0;
1200 ret->escape_char = escape_char;
1204 /* Free the escape filter context on channel free */
1206 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1212 client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1214 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1217 return process_escapes(ssh, c, c->input, c->output, c->extended,
1222 client_channel_closed(struct ssh *ssh, int id, void *arg)
1224 channel_cancel_cleanup(ssh, id);
1226 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1230 * Implements the interactive session with the server. This is called after
1231 * the user has been authenticated, and a command has been started on the
1232 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1233 * used as an escape character for terminating or suspending the session.
1236 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1239 fd_set *readset = NULL, *writeset = NULL;
1240 double start_time, total_time;
1241 int r, max_fd = 0, max_fd2 = 0, len;
1242 u_int64_t ibytes, obytes;
1246 debug("Entering interactive session.");
1248 if (options.control_master &&
1249 !option_clear_or_none(options.control_path)) {
1250 debug("pledge: id");
1251 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty",
1253 fatal("%s pledge(): %s", __func__, strerror(errno));
1255 } else if (options.forward_x11 || options.permit_local_command) {
1256 debug("pledge: exec");
1257 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1259 fatal("%s pledge(): %s", __func__, strerror(errno));
1261 } else if (options.update_hostkeys) {
1262 debug("pledge: filesystem full");
1263 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1265 fatal("%s pledge(): %s", __func__, strerror(errno));
1267 } else if (!option_clear_or_none(options.proxy_command) ||
1268 fork_after_authentication_flag) {
1269 debug("pledge: proc");
1270 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1271 fatal("%s pledge(): %s", __func__, strerror(errno));
1274 debug("pledge: network");
1275 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1276 fatal("%s pledge(): %s", __func__, strerror(errno));
1279 start_time = monotime_double();
1281 /* Initialize variables. */
1284 connection_in = packet_get_connection_in();
1285 connection_out = packet_get_connection_out();
1286 max_fd = MAXIMUM(connection_in, connection_out);
1290 /* Initialize buffer. */
1291 if ((stderr_buffer = sshbuf_new()) == NULL)
1292 fatal("%s: sshbuf_new failed", __func__);
1294 client_init_dispatch();
1297 * Set signal handlers, (e.g. to restore non-blocking mode)
1298 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1300 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1301 signal(SIGHUP, signal_handler);
1302 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1303 signal(SIGINT, signal_handler);
1304 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1305 signal(SIGQUIT, signal_handler);
1306 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1307 signal(SIGTERM, signal_handler);
1308 signal(SIGWINCH, window_change_handler);
1311 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1313 session_ident = ssh2_chan_id;
1314 if (session_ident != -1) {
1315 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1316 channel_register_filter(ssh, session_ident,
1317 client_simple_escape_filter, NULL,
1318 client_filter_cleanup,
1319 client_new_escape_filter_ctx(
1322 channel_register_cleanup(ssh, session_ident,
1323 client_channel_closed, 0);
1326 /* Main loop of the client for the interactive session mode. */
1327 while (!quit_pending) {
1329 /* Process buffered packets sent by the server. */
1330 client_process_buffered_input_packets();
1332 if (session_closed && !channel_still_open(ssh))
1335 if (ssh_packet_is_rekeying(ssh)) {
1336 debug("rekeying in progress");
1337 } else if (need_rekeying) {
1338 /* manual rekey request */
1339 debug("need rekeying");
1340 if ((r = kex_start_rekex(ssh)) != 0)
1341 fatal("%s: kex_start_rekex: %s", __func__,
1346 * Make packets from buffered channel data, and
1347 * enqueue them for sending to the server.
1349 if (packet_not_very_much_data_to_write())
1350 channel_output_poll(ssh);
1353 * Check if the window size has changed, and buffer a
1354 * message about it to the server if so.
1356 client_check_window_change(ssh);
1362 * Wait until we have something to do (something becomes
1363 * available on one of the descriptors).
1366 client_wait_until_can_do_something(ssh, &readset, &writeset,
1367 &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
1372 /* Do channel operations unless rekeying in progress. */
1373 if (!ssh_packet_is_rekeying(ssh))
1374 channel_after_select(ssh, readset, writeset);
1376 /* Buffer input from the connection. */
1377 client_process_net_input(readset);
1383 * Send as much buffered packet data as possible to the
1386 if (FD_ISSET(connection_out, writeset))
1387 packet_write_poll();
1390 * If we are a backgrounded control master, and the
1391 * timeout has expired without any active client
1392 * connections, then quit.
1394 if (control_persist_exit_time > 0) {
1395 if (monotime() >= control_persist_exit_time) {
1396 debug("ControlPersist timeout expired");
1404 /* Terminate the session. */
1406 /* Stop watching for window change. */
1407 signal(SIGWINCH, SIG_DFL);
1409 packet_start(SSH2_MSG_DISCONNECT);
1410 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1411 packet_put_cstring("disconnected by user");
1412 packet_put_cstring(""); /* language tag */
1414 packet_write_wait();
1416 channel_free_all(ssh);
1419 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1421 /* restore blocking io */
1422 if (!isatty(fileno(stdin)))
1423 unset_nonblock(fileno(stdin));
1424 if (!isatty(fileno(stdout)))
1425 unset_nonblock(fileno(stdout));
1426 if (!isatty(fileno(stderr)))
1427 unset_nonblock(fileno(stderr));
1430 * If there was no shell or command requested, there will be no remote
1431 * exit status to be returned. In that case, clear error code if the
1432 * connection was deliberately terminated at this end.
1434 if (no_shell_flag && received_signal == SIGTERM) {
1435 received_signal = 0;
1439 if (received_signal) {
1440 verbose("Killed by signal %d.", (int) received_signal);
1445 * In interactive mode (with pseudo tty) display a message indicating
1446 * that the connection has been closed.
1448 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1449 if ((r = sshbuf_putf(stderr_buffer,
1450 "Connection to %.64s closed.\r\n", host)) != 0)
1451 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1454 /* Output any buffered data for stderr. */
1455 if (sshbuf_len(stderr_buffer) > 0) {
1456 len = atomicio(vwrite, fileno(stderr),
1457 (u_char *)sshbuf_ptr(stderr_buffer),
1458 sshbuf_len(stderr_buffer));
1459 if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
1460 error("Write failed flushing stderr buffer.");
1461 else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
1462 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1465 /* Clear and free any buffers. */
1466 explicit_bzero(buf, sizeof(buf));
1467 sshbuf_free(stderr_buffer);
1469 /* Report bytes transferred, and transfer rates. */
1470 total_time = monotime_double() - start_time;
1471 packet_get_bytes(&ibytes, &obytes);
1472 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1473 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1475 verbose("Bytes per second: sent %.1f, received %.1f",
1476 obytes / total_time, ibytes / total_time);
1477 /* Return the exit status of the program. */
1478 debug("Exit status %d", exit_status);
1485 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1486 int rchan, u_int rwindow, u_int rmaxpack)
1489 struct sshbuf *b = NULL;
1490 char *listen_address, *originator_address;
1491 u_short listen_port, originator_port;
1494 /* Get rest of the packet */
1495 listen_address = packet_get_string(NULL);
1496 listen_port = packet_get_int();
1497 originator_address = packet_get_string(NULL);
1498 originator_port = packet_get_int();
1501 debug("%s: listen %s port %d, originator %s port %d", __func__,
1502 listen_address, listen_port, originator_address, originator_port);
1504 c = channel_connect_by_listen_address(ssh, listen_address, listen_port,
1505 "forwarded-tcpip", originator_address);
1507 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1508 if ((b = sshbuf_new()) == NULL) {
1509 error("%s: alloc reply", __func__);
1512 /* reconstruct and send to muxclient */
1513 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1514 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1515 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1516 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1517 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1518 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1519 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1520 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1521 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1522 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1523 (r = sshbuf_put_stringb(c->output, b)) != 0) {
1524 error("%s: compose for muxclient %s", __func__,
1532 free(originator_address);
1533 free(listen_address);
1538 client_request_forwarded_streamlocal(struct ssh *ssh,
1539 const char *request_type, int rchan)
1544 /* Get the remote path. */
1545 listen_path = packet_get_string(NULL);
1546 /* XXX: Skip reserved field for now. */
1547 if (packet_get_string_ptr(NULL) == NULL)
1548 fatal("%s: packet_get_string_ptr failed", __func__);
1551 debug("%s: %s", __func__, listen_path);
1553 c = channel_connect_by_listen_path(ssh, listen_path,
1554 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1560 client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1564 u_short originator_port;
1567 if (!options.forward_x11) {
1568 error("Warning: ssh server tried X11 forwarding.");
1569 error("Warning: this is probably a break-in attempt by a "
1570 "malicious server.");
1573 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1574 verbose("Rejected X11 connection after ForwardX11Timeout "
1578 originator = packet_get_string(NULL);
1579 originator_port = packet_get_int();
1581 /* XXX check permission */
1582 debug("client_request_x11: request from %s %d", originator,
1585 sock = x11_connect_display(ssh);
1588 c = channel_new(ssh, "x11",
1589 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1590 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1596 client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1601 if (!options.forward_agent) {
1602 error("Warning: ssh server tried agent forwarding.");
1603 error("Warning: this is probably a break-in attempt by a "
1604 "malicious server.");
1607 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1608 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1609 debug("%s: ssh_get_authentication_socket: %s",
1610 __func__, ssh_err(r));
1613 c = channel_new(ssh, "authentication agent connection",
1614 SSH_CHANNEL_OPEN, sock, sock, -1,
1615 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1616 "authentication agent connection", 1);
1622 client_request_tun_fwd(struct ssh *ssh, int tun_mode,
1623 int local_tun, int remote_tun)
1627 char *ifname = NULL;
1629 if (tun_mode == SSH_TUNMODE_NO)
1632 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1634 /* Open local tunnel device */
1635 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
1636 error("Tunnel device open failed.");
1639 debug("Tunnel forwarding using interface %s", ifname);
1641 c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1642 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1645 #if defined(SSH_TUN_FILTER)
1646 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1647 channel_register_filter(ssh, c->self, sys_tun_infilter,
1648 sys_tun_outfilter, NULL, NULL);
1651 packet_start(SSH2_MSG_CHANNEL_OPEN);
1652 packet_put_cstring("tun@openssh.com");
1653 packet_put_int(c->self);
1654 packet_put_int(c->local_window_max);
1655 packet_put_int(c->local_maxpacket);
1656 packet_put_int(tun_mode);
1657 packet_put_int(remote_tun);
1663 /* XXXX move to generic input handler */
1665 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1670 u_int rmaxpack, rwindow, len;
1672 ctype = packet_get_string(&len);
1673 rchan = packet_get_int();
1674 rwindow = packet_get_int();
1675 rmaxpack = packet_get_int();
1677 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1678 ctype, rchan, rwindow, rmaxpack);
1680 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1681 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1683 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1684 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1685 } else if (strcmp(ctype, "x11") == 0) {
1686 c = client_request_x11(ssh, ctype, rchan);
1687 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1688 c = client_request_agent(ssh, ctype, rchan);
1690 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1691 debug3("proxied to downstream: %s", ctype);
1692 } else if (c != NULL) {
1693 debug("confirm %s", ctype);
1694 c->remote_id = rchan;
1695 c->have_remote_id = 1;
1696 c->remote_window = rwindow;
1697 c->remote_maxpacket = rmaxpack;
1698 if (c->type != SSH_CHANNEL_CONNECTING) {
1699 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1700 packet_put_int(c->remote_id);
1701 packet_put_int(c->self);
1702 packet_put_int(c->local_window);
1703 packet_put_int(c->local_maxpacket);
1707 debug("failure %s", ctype);
1708 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1709 packet_put_int(rchan);
1710 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1711 packet_put_cstring("open failed");
1712 packet_put_cstring("");
1720 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1723 int exitval, id, reply, success = 0;
1726 id = packet_get_int();
1727 c = channel_lookup(ssh, id);
1728 if (channel_proxy_upstream(c, type, seq, ssh))
1730 rtype = packet_get_string(NULL);
1731 reply = packet_get_char();
1733 debug("client_input_channel_req: channel %d rtype %s reply %d",
1737 error("client_input_channel_req: request for channel -1");
1738 } else if (c == NULL) {
1739 error("client_input_channel_req: channel %d: "
1740 "unknown channel", id);
1741 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1743 chan_rcvd_eow(ssh, c);
1744 } else if (strcmp(rtype, "exit-status") == 0) {
1745 exitval = packet_get_int();
1746 if (c->ctl_chan != -1) {
1747 mux_exit_message(ssh, c, exitval);
1749 } else if (id == session_ident) {
1750 /* Record exit value of local session */
1752 exit_status = exitval;
1754 /* Probably for a mux channel that has already closed */
1755 debug("%s: no sink for exit-status on channel %d",
1760 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1761 if (!c->have_remote_id)
1762 fatal("%s: channel %d: no remote_id",
1764 packet_start(success ?
1765 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1766 packet_put_int(c->remote_id);
1773 struct hostkeys_update_ctx {
1774 /* The hostname and (optionally) IP address string for the server */
1775 char *host_str, *ip_str;
1778 * Keys received from the server and a flag for each indicating
1779 * whether they already exist in known_hosts.
1780 * keys_seen is filled in by hostkeys_find() and later (for new
1781 * keys) by client_global_hostkeys_private_confirm().
1783 struct sshkey **keys;
1788 * Keys that are in known_hosts, but were not present in the update
1789 * from the server (i.e. scheduled to be deleted).
1790 * Filled in by hostkeys_find().
1792 struct sshkey **old_keys;
1797 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
1803 for (i = 0; i < ctx->nkeys; i++)
1804 sshkey_free(ctx->keys[i]);
1806 free(ctx->keys_seen);
1807 for (i = 0; i < ctx->nold; i++)
1808 sshkey_free(ctx->old_keys[i]);
1809 free(ctx->old_keys);
1810 free(ctx->host_str);
1816 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
1818 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1820 struct sshkey **tmp;
1822 if (l->status != HKF_STATUS_MATCHED || l->key == NULL)
1825 /* Mark off keys we've already seen for this host */
1826 for (i = 0; i < ctx->nkeys; i++) {
1827 if (sshkey_equal(l->key, ctx->keys[i])) {
1828 debug3("%s: found %s key at %s:%ld", __func__,
1829 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
1830 ctx->keys_seen[i] = 1;
1834 /* This line contained a key that not offered by the server */
1835 debug3("%s: deprecated %s key at %s:%ld", __func__,
1836 sshkey_ssh_name(l->key), l->path, l->linenum);
1837 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1838 sizeof(*ctx->old_keys))) == NULL)
1839 fatal("%s: recallocarray failed nold = %zu",
1840 __func__, ctx->nold);
1841 ctx->old_keys = tmp;
1842 ctx->old_keys[ctx->nold++] = l->key;
1849 update_known_hosts(struct hostkeys_update_ctx *ctx)
1852 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
1853 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
1854 char *fp, *response;
1857 for (i = 0; i < ctx->nkeys; i++) {
1858 if (ctx->keys_seen[i] != 2)
1860 if ((fp = sshkey_fingerprint(ctx->keys[i],
1861 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1862 fatal("%s: sshkey_fingerprint failed", __func__);
1863 do_log2(loglevel, "Learned new hostkey: %s %s",
1864 sshkey_type(ctx->keys[i]), fp);
1867 for (i = 0; i < ctx->nold; i++) {
1868 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
1869 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1870 fatal("%s: sshkey_fingerprint failed", __func__);
1871 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
1872 sshkey_type(ctx->old_keys[i]), fp);
1875 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1876 if (get_saved_tio() != NULL) {
1881 for (i = 0; !quit_pending && i < 3; i++) {
1883 response = read_passphrase("Accept updated hostkeys? "
1884 "(yes/no): ", RP_ECHO);
1885 if (strcasecmp(response, "yes") == 0)
1887 else if (quit_pending || response == NULL ||
1888 strcasecmp(response, "no") == 0) {
1889 options.update_hostkeys = 0;
1892 do_log2(loglevel, "Please enter "
1893 "\"yes\" or \"no\"");
1896 if (quit_pending || i >= 3 || response == NULL)
1897 options.update_hostkeys = 0;
1904 * Now that all the keys are verified, we can go ahead and replace
1905 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
1906 * cancel the operation).
1908 if (options.update_hostkeys != 0 &&
1909 (r = hostfile_replace_entries(options.user_hostfiles[0],
1910 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
1911 options.hash_known_hosts, 0,
1912 options.fingerprint_hash)) != 0)
1913 error("%s: hostfile_replace_entries failed: %s",
1914 __func__, ssh_err(r));
1918 client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
1919 u_int32_t seq, void *_ctx)
1921 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1923 struct sshbuf *signdata;
1924 int r, kexsigtype, use_kexsigtype;
1929 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
1930 if (type != SSH2_MSG_REQUEST_SUCCESS) {
1931 error("Server failed to confirm ownership of "
1932 "private host keys");
1933 hostkeys_update_ctx_free(ctx);
1936 kexsigtype = sshkey_type_plain(
1937 sshkey_type_from_name(ssh->kex->hostkey_alg));
1939 if ((signdata = sshbuf_new()) == NULL)
1940 fatal("%s: sshbuf_new failed", __func__);
1941 /* Don't want to accidentally accept an unbound signature */
1942 if (ssh->kex->session_id_len == 0)
1943 fatal("%s: ssh->kex->session_id_len == 0", __func__);
1945 * Expect a signature for each of the ctx->nnew private keys we
1946 * haven't seen before. They will be in the same order as the
1947 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
1949 for (ndone = i = 0; i < ctx->nkeys; i++) {
1950 if (ctx->keys_seen[i])
1952 /* Prepare data to be signed: session ID, unique string, key */
1953 sshbuf_reset(signdata);
1954 if ( (r = sshbuf_put_cstring(signdata,
1955 "hostkeys-prove-00@openssh.com")) != 0 ||
1956 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
1957 ssh->kex->session_id_len)) != 0 ||
1958 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
1959 fatal("%s: failed to prepare signature: %s",
1960 __func__, ssh_err(r));
1961 /* Extract and verify signature */
1962 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
1963 error("%s: couldn't parse message: %s",
1964 __func__, ssh_err(r));
1968 * For RSA keys, prefer to use the signature type negotiated
1969 * during KEX to the default (SHA1).
1971 use_kexsigtype = kexsigtype == KEY_RSA &&
1972 sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA;
1973 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
1974 sshbuf_ptr(signdata), sshbuf_len(signdata),
1975 use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0)) != 0) {
1976 error("%s: server gave bad signature for %s key %zu",
1977 __func__, sshkey_type(ctx->keys[i]), i);
1980 /* Key is good. Mark it as 'seen' */
1981 ctx->keys_seen[i] = 2;
1984 if (ndone != ctx->nnew)
1985 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
1986 ndone, ctx->nnew); /* Shouldn't happen */
1987 ssh_packet_check_eom(ssh);
1989 /* Make the edits to known_hosts */
1990 update_known_hosts(ctx);
1992 hostkeys_update_ctx_free(ctx);
1996 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
1997 * Made slightly less trivial by the multiple RSA signature algorithm names.
2000 key_accepted_by_hostkeyalgs(const struct sshkey *key)
2002 const char *ktype = sshkey_ssh_name(key);
2003 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ?
2004 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG;
2006 if (key == NULL || key->type == KEY_UNSPEC)
2008 if (key->type == KEY_RSA &&
2009 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
2010 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
2012 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
2016 * Handle hostkeys-00@openssh.com global request to inform the client of all
2017 * the server's hostkeys. The keys are checked against the user's
2018 * HostkeyAlgorithms preference before they are accepted.
2021 client_input_hostkeys(void)
2023 struct ssh *ssh = active_state; /* XXX */
2024 const u_char *blob = NULL;
2026 struct sshbuf *buf = NULL;
2027 struct sshkey *key = NULL, **tmp;
2030 static int hostkeys_seen = 0; /* XXX use struct ssh */
2031 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2032 struct hostkeys_update_ctx *ctx = NULL;
2035 fatal("%s: server already sent hostkeys", __func__);
2036 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2038 return 1; /* won't ask in batchmode, so don't even try */
2039 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2042 ctx = xcalloc(1, sizeof(*ctx));
2043 while (ssh_packet_remaining(ssh) > 0) {
2046 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2047 error("%s: couldn't parse message: %s",
2048 __func__, ssh_err(r));
2051 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2052 error("%s: parse key: %s", __func__, ssh_err(r));
2055 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2057 debug3("%s: received %s key %s", __func__,
2058 sshkey_type(key), fp);
2061 if (!key_accepted_by_hostkeyalgs(key)) {
2062 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2063 __func__, sshkey_ssh_name(key));
2067 if (sshkey_is_cert(key)) {
2068 debug3("%s: %s key is a certificate; skipping",
2069 __func__, sshkey_ssh_name(key));
2072 /* Ensure keys are unique */
2073 for (i = 0; i < ctx->nkeys; i++) {
2074 if (sshkey_equal(key, ctx->keys[i])) {
2075 error("%s: received duplicated %s host key",
2076 __func__, sshkey_ssh_name(key));
2080 /* Key is good, record it */
2081 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2082 sizeof(*ctx->keys))) == NULL)
2083 fatal("%s: recallocarray failed nkeys = %zu",
2084 __func__, ctx->nkeys);
2086 ctx->keys[ctx->nkeys++] = key;
2090 if (ctx->nkeys == 0) {
2091 debug("%s: server sent no hostkeys", __func__);
2095 if ((ctx->keys_seen = calloc(ctx->nkeys,
2096 sizeof(*ctx->keys_seen))) == NULL)
2097 fatal("%s: calloc failed", __func__);
2099 get_hostfile_hostname_ipaddr(host,
2100 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2101 options.port, &ctx->host_str,
2102 options.check_host_ip ? &ctx->ip_str : NULL);
2104 /* Find which keys we already know about. */
2105 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2106 ctx, ctx->host_str, ctx->ip_str,
2107 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2108 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2112 /* Figure out if we have any new keys to add */
2114 for (i = 0; i < ctx->nkeys; i++) {
2115 if (!ctx->keys_seen[i])
2119 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2120 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2122 if (ctx->nnew == 0 && ctx->nold != 0) {
2123 /* We have some keys to remove. Just do it. */
2124 update_known_hosts(ctx);
2125 } else if (ctx->nnew != 0) {
2127 * We have received hitherto-unseen keys from the server.
2128 * Ask the server to confirm ownership of the private halves.
2130 debug3("%s: asking server to prove ownership for %zu keys",
2131 __func__, ctx->nnew);
2132 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2133 (r = sshpkt_put_cstring(ssh,
2134 "hostkeys-prove-00@openssh.com")) != 0 ||
2135 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2136 fatal("%s: cannot prepare packet: %s",
2137 __func__, ssh_err(r));
2138 if ((buf = sshbuf_new()) == NULL)
2139 fatal("%s: sshbuf_new", __func__);
2140 for (i = 0; i < ctx->nkeys; i++) {
2141 if (ctx->keys_seen[i])
2144 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2145 fatal("%s: sshkey_putb: %s",
2146 __func__, ssh_err(r));
2147 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2148 fatal("%s: sshpkt_put_string: %s",
2149 __func__, ssh_err(r));
2151 if ((r = sshpkt_send(ssh)) != 0)
2152 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2153 client_register_global_confirm(
2154 client_global_hostkeys_private_confirm, ctx);
2155 ctx = NULL; /* will be freed in callback */
2160 hostkeys_update_ctx_free(ctx);
2164 * NB. Return success for all cases. The server doesn't need to know
2165 * what the client does with its hosts file.
2171 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2177 rtype = packet_get_cstring(NULL);
2178 want_reply = packet_get_char();
2179 debug("client_input_global_request: rtype %s want_reply %d",
2181 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2182 success = client_input_hostkeys();
2184 packet_start(success ?
2185 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2187 packet_write_wait();
2194 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2195 const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2198 int i, j, matched, len;
2202 debug2("%s: id %d", __func__, id);
2204 if ((c = channel_lookup(ssh, id)) == NULL)
2205 fatal("%s: channel %d: unknown channel", __func__, id);
2207 packet_set_interactive(want_tty,
2208 options.ip_qos_interactive, options.ip_qos_bulk);
2213 /* Store window size in the packet. */
2214 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2215 memset(&ws, 0, sizeof(ws));
2217 channel_request_start(ssh, id, "pty-req", 1);
2218 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2219 packet_put_cstring(term != NULL ? term : "");
2220 packet_put_int((u_int)ws.ws_col);
2221 packet_put_int((u_int)ws.ws_row);
2222 packet_put_int((u_int)ws.ws_xpixel);
2223 packet_put_int((u_int)ws.ws_ypixel);
2225 tiop = get_saved_tio();
2226 ssh_tty_make_modes(ssh, -1, tiop);
2228 /* XXX wait for reply */
2232 /* Transfer any environment variables from client to server */
2233 if (options.num_send_env != 0 && env != NULL) {
2234 debug("Sending environment.");
2235 for (i = 0; env[i] != NULL; i++) {
2237 name = xstrdup(env[i]);
2238 if ((val = strchr(name, '=')) == NULL) {
2245 for (j = 0; j < options.num_send_env; j++) {
2246 if (match_pattern(name, options.send_env[j])) {
2252 debug3("Ignored env %s", name);
2257 debug("Sending env %s = %s", name, val);
2258 channel_request_start(ssh, id, "env", 0);
2259 packet_put_cstring(name);
2260 packet_put_cstring(val);
2265 for (i = 0; i < options.num_setenv; i++) {
2267 name = xstrdup(options.setenv[i]);
2268 if ((val = strchr(name, '=')) == NULL) {
2274 debug("Setting env %s = %s", name, val);
2275 channel_request_start(ssh, id, "env", 0);
2276 packet_put_cstring(name);
2277 packet_put_cstring(val);
2282 len = sshbuf_len(cmd);
2286 if (want_subsystem) {
2287 debug("Sending subsystem: %.*s",
2288 len, (const u_char*)sshbuf_ptr(cmd));
2289 channel_request_start(ssh, id, "subsystem", 1);
2290 client_expect_confirm(ssh, id, "subsystem",
2293 debug("Sending command: %.*s",
2294 len, (const u_char*)sshbuf_ptr(cmd));
2295 channel_request_start(ssh, id, "exec", 1);
2296 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2298 packet_put_string(sshbuf_ptr(cmd), sshbuf_len(cmd));
2301 channel_request_start(ssh, id, "shell", 1);
2302 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2308 client_init_dispatch(void)
2310 dispatch_init(&dispatch_protocol_error);
2312 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2313 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2314 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2315 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2316 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2317 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2318 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2319 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2320 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2321 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2322 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2323 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2326 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2328 /* global request reply messages */
2329 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2330 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2334 client_stop_mux(void)
2336 if (options.control_path != NULL && muxserver_sock != -1)
2337 unlink(options.control_path);
2339 * If we are in persist mode, or don't have a shell, signal that we
2340 * should close when all active channels are closed.
2342 if (options.control_persist || no_shell_flag) {
2344 setproctitle("[stopped mux]");
2348 /* client specific fatal cleanup */
2352 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2353 leave_non_blocking();
2354 if (options.control_path != NULL && muxserver_sock != -1)
2355 unlink(options.control_path);
2356 ssh_kill_proxy_command();