1 /* $OpenBSD: clientloop.c,v 1.370 2021/08/29 23:44:07 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;
119 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
122 * Name of the host we are connecting to. This is the name given on the
123 * command line, or the Hostname specified for the user-supplied name in a
124 * configuration file.
129 * If this field is not NULL, the ForwardAgent socket is this path and different
130 * instead of SSH_AUTH_SOCK.
132 extern char *forward_agent_sock_path;
135 * Flag to indicate that we have received a window change signal which has
136 * not yet been processed. This will cause a message indicating the new
137 * window size to be sent to the server a little later. This is volatile
138 * because this is updated in a signal handler.
140 static volatile sig_atomic_t received_window_change_signal = 0;
141 static volatile sig_atomic_t received_signal = 0;
143 /* Time when backgrounded control master using ControlPersist should exit */
144 static time_t control_persist_exit_time = 0;
146 /* Common data for the client loop code. */
147 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
148 static int last_was_cr; /* Last character was a newline. */
149 static int exit_status; /* Used to store the command exit status. */
150 static struct sshbuf *stderr_buffer; /* Used for final exit message. */
151 static int connection_in; /* Connection to server (input). */
152 static int connection_out; /* Connection to server (output). */
153 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
154 static int session_closed; /* In SSH2: login session closed. */
155 static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
156 static time_t server_alive_time; /* Time to do server_alive_check */
158 static void client_init_dispatch(struct ssh *ssh);
159 int session_ident = -1;
161 /* Track escape per proto2 channel */
162 struct escape_filter_ctx {
167 /* Context for channel confirmation replies */
168 struct channel_reply_ctx {
169 const char *request_type;
171 enum confirm_action action;
174 /* Global request success/failure callbacks */
175 /* XXX move to struct ssh? */
176 struct global_confirm {
177 TAILQ_ENTRY(global_confirm) entry;
178 global_confirm_cb *cb;
182 TAILQ_HEAD(global_confirms, global_confirm);
183 static struct global_confirms global_confirms =
184 TAILQ_HEAD_INITIALIZER(global_confirms);
186 void ssh_process_session2_setup(int, int, int, struct sshbuf *);
189 * Signal handler for the window change signal (SIGWINCH). This just sets a
190 * flag indicating that the window has changed.
194 window_change_handler(int sig)
196 received_window_change_signal = 1;
200 * Signal handler for signals that cause the program to terminate. These
201 * signals must be trapped to restore terminal modes.
205 signal_handler(int sig)
207 received_signal = sig;
212 * Sets control_persist_exit_time to the absolute time when the
213 * backgrounded control master should exit due to expiry of the
214 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
215 * control master process, or if there is no ControlPersist timeout.
218 set_control_persist_exit_time(struct ssh *ssh)
220 if (muxserver_sock == -1 || !options.control_persist
221 || options.control_persist_timeout == 0) {
222 /* not using a ControlPersist timeout */
223 control_persist_exit_time = 0;
224 } else if (channel_still_open(ssh)) {
225 /* some client connections are still open */
226 if (control_persist_exit_time > 0)
227 debug2_f("cancel scheduled exit");
228 control_persist_exit_time = 0;
229 } else if (control_persist_exit_time <= 0) {
230 /* a client connection has recently closed */
231 control_persist_exit_time = monotime() +
232 (time_t)options.control_persist_timeout;
233 debug2_f("schedule exit in %d seconds",
234 options.control_persist_timeout);
236 /* else we are already counting down to the timeout */
239 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
241 client_x11_display_valid(const char *display)
248 dlen = strlen(display);
249 for (i = 0; i < dlen; i++) {
250 if (!isalnum((u_char)display[i]) &&
251 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
252 debug("Invalid character '%c' in DISPLAY", display[i]);
259 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
260 #define X11_TIMEOUT_SLACK 60
262 client_x11_get_proto(struct ssh *ssh, const char *display,
263 const char *xauth_path, u_int trusted, u_int timeout,
264 char **_proto, char **_data)
266 char *cmd, line[512], xdisplay[512];
267 char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
268 static char proto[512], data[512];
270 int got_data = 0, generated = 0, do_unlink = 0, r;
272 u_int now, x11_timeout_real;
276 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
278 if (!client_x11_display_valid(display)) {
280 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
284 if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
285 debug("No xauth program.");
289 if (xauth_path != NULL) {
291 * Handle FamilyLocal case where $DISPLAY does
292 * not match an authorization entry. For this we
293 * just try "xauth list unix:displaynum.screennum".
294 * XXX: "localhost" match to determine FamilyLocal
297 if (strncmp(display, "localhost:", 10) == 0) {
298 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
299 display + 10)) < 0 ||
300 (size_t)r >= sizeof(xdisplay)) {
301 error_f("display name too long");
308 * Generate an untrusted X11 auth cookie.
310 * The authentication cookie should briefly outlive
311 * ssh's willingness to forward X11 connections to
312 * avoid nasty fail-open behaviour in the X server.
314 mktemp_proto(xauthdir, sizeof(xauthdir));
315 if (mkdtemp(xauthdir) == NULL) {
316 error_f("mkdtemp: %s", strerror(errno));
320 if ((r = snprintf(xauthfile, sizeof(xauthfile),
321 "%s/xauthfile", xauthdir)) < 0 ||
322 (size_t)r >= sizeof(xauthfile)) {
323 error_f("xauthfile path too long");
329 /* auth doesn't time out */
330 xasprintf(&cmd, "%s -f %s generate %s %s "
332 xauth_path, xauthfile, display,
333 SSH_X11_PROTO, _PATH_DEVNULL);
335 /* Add some slack to requested expiry */
336 if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
337 x11_timeout_real = timeout +
340 /* Don't overflow on long timeouts */
341 x11_timeout_real = UINT_MAX;
343 xasprintf(&cmd, "%s -f %s generate %s %s "
344 "untrusted timeout %u 2>%s",
345 xauth_path, xauthfile, display,
346 SSH_X11_PROTO, x11_timeout_real,
349 debug2_f("xauth command: %s", cmd);
351 if (timeout != 0 && x11_refuse_time == 0) {
352 now = monotime() + 1;
353 if (UINT_MAX - timeout < now)
354 x11_refuse_time = UINT_MAX;
356 x11_refuse_time = now + timeout;
357 channel_set_x11_refuse_time(ssh,
360 if (system(cmd) == 0)
366 * When in untrusted mode, we read the cookie only if it was
367 * successfully generated as an untrusted one in the step
370 if (trusted || generated) {
372 "%s %s%s list %s 2>" _PATH_DEVNULL,
374 generated ? "-f " : "" ,
375 generated ? xauthfile : "",
377 debug2("x11_get_proto: %s", cmd);
379 if (f && fgets(line, sizeof(line), f) &&
380 sscanf(line, "%*s %511s %511s", proto, data) == 2)
393 /* Don't fall back to fake X11 data for untrusted forwarding */
394 if (!trusted && !got_data) {
395 error("Warning: untrusted X11 forwarding setup failed: "
396 "xauth key data not generated");
401 * If we didn't get authentication data, just make up some
402 * data. The forwarding code will check the validity of the
403 * response anyway, and substitute this data. The X11
404 * server, however, will ignore this fake data and use
405 * whatever authentication mechanisms it was using otherwise
406 * for the local connection.
412 logit("Warning: No xauth data; "
413 "using fake authentication data for X11 forwarding.");
414 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
415 arc4random_buf(rnd, sizeof(rnd));
416 for (i = 0; i < sizeof(rnd); i++) {
417 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
426 * Checks if the client window has changed, and sends a packet about it to
427 * the server if so. The actual change is detected elsewhere (by a software
428 * interrupt on Unix); this just checks the flag and sends a message if
433 client_check_window_change(struct ssh *ssh)
435 if (!received_window_change_signal)
437 received_window_change_signal = 0;
439 channel_send_window_changes(ssh);
443 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
445 struct global_confirm *gc;
447 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
450 gc->cb(ssh, type, seq, gc->ctx);
451 if (--gc->ref_count <= 0) {
452 TAILQ_REMOVE(&global_confirms, gc, entry);
453 freezero(gc, sizeof(*gc));
456 ssh_packet_set_alive_timeouts(ssh, 0);
461 schedule_server_alive_check(void)
463 if (options.server_alive_interval > 0)
464 server_alive_time = monotime() + options.server_alive_interval;
468 server_alive_check(struct ssh *ssh)
472 if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
473 logit("Timeout, server %s not responding.", host);
476 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
477 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
478 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* boolean: want reply */
479 (r = sshpkt_send(ssh)) != 0)
480 fatal_fr(r, "send packet");
481 /* Insert an empty placeholder to maintain ordering */
482 client_register_global_confirm(NULL, NULL);
483 schedule_server_alive_check();
487 * Waits until the client can do something (some data becomes available on
488 * one of the file descriptors).
491 client_wait_until_can_do_something(struct ssh *ssh,
492 fd_set **readsetp, fd_set **writesetp,
493 int *maxfdp, u_int *nallocp, int rekeying)
495 struct timeval tv, *tvp;
497 time_t minwait_secs = 0, now = monotime();
500 /* Add any selections by the channel mechanism. */
501 channel_prepare_select(ssh, readsetp, writesetp, maxfdp,
502 nallocp, &minwait_secs);
504 /* channel_prepare_select could have closed the last channel */
505 if (session_closed && !channel_still_open(ssh) &&
506 !ssh_packet_have_data_to_write(ssh)) {
507 /* clear mask since we did not call select() */
508 memset(*readsetp, 0, *nallocp);
509 memset(*writesetp, 0, *nallocp);
513 FD_SET(connection_in, *readsetp);
515 /* Select server connection if have data to write to the server. */
516 if (ssh_packet_have_data_to_write(ssh))
517 FD_SET(connection_out, *writesetp);
520 * Wait for something to happen. This will suspend the process until
521 * some selected descriptor can be read, written, or has some other
522 * event pending, or a timeout expires.
525 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
526 if (options.server_alive_interval > 0)
527 timeout_secs = MAXIMUM(server_alive_time - now, 0);
528 if (options.rekey_interval > 0 && !rekeying)
529 timeout_secs = MINIMUM(timeout_secs,
530 ssh_packet_get_rekey_timeout(ssh));
531 set_control_persist_exit_time(ssh);
532 if (control_persist_exit_time > 0) {
533 timeout_secs = MINIMUM(timeout_secs,
534 control_persist_exit_time - now);
535 if (timeout_secs < 0)
538 if (minwait_secs != 0)
539 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
540 if (timeout_secs == INT_MAX)
543 tv.tv_sec = timeout_secs;
548 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
551 * We have to clear the select masks, because we return.
552 * We have to return, because the mainloop checks for the flags
553 * set by the signal handlers.
555 memset(*readsetp, 0, *nallocp);
556 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_fr(r, "sshbuf_putf");
564 } else if (options.server_alive_interval > 0 && !FD_ISSET(connection_in,
565 *readsetp) && monotime() >= server_alive_time)
567 * ServerAlive check is needed. We can't rely on the select
568 * timing out since traffic on the client side such as port
569 * forwards can keep waking it up.
571 server_alive_check(ssh);
575 client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
577 /* Flush stdout and stderr buffers. */
578 if (sshbuf_len(bout) > 0)
579 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
581 if (sshbuf_len(berr) > 0)
582 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
585 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
591 /* Send the suspend signal to the program itself. */
592 kill(getpid(), SIGTSTP);
594 /* Reset window sizes in case they have changed */
595 received_window_change_signal = 1;
597 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
601 client_process_net_input(struct ssh *ssh, fd_set *readset)
603 char buf[SSH_IOBUFSZ];
607 * Read input from the server, and add any such data to the buffer of
608 * the packet subsystem.
610 if (FD_ISSET(connection_in, readset)) {
611 schedule_server_alive_check();
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_fr(r, "sshbuf_putf");
627 * There is a kernel bug on Solaris that causes select to
628 * sometimes wake up even though there is no data available.
631 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
636 * An error has encountered. Perhaps there is a
639 if ((r = sshbuf_putf(stderr_buffer,
640 "Read from remote host %.300s: %.100s\r\n",
641 host, strerror(errno))) != 0)
642 fatal_fr(r, "sshbuf_putf");
646 ssh_packet_process_incoming(ssh, buf, len);
651 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
653 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
658 * If a TTY was explicitly requested, then a failure to allocate
661 if (cr->action == CONFIRM_TTY &&
662 (options.request_tty == REQUEST_TTY_FORCE ||
663 options.request_tty == REQUEST_TTY_YES))
664 cr->action = CONFIRM_CLOSE;
666 /* XXX suppress on mux _client_ quietmode */
667 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
668 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
670 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
671 debug2("%s request accepted on channel %d",
672 cr->request_type, c->self);
673 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
675 snprintf(errmsg, sizeof(errmsg),
676 "%s request failed\r\n", cr->request_type);
678 snprintf(errmsg, sizeof(errmsg),
679 "%s request failed on channel %d",
680 cr->request_type, c->self);
682 /* If error occurred on primary session channel, then exit */
683 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
686 * If error occurred on mux client, append to
690 debug3_f("channel %d: mux request: %s", c->self,
692 if ((r = sshbuf_put(c->extended, errmsg,
693 strlen(errmsg))) != 0)
694 fatal_fr(r, "sshbuf_put");
697 if (cr->action == CONFIRM_TTY) {
699 * If a TTY allocation error occurred, then arrange
700 * for the correct TTY to leave raw mode.
702 if (c->self == session_ident)
705 mux_tty_alloc_failed(ssh, c);
706 } else if (cr->action == CONFIRM_CLOSE) {
707 chan_read_failed(ssh, c);
708 chan_write_failed(ssh, c);
715 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
721 client_expect_confirm(struct ssh *ssh, int id, const char *request,
722 enum confirm_action action)
724 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
726 cr->request_type = request;
729 channel_register_status_confirm(ssh, id, client_status_confirm,
730 client_abandon_status_confirm, cr);
734 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
736 struct global_confirm *gc, *last_gc;
738 /* Coalesce identical callbacks */
739 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
740 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
741 if (++last_gc->ref_count >= INT_MAX)
742 fatal_f("last_gc->ref_count = %d",
747 gc = xcalloc(1, sizeof(*gc));
751 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
755 process_cmdline(struct ssh *ssh)
757 void (*handler)(int);
759 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
762 memset(&fwd, 0, sizeof(fwd));
764 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
765 handler = ssh_signal(SIGINT, SIG_IGN);
766 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
769 while (isspace((u_char)*s))
772 s++; /* Skip cmdline '-', if any */
776 if (*s == 'h' || *s == 'H' || *s == '?') {
778 logit(" -L[bind_address:]port:host:hostport "
779 "Request local forward");
780 logit(" -R[bind_address:]port:host:hostport "
781 "Request remote forward");
782 logit(" -D[bind_address:]port "
783 "Request dynamic forward");
784 logit(" -KL[bind_address:]port "
785 "Cancel local forward");
786 logit(" -KR[bind_address:]port "
787 "Cancel remote forward");
788 logit(" -KD[bind_address:]port "
789 "Cancel dynamic forward");
790 if (!options.permit_local_command)
793 "Execute local command");
797 if (*s == '!' && options.permit_local_command) {
814 logit("Invalid command.");
818 while (isspace((u_char)*++s))
821 /* XXX update list of forwards in options */
823 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
824 if (!parse_forward(&fwd, s, 1, 0)) {
825 logit("Bad forwarding close specification.");
829 ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
831 ok = channel_cancel_lport_listener(ssh, &fwd,
832 0, &options.fwd_opts) > 0;
834 ok = channel_cancel_lport_listener(ssh, &fwd,
835 CHANNEL_CANCEL_PORT_STATIC,
836 &options.fwd_opts) > 0;
838 logit("Unknown port forwarding.");
841 logit("Canceled forwarding.");
843 if (!parse_forward(&fwd, s, dynamic, remote)) {
844 logit("Bad forwarding specification.");
847 if (local || dynamic) {
848 if (!channel_setup_local_fwd_listener(ssh, &fwd,
849 &options.fwd_opts)) {
850 logit("Port forwarding failed.");
854 if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
855 logit("Port forwarding failed.");
859 logit("Forwarding port.");
863 ssh_signal(SIGINT, handler);
864 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
866 free(fwd.listen_host);
867 free(fwd.listen_path);
868 free(fwd.connect_host);
869 free(fwd.connect_path);
872 /* reasons to suppress output of an escape command in help output */
873 #define SUPPRESS_NEVER 0 /* never suppress, always show */
874 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
875 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
876 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
877 struct escape_help_text {
882 static struct escape_help_text esc_txt[] = {
883 {".", "terminate session", SUPPRESS_MUXMASTER},
884 {".", "terminate connection (and any multiplexed sessions)",
886 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
887 {"C", "open a command line", SUPPRESS_MUXCLIENT},
888 {"R", "request rekey", SUPPRESS_NEVER},
889 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
890 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
891 {"#", "list forwarded connections", SUPPRESS_NEVER},
892 {"&", "background ssh (when waiting for connections to terminate)",
894 {"?", "this message", SUPPRESS_NEVER},
898 print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
901 unsigned int i, suppress_flags;
904 if ((r = sshbuf_putf(b,
905 "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
906 fatal_fr(r, "sshbuf_putf");
909 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
910 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
911 (using_stderr ? 0 : SUPPRESS_SYSLOG);
913 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
914 if (esc_txt[i].flags & suppress_flags)
916 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
917 escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
918 fatal_fr(r, "sshbuf_putf");
921 if ((r = sshbuf_putf(b,
922 " %c%c - send the escape character by typing it twice\r\n"
923 "(Note that escapes are only recognized immediately after "
924 "newline.)\r\n", escape_char, escape_char)) != 0)
925 fatal_fr(r, "sshbuf_putf");
929 * Process the characters one by one.
932 process_escapes(struct ssh *ssh, Channel *c,
933 struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
941 struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
942 NULL : (struct escape_filter_ctx *)c->filter_ctx;
944 if (c->filter_ctx == NULL)
950 for (i = 0; i < (u_int)len; i++) {
951 /* Get one character at a time. */
954 if (efc->escape_pending) {
955 /* We have previously seen an escape character. */
956 /* Clear the flag now. */
957 efc->escape_pending = 0;
959 /* Process the escaped character. */
962 /* Terminate the connection. */
963 if ((r = sshbuf_putf(berr, "%c.\r\n",
964 efc->escape_char)) != 0)
965 fatal_fr(r, "sshbuf_putf");
966 if (c && c->ctl_chan != -1) {
967 chan_read_failed(ssh, c);
968 chan_write_failed(ssh, c);
969 if (c->detach_user) {
973 c->type = SSH_CHANNEL_ABANDONED;
974 sshbuf_reset(c->input);
975 chan_ibuf_empty(ssh, c);
982 /* XXX support this for mux clients */
983 if (c && c->ctl_chan != -1) {
987 snprintf(b, sizeof b, "^Z");
989 snprintf(b, sizeof b, "%c", ch);
990 if ((r = sshbuf_putf(berr,
991 "%c%s escape not available to "
992 "multiplexed sessions\r\n",
993 efc->escape_char, b)) != 0)
994 fatal_fr(r, "sshbuf_putf");
997 /* Suspend the program. Inform the user */
998 if ((r = sshbuf_putf(berr,
999 "%c^Z [suspend ssh]\r\n",
1000 efc->escape_char)) != 0)
1001 fatal_fr(r, "sshbuf_putf");
1003 /* Restore terminal modes and suspend. */
1004 client_suspend_self(bin, bout, berr);
1006 /* We have been continued. */
1010 if ((r = sshbuf_putf(berr,
1011 "%cB\r\n", efc->escape_char)) != 0)
1012 fatal_fr(r, "sshbuf_putf");
1013 channel_request_start(ssh, c->self, "break", 0);
1014 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
1015 (r = sshpkt_send(ssh)) != 0)
1016 fatal_fr(r, "send packet");
1020 if (ssh->compat & SSH_BUG_NOREKEY)
1021 logit("Server does not "
1022 "support re-keying");
1030 if (c && c->ctl_chan != -1)
1032 if (!log_is_on_stderr()) {
1033 if ((r = sshbuf_putf(berr,
1034 "%c%c [Logging to syslog]\r\n",
1035 efc->escape_char, ch)) != 0)
1036 fatal_fr(r, "sshbuf_putf");
1039 if (ch == 'V' && options.log_level >
1041 log_change_level(--options.log_level);
1042 if (ch == 'v' && options.log_level <
1043 SYSLOG_LEVEL_DEBUG3)
1044 log_change_level(++options.log_level);
1045 if ((r = sshbuf_putf(berr,
1046 "%c%c [LogLevel %s]\r\n",
1047 efc->escape_char, ch,
1048 log_level_name(options.log_level))) != 0)
1049 fatal_fr(r, "sshbuf_putf");
1053 if (c && c->ctl_chan != -1)
1056 * Detach the program (continue to serve
1057 * connections, but put in background and no
1058 * more new connections).
1060 /* Restore tty modes. */
1062 options.request_tty == REQUEST_TTY_FORCE);
1064 /* Stop listening for new connections. */
1065 channel_stop_listening(ssh);
1067 if ((r = sshbuf_putf(berr, "%c& "
1068 "[backgrounded]\n", efc->escape_char)) != 0)
1069 fatal_fr(r, "sshbuf_putf");
1071 /* Fork into background. */
1074 error("fork: %.100s", strerror(errno));
1077 if (pid != 0) { /* This is the parent. */
1078 /* The parent just exits. */
1081 /* The child continues serving connections. */
1082 /* fake EOF on stdin */
1083 if ((r = sshbuf_put_u8(bin, 4)) != 0)
1084 fatal_fr(r, "sshbuf_put_u8");
1087 print_escape_help(berr, efc->escape_char,
1088 (c && c->ctl_chan != -1),
1089 log_is_on_stderr());
1093 if ((r = sshbuf_putf(berr, "%c#\r\n",
1094 efc->escape_char)) != 0)
1095 fatal_fr(r, "sshbuf_putf");
1096 s = channel_open_message(ssh);
1097 if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
1098 fatal_fr(r, "sshbuf_put");
1103 if (c && c->ctl_chan != -1)
1105 process_cmdline(ssh);
1109 if (ch != efc->escape_char) {
1110 if ((r = sshbuf_put_u8(bin,
1111 efc->escape_char)) != 0)
1112 fatal_fr(r, "sshbuf_put_u8");
1115 /* Escaped characters fall through here */
1120 * The previous character was not an escape char.
1121 * Check if this is an escape.
1123 if (last_was_cr && ch == efc->escape_char) {
1125 * It is. Set the flag and continue to
1128 efc->escape_pending = 1;
1134 * Normal character. Record whether it was a newline,
1135 * and append it to the buffer.
1137 last_was_cr = (ch == '\r' || ch == '\n');
1138 if ((r = sshbuf_put_u8(bin, ch)) != 0)
1139 fatal_fr(r, "sshbuf_put_u8");
1146 * Get packets from the connection input buffer, and process them as long as
1147 * there are packets available.
1149 * Any unknown packets received during the actual
1150 * session cause the session to terminate. This is
1151 * intended to make debugging easier since no
1152 * confirmations are sent. Any compatible protocol
1153 * extensions must be negotiated during the
1154 * preparatory phase.
1158 client_process_buffered_input_packets(struct ssh *ssh)
1160 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
1163 /* scan buf[] for '~' before sending data to the peer */
1165 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1167 client_new_escape_filter_ctx(int escape_char)
1169 struct escape_filter_ctx *ret;
1171 ret = xcalloc(1, sizeof(*ret));
1172 ret->escape_pending = 0;
1173 ret->escape_char = escape_char;
1177 /* Free the escape filter context on channel free */
1179 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
1185 client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
1187 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1190 return process_escapes(ssh, c, c->input, c->output, c->extended,
1195 client_channel_closed(struct ssh *ssh, int id, void *arg)
1197 channel_cancel_cleanup(ssh, id);
1199 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1203 * Implements the interactive session with the server. This is called after
1204 * the user has been authenticated, and a command has been started on the
1205 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1206 * used as an escape character for terminating or suspending the session.
1209 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
1212 fd_set *readset = NULL, *writeset = NULL;
1213 double start_time, total_time;
1214 int r, max_fd = 0, max_fd2 = 0, len;
1215 u_int64_t ibytes, obytes;
1218 debug("Entering interactive session.");
1220 if (options.control_master &&
1221 !option_clear_or_none(options.control_path)) {
1222 debug("pledge: id");
1223 if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
1225 fatal_f("pledge(): %s", strerror(errno));
1227 } else if (options.forward_x11 || options.permit_local_command) {
1228 debug("pledge: exec");
1229 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
1231 fatal_f("pledge(): %s", strerror(errno));
1233 } else if (options.update_hostkeys) {
1234 debug("pledge: filesystem full");
1235 if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
1237 fatal_f("pledge(): %s", strerror(errno));
1239 } else if (!option_clear_or_none(options.proxy_command) ||
1240 options.fork_after_authentication) {
1241 debug("pledge: proc");
1242 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
1243 fatal_f("pledge(): %s", strerror(errno));
1246 debug("pledge: network");
1247 if (pledge("stdio unix inet dns proc tty", NULL) == -1)
1248 fatal_f("pledge(): %s", strerror(errno));
1251 start_time = monotime_double();
1253 /* Initialize variables. */
1256 connection_in = ssh_packet_get_connection_in(ssh);
1257 connection_out = ssh_packet_get_connection_out(ssh);
1258 max_fd = MAXIMUM(connection_in, connection_out);
1262 /* Initialize buffer. */
1263 if ((stderr_buffer = sshbuf_new()) == NULL)
1264 fatal_f("sshbuf_new failed");
1266 client_init_dispatch(ssh);
1269 * Set signal handlers, (e.g. to restore non-blocking mode)
1270 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1272 if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1273 ssh_signal(SIGHUP, signal_handler);
1274 if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
1275 ssh_signal(SIGINT, signal_handler);
1276 if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1277 ssh_signal(SIGQUIT, signal_handler);
1278 if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
1279 ssh_signal(SIGTERM, signal_handler);
1280 ssh_signal(SIGWINCH, window_change_handler);
1283 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1285 session_ident = ssh2_chan_id;
1286 if (session_ident != -1) {
1287 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1288 channel_register_filter(ssh, session_ident,
1289 client_simple_escape_filter, NULL,
1290 client_filter_cleanup,
1291 client_new_escape_filter_ctx(
1294 channel_register_cleanup(ssh, session_ident,
1295 client_channel_closed, 0);
1298 schedule_server_alive_check();
1300 /* Main loop of the client for the interactive session mode. */
1301 while (!quit_pending) {
1303 /* Process buffered packets sent by the server. */
1304 client_process_buffered_input_packets(ssh);
1306 if (session_closed && !channel_still_open(ssh))
1309 if (ssh_packet_is_rekeying(ssh)) {
1310 debug("rekeying in progress");
1311 } else if (need_rekeying) {
1312 /* manual rekey request */
1313 debug("need rekeying");
1314 if ((r = kex_start_rekex(ssh)) != 0)
1315 fatal_fr(r, "kex_start_rekex");
1319 * Make packets from buffered channel data, and
1320 * enqueue them for sending to the server.
1322 if (ssh_packet_not_very_much_data_to_write(ssh))
1323 channel_output_poll(ssh);
1326 * Check if the window size has changed, and buffer a
1327 * message about it to the server if so.
1329 client_check_window_change(ssh);
1335 * Wait until we have something to do (something becomes
1336 * available on one of the descriptors).
1339 client_wait_until_can_do_something(ssh, &readset, &writeset,
1340 &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
1345 /* Do channel operations unless rekeying in progress. */
1346 if (!ssh_packet_is_rekeying(ssh))
1347 channel_after_select(ssh, readset, writeset);
1349 /* Buffer input from the connection. */
1350 client_process_net_input(ssh, readset);
1355 /* A timeout may have triggered rekeying */
1356 if ((r = ssh_packet_check_rekey(ssh)) != 0)
1357 fatal_fr(r, "cannot start rekeying");
1360 * Send as much buffered packet data as possible to the
1363 if (FD_ISSET(connection_out, writeset)) {
1364 if ((r = ssh_packet_write_poll(ssh)) != 0) {
1365 sshpkt_fatal(ssh, r,
1366 "%s: ssh_packet_write_poll", __func__);
1371 * If we are a backgrounded control master, and the
1372 * timeout has expired without any active client
1373 * connections, then quit.
1375 if (control_persist_exit_time > 0) {
1376 if (monotime() >= control_persist_exit_time) {
1377 debug("ControlPersist timeout expired");
1385 /* Terminate the session. */
1387 /* Stop watching for window change. */
1388 ssh_signal(SIGWINCH, SIG_DFL);
1390 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
1391 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
1392 (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
1393 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language tag */
1394 (r = sshpkt_send(ssh)) != 0 ||
1395 (r = ssh_packet_write_wait(ssh)) != 0)
1396 fatal_fr(r, "send disconnect");
1398 channel_free_all(ssh);
1401 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1404 * If there was no shell or command requested, there will be no remote
1405 * exit status to be returned. In that case, clear error code if the
1406 * connection was deliberately terminated at this end.
1408 if (options.session_type == SESSION_TYPE_NONE &&
1409 received_signal == SIGTERM) {
1410 received_signal = 0;
1414 if (received_signal) {
1415 verbose("Killed by signal %d.", (int) received_signal);
1420 * In interactive mode (with pseudo tty) display a message indicating
1421 * that the connection has been closed.
1423 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1424 if ((r = sshbuf_putf(stderr_buffer,
1425 "Connection to %.64s closed.\r\n", host)) != 0)
1426 fatal_fr(r, "sshbuf_putf");
1429 /* Output any buffered data for stderr. */
1430 if (sshbuf_len(stderr_buffer) > 0) {
1431 len = atomicio(vwrite, fileno(stderr),
1432 (u_char *)sshbuf_ptr(stderr_buffer),
1433 sshbuf_len(stderr_buffer));
1434 if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
1435 error("Write failed flushing stderr buffer.");
1436 else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
1437 fatal_fr(r, "sshbuf_consume");
1440 /* Clear and free any buffers. */
1441 sshbuf_free(stderr_buffer);
1443 /* Report bytes transferred, and transfer rates. */
1444 total_time = monotime_double() - start_time;
1445 ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1446 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1447 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1449 verbose("Bytes per second: sent %.1f, received %.1f",
1450 obytes / total_time, ibytes / total_time);
1451 /* Return the exit status of the program. */
1452 debug("Exit status %d", exit_status);
1459 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
1460 int rchan, u_int rwindow, u_int rmaxpack)
1463 struct sshbuf *b = NULL;
1464 char *listen_address, *originator_address;
1465 u_int listen_port, originator_port;
1468 /* Get rest of the packet */
1469 if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
1470 (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
1471 (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
1472 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1473 (r = sshpkt_get_end(ssh)) != 0)
1474 fatal_fr(r, "parse packet");
1476 debug_f("listen %s port %d, originator %s port %d",
1477 listen_address, listen_port, originator_address, originator_port);
1479 if (listen_port > 0xffff)
1480 error_f("invalid listen port");
1481 else if (originator_port > 0xffff)
1482 error_f("invalid originator port");
1484 c = channel_connect_by_listen_address(ssh,
1485 listen_address, listen_port, "forwarded-tcpip",
1486 originator_address);
1489 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1490 if ((b = sshbuf_new()) == NULL) {
1491 error_f("alloc reply");
1494 /* reconstruct and send to muxclient */
1495 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
1496 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1497 (r = sshbuf_put_cstring(b, request_type)) != 0 ||
1498 (r = sshbuf_put_u32(b, rchan)) != 0 ||
1499 (r = sshbuf_put_u32(b, rwindow)) != 0 ||
1500 (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
1501 (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
1502 (r = sshbuf_put_u32(b, listen_port)) != 0 ||
1503 (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
1504 (r = sshbuf_put_u32(b, originator_port)) != 0 ||
1505 (r = sshbuf_put_stringb(c->output, b)) != 0) {
1506 error_fr(r, "compose for muxclient");
1513 free(originator_address);
1514 free(listen_address);
1519 client_request_forwarded_streamlocal(struct ssh *ssh,
1520 const char *request_type, int rchan)
1526 /* Get the remote path. */
1527 if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
1528 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* reserved */
1529 (r = sshpkt_get_end(ssh)) != 0)
1530 fatal_fr(r, "parse packet");
1532 debug_f("request: %s", listen_path);
1534 c = channel_connect_by_listen_path(ssh, listen_path,
1535 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1541 client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
1545 u_int originator_port;
1548 if (!options.forward_x11) {
1549 error("Warning: ssh server tried X11 forwarding.");
1550 error("Warning: this is probably a break-in attempt by a "
1551 "malicious server.");
1554 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1555 verbose("Rejected X11 connection after ForwardX11Timeout "
1559 if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
1560 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
1561 (r = sshpkt_get_end(ssh)) != 0)
1562 fatal_fr(r, "parse packet");
1563 /* XXX check permission */
1564 /* XXX range check originator port? */
1565 debug("client_request_x11: request from %s %u", originator,
1568 sock = x11_connect_display(ssh);
1571 c = channel_new(ssh, "x11",
1572 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1573 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1579 client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
1584 if (!options.forward_agent) {
1585 error("Warning: ssh server tried agent forwarding.");
1586 error("Warning: this is probably a break-in attempt by a "
1587 "malicious server.");
1590 if (forward_agent_sock_path == NULL) {
1591 r = ssh_get_authentication_socket(&sock);
1593 r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
1596 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1597 debug_fr(r, "ssh_get_authentication_socket");
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, channel_open_fn *cb, void *cbctx)
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);
1639 channel_register_open_confirm(ssh, c->self, cb, cbctx);
1641 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1642 (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
1643 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1644 (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
1645 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1646 (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
1647 (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
1648 (r = sshpkt_send(ssh)) != 0)
1649 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1654 /* XXXX move to generic input handler */
1656 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
1663 u_int rmaxpack, rwindow;
1665 if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
1666 (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
1667 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
1668 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
1671 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1672 ctype, rchan, rwindow, rmaxpack);
1674 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1675 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
1677 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
1678 c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
1679 } else if (strcmp(ctype, "x11") == 0) {
1680 c = client_request_x11(ssh, ctype, rchan);
1681 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1682 c = client_request_agent(ssh, ctype, rchan);
1684 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
1685 debug3("proxied to downstream: %s", ctype);
1686 } else if (c != NULL) {
1687 debug("confirm %s", ctype);
1688 c->remote_id = rchan;
1689 c->have_remote_id = 1;
1690 c->remote_window = rwindow;
1691 c->remote_maxpacket = rmaxpack;
1692 if (c->type != SSH_CHANNEL_CONNECTING) {
1693 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1694 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1695 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1696 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1697 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1698 (r = sshpkt_send(ssh)) != 0)
1699 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
1702 debug("failure %s", ctype);
1703 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1704 (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
1705 (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
1706 (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
1707 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1708 (r = sshpkt_send(ssh)) != 0)
1709 sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1718 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
1726 if ((r = sshpkt_get_u32(ssh, &id)) != 0)
1729 c = channel_lookup(ssh, id);
1730 if (channel_proxy_upstream(c, type, seq, ssh))
1732 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
1733 (r = sshpkt_get_u8(ssh, &reply)) != 0)
1736 debug("client_input_channel_req: channel %u rtype %s reply %d",
1740 error("client_input_channel_req: channel %d: "
1741 "unknown channel", id);
1742 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1743 if ((r = sshpkt_get_end(ssh)) != 0)
1745 chan_rcvd_eow(ssh, c);
1746 } else if (strcmp(rtype, "exit-status") == 0) {
1747 if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
1749 if (c->ctl_chan != -1) {
1750 mux_exit_message(ssh, c, exitval);
1752 } else if ((int)id == session_ident) {
1753 /* Record exit value of local session */
1755 exit_status = exitval;
1757 /* Probably for a mux channel that has already closed */
1758 debug_f("no sink for exit-status on channel %d",
1761 if ((r = sshpkt_get_end(ssh)) != 0)
1764 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1765 if (!c->have_remote_id)
1766 fatal_f("channel %d: no remote_id", c->self);
1767 if ((r = sshpkt_start(ssh, success ?
1768 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
1769 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1770 (r = sshpkt_send(ssh)) != 0)
1771 sshpkt_fatal(ssh, r, "%s: send failure", __func__);
1779 struct hostkeys_update_ctx {
1780 /* The hostname and (optionally) IP address string for the server */
1781 char *host_str, *ip_str;
1784 * Keys received from the server and a flag for each indicating
1785 * whether they already exist in known_hosts.
1786 * keys_match is filled in by hostkeys_find() and later (for new
1787 * keys) by client_global_hostkeys_private_confirm().
1789 struct sshkey **keys;
1790 u_int *keys_match; /* mask of HKF_MATCH_* from hostfile.h */
1791 int *keys_verified; /* flag for new keys verified by server */
1792 size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */
1795 * Keys that are in known_hosts, but were not present in the update
1796 * from the server (i.e. scheduled to be deleted).
1797 * Filled in by hostkeys_find().
1799 struct sshkey **old_keys;
1802 /* Various special cases. */
1803 int complex_hostspec; /* wildcard or manual pattern-list host name */
1804 int ca_available; /* saw CA key for this host */
1805 int old_key_seen; /* saw old key with other name/addr */
1806 int other_name_seen; /* saw key with other name/addr */
1810 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
1816 for (i = 0; i < ctx->nkeys; i++)
1817 sshkey_free(ctx->keys[i]);
1819 free(ctx->keys_match);
1820 free(ctx->keys_verified);
1821 for (i = 0; i < ctx->nold; i++)
1822 sshkey_free(ctx->old_keys[i]);
1823 free(ctx->old_keys);
1824 free(ctx->host_str);
1830 * Returns non-zero if a known_hosts hostname list is not of a form that
1831 * can be handled by UpdateHostkeys. These include wildcard hostnames and
1832 * hostnames lists that do not follow the form host[,ip].
1835 hostspec_is_complex(const char *hosts)
1840 if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL)
1842 /* single host/ip = ok */
1843 if ((cp = strchr(hosts, ',')) == NULL)
1845 /* more than two entries on the line */
1846 if (strchr(cp + 1, ',') != NULL)
1848 /* XXX maybe parse cp+1 and ensure it is an IP? */
1852 /* callback to search for ctx->keys in known_hosts */
1854 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
1856 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1858 struct sshkey **tmp;
1862 if (l->status != HKF_STATUS_MATCHED) {
1863 /* Record if one of the keys appears on a non-matching line */
1864 for (i = 0; i < ctx->nkeys; i++) {
1865 if (sshkey_equal(l->key, ctx->keys[i])) {
1866 ctx->other_name_seen = 1;
1867 debug3_f("found %s key under different "
1868 "name/addr at %s:%ld",
1869 sshkey_ssh_name(ctx->keys[i]),
1870 l->path, l->linenum);
1876 /* Don't proceed if revocation or CA markers are present */
1877 /* XXX relax this */
1878 if (l->marker != MRK_NONE) {
1879 debug3_f("hostkeys file %s:%ld has CA/revocation marker",
1880 l->path, l->linenum);
1881 ctx->complex_hostspec = 1;
1885 /* If CheckHostIP is enabled, then check for mismatched hostname/addr */
1886 if (ctx->ip_str != NULL && strchr(l->hosts, ',') != NULL) {
1887 if ((l->match & HKF_MATCH_HOST) == 0) {
1888 /* Record if address matched a different hostname. */
1889 ctx->other_name_seen = 1;
1890 debug3_f("found address %s against different hostname "
1891 "at %s:%ld", ctx->ip_str, l->path, l->linenum);
1893 } else if ((l->match & HKF_MATCH_IP) == 0) {
1894 /* Record if hostname matched a different address. */
1895 ctx->other_name_seen = 1;
1896 debug3_f("found hostname %s against different address "
1897 "at %s:%ld", ctx->host_str, l->path, l->linenum);
1902 * UpdateHostkeys is skipped for wildcard host names and hostnames
1903 * that contain more than two entries (ssh never writes these).
1905 if (hostspec_is_complex(l->hosts)) {
1906 debug3_f("hostkeys file %s:%ld complex host specification",
1907 l->path, l->linenum);
1908 ctx->complex_hostspec = 1;
1912 /* Mark off keys we've already seen for this host */
1913 for (i = 0; i < ctx->nkeys; i++) {
1914 if (!sshkey_equal(l->key, ctx->keys[i]))
1916 debug3_f("found %s key at %s:%ld",
1917 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
1918 ctx->keys_match[i] |= l->match;
1921 /* This line contained a key that not offered by the server */
1922 debug3_f("deprecated %s key at %s:%ld", sshkey_ssh_name(l->key),
1923 l->path, l->linenum);
1924 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
1925 sizeof(*ctx->old_keys))) == NULL)
1926 fatal_f("recallocarray failed nold = %zu", ctx->nold);
1927 ctx->old_keys = tmp;
1928 ctx->old_keys[ctx->nold++] = l->key;
1934 /* callback to search for ctx->old_keys in known_hosts under other names */
1936 hostkeys_check_old(struct hostkey_foreach_line *l, void *_ctx)
1938 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
1942 /* only care about lines that *don't* match the active host spec */
1943 if (l->status == HKF_STATUS_MATCHED || l->key == NULL)
1946 hashed = l->match & (HKF_MATCH_HOST_HASHED|HKF_MATCH_IP_HASHED);
1947 for (i = 0; i < ctx->nold; i++) {
1948 if (!sshkey_equal(l->key, ctx->old_keys[i]))
1950 debug3_f("found deprecated %s key at %s:%ld as %s",
1951 sshkey_ssh_name(ctx->old_keys[i]), l->path, l->linenum,
1952 hashed ? "[HASHED]" : l->hosts);
1953 ctx->old_key_seen = 1;
1960 * Check known_hosts files for deprecated keys under other names. Returns 0
1961 * on success or -1 on failure. Updates ctx->old_key_seen if deprecated keys
1962 * exist under names other than the active hostname/IP.
1965 check_old_keys_othernames(struct hostkeys_update_ctx *ctx)
1970 debug2_f("checking for %zu deprecated keys", ctx->nold);
1971 for (i = 0; i < options.num_user_hostfiles; i++) {
1972 debug3_f("searching %s for %s / %s",
1973 options.user_hostfiles[i], ctx->host_str,
1974 ctx->ip_str ? ctx->ip_str : "(none)");
1975 if ((r = hostkeys_foreach(options.user_hostfiles[i],
1976 hostkeys_check_old, ctx, ctx->host_str, ctx->ip_str,
1977 HKF_WANT_PARSE_KEY, 0)) != 0) {
1978 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
1979 debug_f("hostkeys file %s does not exist",
1980 options.user_hostfiles[i]);
1983 error_fr(r, "hostkeys_foreach failed for %s",
1984 options.user_hostfiles[i]);
1992 hostkey_change_preamble(LogLevel loglevel)
1994 do_log2(loglevel, "The server has updated its host keys.");
1995 do_log2(loglevel, "These changes were verified by the server's "
1996 "existing trusted key.");
2000 update_known_hosts(struct hostkeys_update_ctx *ctx)
2002 int r, was_raw = 0, first = 1;
2003 int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
2004 LogLevel loglevel = asking ? SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2005 char *fp, *response;
2009 for (i = 0; i < ctx->nkeys; i++) {
2010 if (!ctx->keys_verified[i])
2012 if ((fp = sshkey_fingerprint(ctx->keys[i],
2013 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2014 fatal_f("sshkey_fingerprint failed");
2015 if (first && asking)
2016 hostkey_change_preamble(loglevel);
2017 do_log2(loglevel, "Learned new hostkey: %s %s",
2018 sshkey_type(ctx->keys[i]), fp);
2022 for (i = 0; i < ctx->nold; i++) {
2023 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2024 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2025 fatal_f("sshkey_fingerprint failed");
2026 if (first && asking)
2027 hostkey_change_preamble(loglevel);
2028 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2029 sshkey_type(ctx->old_keys[i]), fp);
2033 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
2034 if (get_saved_tio() != NULL) {
2039 for (i = 0; !quit_pending && i < 3; i++) {
2041 response = read_passphrase("Accept updated hostkeys? "
2042 "(yes/no): ", RP_ECHO);
2043 if (strcasecmp(response, "yes") == 0)
2045 else if (quit_pending || response == NULL ||
2046 strcasecmp(response, "no") == 0) {
2047 options.update_hostkeys = 0;
2050 do_log2(loglevel, "Please enter "
2051 "\"yes\" or \"no\"");
2054 if (quit_pending || i >= 3 || response == NULL)
2055 options.update_hostkeys = 0;
2060 if (options.update_hostkeys == 0)
2063 * Now that all the keys are verified, we can go ahead and replace
2064 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2065 * cancel the operation).
2067 for (i = 0; i < options.num_user_hostfiles; i++) {
2069 * NB. keys are only added to hostfiles[0], for the rest we
2070 * just delete the hostname entries.
2072 if (stat(options.user_hostfiles[i], &sb) != 0) {
2073 if (errno == ENOENT) {
2074 debug_f("known hosts file %s does not "
2075 "exist", options.user_hostfiles[i]);
2077 error_f("known hosts file %s "
2079 options.user_hostfiles[i], strerror(errno));
2083 if ((r = hostfile_replace_entries(options.user_hostfiles[i],
2084 ctx->host_str, ctx->ip_str,
2085 i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
2086 options.hash_known_hosts, 0,
2087 options.fingerprint_hash)) != 0) {
2088 error_fr(r, "hostfile_replace_entries failed for %s",
2089 options.user_hostfiles[i]);
2095 client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
2096 u_int32_t seq, void *_ctx)
2098 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2100 struct sshbuf *signdata;
2101 int r, kexsigtype, use_kexsigtype;
2106 fatal_f("ctx->nnew == 0"); /* sanity */
2107 if (type != SSH2_MSG_REQUEST_SUCCESS) {
2108 error("Server failed to confirm ownership of "
2109 "private host keys");
2110 hostkeys_update_ctx_free(ctx);
2113 kexsigtype = sshkey_type_plain(
2114 sshkey_type_from_name(ssh->kex->hostkey_alg));
2116 if ((signdata = sshbuf_new()) == NULL)
2117 fatal_f("sshbuf_new failed");
2119 * Expect a signature for each of the ctx->nnew private keys we
2120 * haven't seen before. They will be in the same order as the
2121 * ctx->keys where the corresponding ctx->keys_match[i] == 0.
2123 for (ndone = i = 0; i < ctx->nkeys; i++) {
2124 if (ctx->keys_match[i])
2126 /* Prepare data to be signed: session ID, unique string, key */
2127 sshbuf_reset(signdata);
2128 if ( (r = sshbuf_put_cstring(signdata,
2129 "hostkeys-prove-00@openssh.com")) != 0 ||
2130 (r = sshbuf_put_stringb(signdata,
2131 ssh->kex->session_id)) != 0 ||
2132 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
2133 fatal_fr(r, "compose signdata");
2134 /* Extract and verify signature */
2135 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
2136 error_fr(r, "parse sig");
2140 * For RSA keys, prefer to use the signature type negotiated
2141 * during KEX to the default (SHA1).
2143 use_kexsigtype = kexsigtype == KEY_RSA &&
2144 sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA;
2145 debug3_f("verify %s key %zu using %s sigalg",
2146 sshkey_type(ctx->keys[i]), i,
2147 use_kexsigtype ? ssh->kex->hostkey_alg : "default");
2148 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2149 sshbuf_ptr(signdata), sshbuf_len(signdata),
2150 use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0,
2152 error_fr(r, "server gave bad signature for %s key %zu",
2153 sshkey_type(ctx->keys[i]), i);
2156 /* Key is good. Mark it as 'seen' */
2157 ctx->keys_verified[i] = 1;
2160 /* Shouldn't happen */
2161 if (ndone != ctx->nnew)
2162 fatal_f("ndone != ctx->nnew (%zu / %zu)", ndone, ctx->nnew);
2163 if ((r = sshpkt_get_end(ssh)) != 0) {
2164 error_f("protocol error");
2168 /* Make the edits to known_hosts */
2169 update_known_hosts(ctx);
2171 hostkeys_update_ctx_free(ctx);
2175 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
2176 * Made slightly less trivial by the multiple RSA signature algorithm names.
2179 key_accepted_by_hostkeyalgs(const struct sshkey *key)
2181 const char *ktype = sshkey_ssh_name(key);
2182 const char *hostkeyalgs = options.hostkeyalgorithms;
2184 if (key == NULL || key->type == KEY_UNSPEC)
2186 if (key->type == KEY_RSA &&
2187 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
2188 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
2190 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
2194 * Handle hostkeys-00@openssh.com global request to inform the client of all
2195 * the server's hostkeys. The keys are checked against the user's
2196 * HostkeyAlgorithms preference before they are accepted.
2199 client_input_hostkeys(struct ssh *ssh)
2201 const u_char *blob = NULL;
2203 struct sshbuf *buf = NULL;
2204 struct sshkey *key = NULL, **tmp;
2207 static int hostkeys_seen = 0; /* XXX use struct ssh */
2208 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2209 struct hostkeys_update_ctx *ctx = NULL;
2213 fatal_f("server already sent hostkeys");
2214 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2216 return 1; /* won't ask in batchmode, so don't even try */
2217 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2220 ctx = xcalloc(1, sizeof(*ctx));
2221 while (ssh_packet_remaining(ssh) > 0) {
2224 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2225 error_fr(r, "parse key");
2228 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2229 do_log2_fr(r, r == SSH_ERR_KEY_TYPE_UNKNOWN ?
2230 SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
2234 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2236 debug3_f("received %s key %s", sshkey_type(key), fp);
2239 if (!key_accepted_by_hostkeyalgs(key)) {
2240 debug3_f("%s key not permitted by "
2241 "HostkeyAlgorithms", sshkey_ssh_name(key));
2245 if (sshkey_is_cert(key)) {
2246 debug3_f("%s key is a certificate; skipping",
2247 sshkey_ssh_name(key));
2250 /* Ensure keys are unique */
2251 for (i = 0; i < ctx->nkeys; i++) {
2252 if (sshkey_equal(key, ctx->keys[i])) {
2253 error_f("received duplicated %s host key",
2254 sshkey_ssh_name(key));
2258 /* Key is good, record it */
2259 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
2260 sizeof(*ctx->keys))) == NULL)
2261 fatal_f("recallocarray failed nkeys = %zu",
2264 ctx->keys[ctx->nkeys++] = key;
2268 if (ctx->nkeys == 0) {
2269 debug_f("server sent no hostkeys");
2273 if ((ctx->keys_match = calloc(ctx->nkeys,
2274 sizeof(*ctx->keys_match))) == NULL ||
2275 (ctx->keys_verified = calloc(ctx->nkeys,
2276 sizeof(*ctx->keys_verified))) == NULL)
2277 fatal_f("calloc failed");
2279 get_hostfile_hostname_ipaddr(host,
2280 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2281 options.port, &ctx->host_str,
2282 options.check_host_ip ? &ctx->ip_str : NULL);
2284 /* Find which keys we already know about. */
2285 for (i = 0; i < options.num_user_hostfiles; i++) {
2286 debug_f("searching %s for %s / %s",
2287 options.user_hostfiles[i], ctx->host_str,
2288 ctx->ip_str ? ctx->ip_str : "(none)");
2289 if ((r = hostkeys_foreach(options.user_hostfiles[i],
2290 hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
2291 HKF_WANT_PARSE_KEY, 0)) != 0) {
2292 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
2293 debug_f("hostkeys file %s does not exist",
2294 options.user_hostfiles[i]);
2297 error_fr(r, "hostkeys_foreach failed for %s",
2298 options.user_hostfiles[i]);
2303 /* Figure out if we have any new keys to add */
2304 ctx->nnew = ctx->nincomplete = 0;
2305 want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0);
2306 for (i = 0; i < ctx->nkeys; i++) {
2307 if (ctx->keys_match[i] == 0)
2309 if ((ctx->keys_match[i] & want) != want)
2313 debug3_f("%zu server keys: %zu new, %zu retained, "
2314 "%zu incomplete match. %zu to remove", ctx->nkeys, ctx->nnew,
2315 ctx->nkeys - ctx->nnew - ctx->nincomplete,
2316 ctx->nincomplete, ctx->nold);
2318 if (ctx->nnew == 0 && ctx->nold == 0) {
2319 debug_f("no new or deprecated keys from server");
2323 /* Various reasons why we cannot proceed with the update */
2324 if (ctx->complex_hostspec) {
2325 debug_f("CA/revocation marker, manual host list or wildcard "
2326 "host pattern found, skipping UserKnownHostsFile update");
2329 if (ctx->other_name_seen) {
2330 debug_f("host key found matching a different name/address, "
2331 "skipping UserKnownHostsFile update");
2335 * If removing keys, check whether they appear under different
2336 * names/addresses and refuse to proceed if they do. This avoids
2337 * cases such as hosts with multiple names becoming inconsistent
2338 * with regards to CheckHostIP entries.
2339 * XXX UpdateHostkeys=force to override this (and other) checks?
2341 if (ctx->nold != 0) {
2342 if (check_old_keys_othernames(ctx) != 0)
2343 goto out; /* error already logged */
2344 if (ctx->old_key_seen) {
2345 debug_f("key(s) for %s%s%s exist under other names; "
2346 "skipping UserKnownHostsFile update",
2347 ctx->host_str, ctx->ip_str == NULL ? "" : ",",
2348 ctx->ip_str == NULL ? "" : ctx->ip_str);
2353 if (ctx->nnew == 0) {
2355 * We have some keys to remove or fix matching for.
2356 * We can proceed to do this without requiring a fresh proof
2359 update_known_hosts(ctx);
2363 * We have received previously-unseen keys from the server.
2364 * Ask the server to confirm ownership of the private halves.
2366 debug3_f("asking server to prove ownership for %zu keys", ctx->nnew);
2367 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2368 (r = sshpkt_put_cstring(ssh,
2369 "hostkeys-prove-00@openssh.com")) != 0 ||
2370 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2371 fatal_fr(r, "prepare hostkeys-prove");
2372 if ((buf = sshbuf_new()) == NULL)
2373 fatal_f("sshbuf_new");
2374 for (i = 0; i < ctx->nkeys; i++) {
2375 if (ctx->keys_match[i])
2378 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0 ||
2379 (r = sshpkt_put_stringb(ssh, buf)) != 0)
2380 fatal_fr(r, "assemble hostkeys-prove");
2382 if ((r = sshpkt_send(ssh)) != 0)
2383 fatal_fr(r, "send hostkeys-prove");
2384 client_register_global_confirm(
2385 client_global_hostkeys_private_confirm, ctx);
2386 ctx = NULL; /* will be freed in callback */
2390 hostkeys_update_ctx_free(ctx);
2394 * NB. Return success for all cases. The server doesn't need to know
2395 * what the client does with its hosts file.
2401 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
2407 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
2408 (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
2410 debug("client_input_global_request: rtype %s want_reply %d",
2412 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2413 success = client_input_hostkeys(ssh);
2415 if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
2416 SSH2_MSG_REQUEST_FAILURE)) != 0 ||
2417 (r = sshpkt_send(ssh)) != 0 ||
2418 (r = ssh_packet_write_wait(ssh)) != 0)
2428 client_send_env(struct ssh *ssh, int id, const char *name, const char *val)
2432 debug("channel %d: setting env %s = \"%s\"", id, name, val);
2433 channel_request_start(ssh, id, "env", 0);
2434 if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
2435 (r = sshpkt_put_cstring(ssh, val)) != 0 ||
2436 (r = sshpkt_send(ssh)) != 0)
2437 fatal_fr(r, "send setenv");
2441 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
2442 const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
2445 int i, j, matched, len, r;
2449 debug2_f("id %d", id);
2451 if ((c = channel_lookup(ssh, id)) == NULL)
2452 fatal_f("channel %d: unknown channel", id);
2454 ssh_packet_set_interactive(ssh, want_tty,
2455 options.ip_qos_interactive, options.ip_qos_bulk);
2460 /* Store window size in the packet. */
2461 if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
2462 memset(&ws, 0, sizeof(ws));
2464 channel_request_start(ssh, id, "pty-req", 1);
2465 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
2466 if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
2468 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
2469 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
2470 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
2471 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
2472 fatal_fr(r, "build pty-req");
2474 tiop = get_saved_tio();
2475 ssh_tty_make_modes(ssh, -1, tiop);
2476 if ((r = sshpkt_send(ssh)) != 0)
2477 fatal_fr(r, "send pty-req");
2478 /* XXX wait for reply */
2482 /* Transfer any environment variables from client to server */
2483 if (options.num_send_env != 0 && env != NULL) {
2484 debug("Sending environment.");
2485 for (i = 0; env[i] != NULL; i++) {
2487 name = xstrdup(env[i]);
2488 if ((val = strchr(name, '=')) == NULL) {
2495 for (j = 0; j < options.num_send_env; j++) {
2496 if (match_pattern(name, options.send_env[j])) {
2502 debug3("Ignored env %s", name);
2506 client_send_env(ssh, id, name, val);
2510 for (i = 0; i < options.num_setenv; i++) {
2512 name = xstrdup(options.setenv[i]);
2513 if ((val = strchr(name, '=')) == NULL) {
2518 client_send_env(ssh, id, name, val);
2522 len = sshbuf_len(cmd);
2526 if (want_subsystem) {
2527 debug("Sending subsystem: %.*s",
2528 len, (const u_char*)sshbuf_ptr(cmd));
2529 channel_request_start(ssh, id, "subsystem", 1);
2530 client_expect_confirm(ssh, id, "subsystem",
2533 debug("Sending command: %.*s",
2534 len, (const u_char*)sshbuf_ptr(cmd));
2535 channel_request_start(ssh, id, "exec", 1);
2536 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
2538 if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
2539 (r = sshpkt_send(ssh)) != 0)
2540 fatal_fr(r, "send command");
2542 channel_request_start(ssh, id, "shell", 1);
2543 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
2544 if ((r = sshpkt_send(ssh)) != 0)
2545 fatal_fr(r, "send shell");
2550 client_init_dispatch(struct ssh *ssh)
2552 ssh_dispatch_init(ssh, &dispatch_protocol_error);
2554 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2555 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2556 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2557 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2558 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2559 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2560 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2561 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2562 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2563 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2564 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2565 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2568 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
2570 /* global request reply messages */
2571 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2572 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2576 client_stop_mux(void)
2578 if (options.control_path != NULL && muxserver_sock != -1)
2579 unlink(options.control_path);
2581 * If we are in persist mode, or don't have a shell, signal that we
2582 * should close when all active channels are closed.
2584 if (options.control_persist || options.session_type == SESSION_TYPE_NONE) {
2586 setproctitle("[stopped mux]");
2590 /* client specific fatal cleanup */
2594 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2595 if (options.control_path != NULL && muxserver_sock != -1)
2596 unlink(options.control_path);
2597 ssh_kill_proxy_command();