1 /* $NetBSD: clientloop.c,v 1.42 2024/07/11 17:26:53 riastradh Exp $ */ 2 /* $OpenBSD: clientloop.c,v 1.408 2024/07/01 04:31:17 djm Exp $ */ 3 4 /* 5 * Author: Tatu Ylonen <ylo@cs.hut.fi> 6 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 7 * All rights reserved 8 * The main loop for the interactive session (client side). 9 * 10 * As far as I am concerned, the code I have written for this software 11 * can be used freely for any purpose. Any derived versions of this 12 * software must be clearly marked as such, and if the derived work is 13 * incompatible with the protocol description in the RFC file, it must be 14 * called by a name other than "ssh" or "Secure Shell". 15 * 16 * 17 * Copyright (c) 1999 Theo de Raadt. All rights reserved. 18 * 19 * Redistribution and use in source and binary forms, with or without 20 * modification, are permitted provided that the following conditions 21 * are met: 22 * 1. Redistributions of source code must retain the above copyright 23 * notice, this list of conditions and the following disclaimer. 24 * 2. Redistributions in binary form must reproduce the above copyright 25 * notice, this list of conditions and the following disclaimer in the 26 * documentation and/or other materials provided with the distribution. 27 * 28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 38 * 39 * 40 * SSH2 support added by Markus Friedl. 41 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved. 42 * 43 * Redistribution and use in source and binary forms, with or without 44 * modification, are permitted provided that the following conditions 45 * are met: 46 * 1. Redistributions of source code must retain the above copyright 47 * notice, this list of conditions and the following disclaimer. 48 * 2. Redistributions in binary form must reproduce the above copyright 49 * notice, this list of conditions and the following disclaimer in the 50 * documentation and/or other materials provided with the distribution. 51 * 52 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 53 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 54 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 55 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 56 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 57 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 58 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 59 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 60 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 61 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 62 */ 63 64 #include "includes.h" 65 __RCSID("$NetBSD: clientloop.c,v 1.42 2024/07/11 17:26:53 riastradh Exp $"); 66 67 #include <sys/types.h> 68 #include <sys/ioctl.h> 69 #include <sys/stat.h> 70 #include <sys/socket.h> 71 #include <sys/time.h> 72 #include <sys/queue.h> 73 74 #include <ctype.h> 75 #include <errno.h> 76 #include <paths.h> 77 #include <poll.h> 78 #include <signal.h> 79 #include <stdio.h> 80 #include <stdlib.h> 81 #include <string.h> 82 #include <stdarg.h> 83 #include <termios.h> 84 #include <pwd.h> 85 #include <unistd.h> 86 #include <limits.h> 87 88 #include "xmalloc.h" 89 #include "ssh.h" 90 #include "ssh2.h" 91 #include "packet.h" 92 #include "sshbuf.h" 93 #include "compat.h" 94 #include "channels.h" 95 #include "dispatch.h" 96 #include "sshkey.h" 97 #include "cipher.h" 98 #include "kex.h" 99 #include "myproposal.h" 100 #include "log.h" 101 #include "misc.h" 102 #include "readconf.h" 103 #include "clientloop.h" 104 #include "sshconnect.h" 105 #include "authfd.h" 106 #include "atomicio.h" 107 #include "sshpty.h" 108 #include "match.h" 109 #include "msg.h" 110 #include "getpeereid.h" 111 #include "ssherr.h" 112 #include "hostfile.h" 113 114 /* Permitted RSA signature algorithms for UpdateHostkeys proofs */ 115 #define HOSTKEY_PROOF_RSA_ALGS "rsa-sha2-512,rsa-sha2-256" 116 117 /* Uncertainty (in percent) of keystroke timing intervals */ 118 #define SSH_KEYSTROKE_TIMING_FUZZ 10 119 120 /* import options */ 121 extern Options options; 122 123 /* Control socket */ 124 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */ 125 126 /* 127 * Name of the host we are connecting to. This is the name given on the 128 * command line, or the Hostname specified for the user-supplied name in a 129 * configuration file. 130 */ 131 extern char *host; 132 133 /* 134 * If this field is not NULL, the ForwardAgent socket is this path and different 135 * instead of SSH_AUTH_SOCK. 136 */ 137 extern char *forward_agent_sock_path; 138 139 /* 140 * Flag to indicate that we have received a window change signal which has 141 * not yet been processed. This will cause a message indicating the new 142 * window size to be sent to the server a little later. This is volatile 143 * because this is updated in a signal handler. 144 */ 145 static volatile sig_atomic_t received_window_change_signal = 0; 146 static volatile sig_atomic_t received_signal = 0; 147 148 /* Time when backgrounded control master using ControlPersist should exit */ 149 static time_t control_persist_exit_time = 0; 150 151 /* Common data for the client loop code. */ 152 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */ 153 static int last_was_cr; /* Last character was a newline. */ 154 static int exit_status; /* Used to store the command exit status. */ 155 static int connection_in; /* Connection to server (input). */ 156 static int connection_out; /* Connection to server (output). */ 157 static int need_rekeying; /* Set to non-zero if rekeying is requested. */ 158 static int session_closed; /* In SSH2: login session closed. */ 159 static time_t x11_refuse_time; /* If >0, refuse x11 opens after this time. */ 160 static time_t server_alive_time; /* Time to do server_alive_check */ 161 static int hostkeys_update_complete; 162 static int session_setup_complete; 163 164 static void client_init_dispatch(struct ssh *ssh); 165 int session_ident = -1; 166 167 /* Track escape per proto2 channel */ 168 struct escape_filter_ctx { 169 int escape_pending; 170 int escape_char; 171 }; 172 173 /* Context for channel confirmation replies */ 174 struct channel_reply_ctx { 175 const char *request_type; 176 int id; 177 enum confirm_action action; 178 }; 179 180 /* Global request success/failure callbacks */ 181 /* XXX move to struct ssh? */ 182 struct global_confirm { 183 TAILQ_ENTRY(global_confirm) entry; 184 global_confirm_cb *cb; 185 void *ctx; 186 int ref_count; 187 }; 188 TAILQ_HEAD(global_confirms, global_confirm); 189 static struct global_confirms global_confirms = 190 TAILQ_HEAD_INITIALIZER(global_confirms); 191 192 static void quit_message(const char *fmt, ...) 193 __attribute__((__format__ (printf, 1, 2))); 194 195 static void 196 quit_message(const char *fmt, ...) 197 { 198 char *msg, *fmt2; 199 va_list args; 200 xasprintf(&fmt2, "%s\r\n", fmt); 201 202 va_start(args, fmt); 203 #pragma GCC diagnostic push 204 #pragma GCC diagnostic ignored "-Wformat-nonliteral" 205 xvasprintf(&msg, fmt2, args); 206 #pragma GCC diagnostic pop 207 va_end(args); 208 209 (void)atomicio(vwrite, STDERR_FILENO, msg, strlen(msg)); 210 free(msg); 211 free(fmt2); 212 213 quit_pending = 1; 214 } 215 216 /* 217 * Signal handler for the window change signal (SIGWINCH). This just sets a 218 * flag indicating that the window has changed. 219 */ 220 static void 221 window_change_handler(int sig) 222 { 223 received_window_change_signal = 1; 224 } 225 226 /* 227 * Signal handler for signals that cause the program to terminate. These 228 * signals must be trapped to restore terminal modes. 229 */ 230 static void 231 signal_handler(int sig) 232 { 233 received_signal = sig; 234 quit_pending = 1; 235 } 236 237 /* 238 * Sets control_persist_exit_time to the absolute time when the 239 * backgrounded control master should exit due to expiry of the 240 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded 241 * control master process, or if there is no ControlPersist timeout. 242 */ 243 static void 244 set_control_persist_exit_time(struct ssh *ssh) 245 { 246 if (muxserver_sock == -1 || !options.control_persist 247 || options.control_persist_timeout == 0) { 248 /* not using a ControlPersist timeout */ 249 control_persist_exit_time = 0; 250 } else if (channel_still_open(ssh)) { 251 /* some client connections are still open */ 252 if (control_persist_exit_time > 0) 253 debug2_f("cancel scheduled exit"); 254 control_persist_exit_time = 0; 255 } else if (control_persist_exit_time <= 0) { 256 /* a client connection has recently closed */ 257 control_persist_exit_time = monotime() + 258 (time_t)options.control_persist_timeout; 259 debug2_f("schedule exit in %d seconds", 260 options.control_persist_timeout); 261 } 262 /* else we are already counting down to the timeout */ 263 } 264 265 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_" 266 static int 267 client_x11_display_valid(const char *display) 268 { 269 size_t i, dlen; 270 271 if (display == NULL) 272 return 0; 273 274 dlen = strlen(display); 275 for (i = 0; i < dlen; i++) { 276 if (!isalnum((u_char)display[i]) && 277 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) { 278 debug("Invalid character '%c' in DISPLAY", display[i]); 279 return 0; 280 } 281 } 282 return 1; 283 } 284 285 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1" 286 #define X11_TIMEOUT_SLACK 60 287 int 288 client_x11_get_proto(struct ssh *ssh, const char *display, 289 const char *xauth_path, u_int trusted, u_int timeout, 290 char **_proto, char **_data) 291 { 292 char *cmd, line[512], xdisplay[512]; 293 char xauthfile[PATH_MAX], xauthdir[PATH_MAX]; 294 static char proto[512], data[512]; 295 FILE *f; 296 int got_data = 0, generated = 0, do_unlink = 0, r; 297 struct stat st; 298 u_int now, x11_timeout_real; 299 300 *_proto = proto; 301 *_data = data; 302 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0'; 303 304 if (!client_x11_display_valid(display)) { 305 if (display != NULL) 306 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding", 307 display); 308 return -1; 309 } 310 if (xauth_path != NULL && stat(xauth_path, &st) == -1) { 311 debug("No xauth program."); 312 xauth_path = NULL; 313 } 314 315 if (xauth_path != NULL) { 316 /* 317 * Handle FamilyLocal case where $DISPLAY does 318 * not match an authorization entry. For this we 319 * just try "xauth list unix:displaynum.screennum". 320 * XXX: "localhost" match to determine FamilyLocal 321 * is not perfect. 322 */ 323 if (strncmp(display, "localhost:", 10) == 0) { 324 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s", 325 display + 10)) < 0 || 326 (size_t)r >= sizeof(xdisplay)) { 327 error_f("display name too long"); 328 return -1; 329 } 330 display = xdisplay; 331 } 332 if (trusted == 0) { 333 /* 334 * Generate an untrusted X11 auth cookie. 335 * 336 * The authentication cookie should briefly outlive 337 * ssh's willingness to forward X11 connections to 338 * avoid nasty fail-open behaviour in the X server. 339 */ 340 mktemp_proto(xauthdir, sizeof(xauthdir)); 341 if (mkdtemp(xauthdir) == NULL) { 342 error_f("mkdtemp: %s", strerror(errno)); 343 return -1; 344 } 345 do_unlink = 1; 346 if ((r = snprintf(xauthfile, sizeof(xauthfile), 347 "%s/xauthfile", xauthdir)) < 0 || 348 (size_t)r >= sizeof(xauthfile)) { 349 error_f("xauthfile path too long"); 350 rmdir(xauthdir); 351 return -1; 352 } 353 354 if (timeout == 0) { 355 /* auth doesn't time out */ 356 xasprintf(&cmd, "%s -f %s generate %s %s " 357 "untrusted 2>%s", 358 xauth_path, xauthfile, display, 359 SSH_X11_PROTO, _PATH_DEVNULL); 360 } else { 361 /* Add some slack to requested expiry */ 362 if (timeout < UINT_MAX - X11_TIMEOUT_SLACK) 363 x11_timeout_real = timeout + 364 X11_TIMEOUT_SLACK; 365 else { 366 /* Don't overflow on long timeouts */ 367 x11_timeout_real = UINT_MAX; 368 } 369 xasprintf(&cmd, "%s -f %s generate %s %s " 370 "untrusted timeout %u 2>%s", 371 xauth_path, xauthfile, display, 372 SSH_X11_PROTO, x11_timeout_real, 373 _PATH_DEVNULL); 374 } 375 debug2_f("xauth command: %s", cmd); 376 377 if (timeout != 0 && x11_refuse_time == 0) { 378 now = monotime() + 1; 379 if (SSH_TIME_T_MAX - timeout < now) 380 x11_refuse_time = SSH_TIME_T_MAX; 381 else 382 x11_refuse_time = now + timeout; 383 channel_set_x11_refuse_time(ssh, 384 x11_refuse_time); 385 } 386 if (system(cmd) == 0) 387 generated = 1; 388 free(cmd); 389 } 390 391 /* 392 * When in untrusted mode, we read the cookie only if it was 393 * successfully generated as an untrusted one in the step 394 * above. 395 */ 396 if (trusted || generated) { 397 xasprintf(&cmd, 398 "%s %s%s list %s 2>" _PATH_DEVNULL, 399 xauth_path, 400 generated ? "-f " : "" , 401 generated ? xauthfile : "", 402 display); 403 debug2("x11_get_proto: %s", cmd); 404 f = popen(cmd, "r"); 405 if (f && fgets(line, sizeof(line), f) && 406 sscanf(line, "%*s %511s %511s", proto, data) == 2) 407 got_data = 1; 408 if (f) 409 pclose(f); 410 free(cmd); 411 } 412 } 413 414 if (do_unlink) { 415 unlink(xauthfile); 416 rmdir(xauthdir); 417 } 418 419 /* Don't fall back to fake X11 data for untrusted forwarding */ 420 if (!trusted && !got_data) { 421 error("Warning: untrusted X11 forwarding setup failed: " 422 "xauth key data not generated"); 423 return -1; 424 } 425 426 /* 427 * If we didn't get authentication data, just make up some 428 * data. The forwarding code will check the validity of the 429 * response anyway, and substitute this data. The X11 430 * server, however, will ignore this fake data and use 431 * whatever authentication mechanisms it was using otherwise 432 * for the local connection. 433 */ 434 if (!got_data) { 435 u_int8_t rnd[16]; 436 u_int i; 437 438 logit("Warning: No xauth data; " 439 "using fake authentication data for X11 forwarding."); 440 strlcpy(proto, SSH_X11_PROTO, sizeof proto); 441 arc4random_buf(rnd, sizeof(rnd)); 442 for (i = 0; i < sizeof(rnd); i++) { 443 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", 444 rnd[i]); 445 } 446 } 447 448 return 0; 449 } 450 451 /* 452 * Checks if the client window has changed, and sends a packet about it to 453 * the server if so. The actual change is detected elsewhere (by a software 454 * interrupt on Unix); this just checks the flag and sends a message if 455 * appropriate. 456 */ 457 458 static void 459 client_check_window_change(struct ssh *ssh) 460 { 461 if (!received_window_change_signal) 462 return; 463 received_window_change_signal = 0; 464 debug2_f("changed"); 465 channel_send_window_changes(ssh); 466 } 467 468 static int 469 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh) 470 { 471 struct global_confirm *gc; 472 473 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL) 474 return 0; 475 if (gc->cb != NULL) 476 gc->cb(ssh, type, seq, gc->ctx); 477 if (--gc->ref_count <= 0) { 478 TAILQ_REMOVE(&global_confirms, gc, entry); 479 freezero(gc, sizeof(*gc)); 480 } 481 482 ssh_packet_set_alive_timeouts(ssh, 0); 483 return 0; 484 } 485 486 static void 487 schedule_server_alive_check(void) 488 { 489 if (options.server_alive_interval > 0) 490 server_alive_time = monotime() + options.server_alive_interval; 491 } 492 493 static void 494 server_alive_check(struct ssh *ssh) 495 { 496 int r; 497 498 if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) { 499 logit("Timeout, server %s not responding.", host); 500 cleanup_exit(255); 501 } 502 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 503 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 || 504 (r = sshpkt_put_u8(ssh, 1)) != 0 || /* boolean: want reply */ 505 (r = sshpkt_send(ssh)) != 0) 506 fatal_fr(r, "send packet"); 507 /* Insert an empty placeholder to maintain ordering */ 508 client_register_global_confirm(NULL, NULL); 509 schedule_server_alive_check(); 510 } 511 512 /* Try to send a dummy keystroke */ 513 static int 514 send_chaff(struct ssh *ssh) 515 { 516 int r; 517 518 if (ssh->kex == NULL || (ssh->kex->flags & KEX_HAS_PING) == 0) 519 return 0; 520 /* XXX probabilistically send chaff? */ 521 /* 522 * a SSH2_MSG_CHANNEL_DATA payload is 9 bytes: 523 * 4 bytes channel ID + 4 bytes string length + 1 byte string data 524 * simulate that here. 525 */ 526 if ((r = sshpkt_start(ssh, SSH2_MSG_PING)) != 0 || 527 (r = sshpkt_put_cstring(ssh, "PING!")) != 0 || 528 (r = sshpkt_send(ssh)) != 0) 529 fatal_fr(r, "send packet"); 530 return 1; 531 } 532 533 /* Sets the next interval to send a keystroke or chaff packet */ 534 static void 535 set_next_interval(const struct timespec *now, struct timespec *next_interval, 536 u_int interval_ms, int starting) 537 { 538 struct timespec tmp; 539 long long interval_ns, fuzz_ns; 540 static long long rate_fuzz; 541 542 interval_ns = interval_ms * (1000LL * 1000); 543 fuzz_ns = (interval_ns * SSH_KEYSTROKE_TIMING_FUZZ) / 100; 544 /* Center fuzz around requested interval */ 545 if (fuzz_ns > INT_MAX) 546 fuzz_ns = INT_MAX; 547 if (fuzz_ns > interval_ns) { 548 /* Shouldn't happen */ 549 fatal_f("internal error: fuzz %u%% %lldns > interval %lldns", 550 SSH_KEYSTROKE_TIMING_FUZZ, fuzz_ns, interval_ns); 551 } 552 /* 553 * Randomise the keystroke/chaff intervals in two ways: 554 * 1. Each interval has some random jitter applied to make the 555 * interval-to-interval time unpredictable. 556 * 2. The overall interval rate is also randomly perturbed for each 557 * chaffing session to make the average rate unpredictable. 558 */ 559 if (starting) 560 rate_fuzz = arc4random_uniform(fuzz_ns); 561 interval_ns -= fuzz_ns; 562 interval_ns += arc4random_uniform(fuzz_ns) + rate_fuzz; 563 564 tmp.tv_sec = interval_ns / (1000 * 1000 * 1000); 565 tmp.tv_nsec = interval_ns % (1000 * 1000 * 1000); 566 567 timespecadd(now, &tmp, next_interval); 568 } 569 570 /* 571 * Performs keystroke timing obfuscation. Returns non-zero if the 572 * output fd should be polled. 573 */ 574 static int 575 obfuscate_keystroke_timing(struct ssh *ssh, struct timespec *timeout, 576 int channel_did_enqueue) 577 { 578 static int active; 579 static struct timespec next_interval, chaff_until; 580 struct timespec now, tmp; 581 int just_started = 0, had_keystroke = 0; 582 static unsigned long long nchaff; 583 const char *stop_reason = NULL; 584 long long n; 585 586 monotime_ts(&now); 587 588 if (options.obscure_keystroke_timing_interval <= 0) 589 return 1; /* disabled in config */ 590 591 if (!channel_tty_open(ssh) || quit_pending) { 592 /* Stop if no channels left of we're waiting for one to close */ 593 stop_reason = "no active channels"; 594 } else if (ssh_packet_is_rekeying(ssh)) { 595 /* Stop if we're rekeying */ 596 stop_reason = "rekeying started"; 597 } else if (!ssh_packet_interactive_data_to_write(ssh) && 598 ssh_packet_have_data_to_write(ssh)) { 599 /* Stop if the output buffer has more than a few keystrokes */ 600 stop_reason = "output buffer filling"; 601 } else if (active && channel_did_enqueue && 602 ssh_packet_have_data_to_write(ssh)) { 603 /* Still in active mode and have a keystroke queued. */ 604 had_keystroke = 1; 605 } else if (active) { 606 if (timespeccmp(&now, &chaff_until, >=)) { 607 /* Stop if there have been no keystrokes for a while */ 608 stop_reason = "chaff time expired"; 609 } else if (timespeccmp(&now, &next_interval, >=) && 610 !ssh_packet_have_data_to_write(ssh)) { 611 /* If due to send but have no data, then send chaff */ 612 if (send_chaff(ssh)) 613 nchaff++; 614 } 615 } 616 617 if (stop_reason != NULL) { 618 if (active) { 619 debug3_f("stopping: %s (%llu chaff packets sent)", 620 stop_reason, nchaff); 621 active = 0; 622 } 623 return 1; 624 } 625 626 /* 627 * If we're in interactive mode, and only have a small amount 628 * of outbound data, then we assume that the user is typing 629 * interactively. In this case, start quantising outbound packets to 630 * fixed time intervals to hide inter-keystroke timing. 631 */ 632 if (!active && ssh_packet_interactive_data_to_write(ssh) && 633 channel_did_enqueue && ssh_packet_have_data_to_write(ssh)) { 634 debug3_f("starting: interval ~%dms", 635 options.obscure_keystroke_timing_interval); 636 just_started = had_keystroke = active = 1; 637 nchaff = 0; 638 set_next_interval(&now, &next_interval, 639 options.obscure_keystroke_timing_interval, 1); 640 } 641 642 /* Don't hold off if obfuscation inactive */ 643 if (!active) 644 return 1; 645 646 if (had_keystroke) { 647 /* 648 * Arrange to send chaff packets for a random interval after 649 * the last keystroke was sent. 650 */ 651 ms_to_timespec(&tmp, SSH_KEYSTROKE_CHAFF_MIN_MS + 652 arc4random_uniform(SSH_KEYSTROKE_CHAFF_RNG_MS)); 653 timespecadd(&now, &tmp, &chaff_until); 654 } 655 656 ptimeout_deadline_monotime_tsp(timeout, &next_interval); 657 658 if (just_started) 659 return 1; 660 661 /* Don't arm output fd for poll until the timing interval has elapsed */ 662 if (timespeccmp(&now, &next_interval, <)) 663 return 0; 664 665 /* Calculate number of intervals missed since the last check */ 666 n = (now.tv_sec - next_interval.tv_sec) * 1000LL * 1000 * 1000; 667 n += now.tv_nsec - next_interval.tv_nsec; 668 n /= options.obscure_keystroke_timing_interval * 1000LL * 1000; 669 n = (n < 0) ? 1 : n + 1; 670 671 /* Advance to the next interval */ 672 set_next_interval(&now, &next_interval, 673 options.obscure_keystroke_timing_interval * n, 0); 674 return 1; 675 } 676 677 /* 678 * Waits until the client can do something (some data becomes available on 679 * one of the file descriptors). 680 */ 681 static void 682 client_wait_until_can_do_something(struct ssh *ssh, struct pollfd **pfdp, 683 u_int *npfd_allocp, u_int *npfd_activep, int channel_did_enqueue, 684 sigset_t *sigsetp, int *conn_in_readyp, int *conn_out_readyp) 685 { 686 struct timespec timeout; 687 int ret, oready; 688 u_int p; 689 690 *conn_in_readyp = *conn_out_readyp = 0; 691 692 /* Prepare channel poll. First two pollfd entries are reserved */ 693 ptimeout_init(&timeout); 694 channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout); 695 if (*npfd_activep < 2) 696 fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */ 697 698 /* channel_prepare_poll could have closed the last channel */ 699 if (session_closed && !channel_still_open(ssh) && 700 !ssh_packet_have_data_to_write(ssh)) { 701 /* clear events since we did not call poll() */ 702 for (p = 0; p < *npfd_activep; p++) 703 (*pfdp)[p].revents = 0; 704 return; 705 } 706 707 oready = obfuscate_keystroke_timing(ssh, &timeout, channel_did_enqueue); 708 709 /* Monitor server connection on reserved pollfd entries */ 710 (*pfdp)[0].fd = connection_in; 711 (*pfdp)[0].events = POLLIN; 712 (*pfdp)[1].fd = connection_out; 713 (*pfdp)[1].events = (oready && ssh_packet_have_data_to_write(ssh)) ? 714 POLLOUT : 0; 715 716 /* 717 * Wait for something to happen. This will suspend the process until 718 * some polled descriptor can be read, written, or has some other 719 * event pending, or a timeout expires. 720 */ 721 set_control_persist_exit_time(ssh); 722 if (control_persist_exit_time > 0) 723 ptimeout_deadline_monotime(&timeout, control_persist_exit_time); 724 if (options.server_alive_interval > 0) 725 ptimeout_deadline_monotime(&timeout, server_alive_time); 726 if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) { 727 ptimeout_deadline_sec(&timeout, 728 ssh_packet_get_rekey_timeout(ssh)); 729 } 730 731 ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp); 732 733 if (ret == -1) { 734 /* 735 * We have to clear the events because we return. 736 * We have to return, because the mainloop checks for the flags 737 * set by the signal handlers. 738 */ 739 for (p = 0; p < *npfd_activep; p++) 740 (*pfdp)[p].revents = 0; 741 if (errno == EINTR) 742 return; 743 /* Note: we might still have data in the buffers. */ 744 quit_message("poll: %s", strerror(errno)); 745 return; 746 } 747 748 *conn_in_readyp = (*pfdp)[0].revents != 0; 749 *conn_out_readyp = (*pfdp)[1].revents != 0; 750 751 if (options.server_alive_interval > 0 && !*conn_in_readyp && 752 monotime() >= server_alive_time) { 753 /* 754 * ServerAlive check is needed. We can't rely on the poll 755 * timing out since traffic on the client side such as port 756 * forwards can keep waking it up. 757 */ 758 server_alive_check(ssh); 759 } 760 } 761 762 static void 763 client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr) 764 { 765 /* Flush stdout and stderr buffers. */ 766 if (sshbuf_len(bout) > 0) 767 atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout), 768 sshbuf_len(bout)); 769 if (sshbuf_len(berr) > 0) 770 atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr), 771 sshbuf_len(berr)); 772 773 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 774 775 sshbuf_reset(bin); 776 sshbuf_reset(bout); 777 sshbuf_reset(berr); 778 779 /* Send the suspend signal to the program itself. */ 780 kill(getpid(), SIGTSTP); 781 782 /* Reset window sizes in case they have changed */ 783 received_window_change_signal = 1; 784 785 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 786 } 787 788 static void 789 client_process_net_input(struct ssh *ssh) 790 { 791 int r; 792 793 /* 794 * Read input from the server, and add any such data to the buffer of 795 * the packet subsystem. 796 */ 797 schedule_server_alive_check(); 798 if ((r = ssh_packet_process_read(ssh, connection_in)) == 0) 799 return; /* success */ 800 if (r == SSH_ERR_SYSTEM_ERROR) { 801 if (errno == EAGAIN || errno == EINTR) 802 return; 803 if (errno == EPIPE) { 804 quit_message("Connection to %s closed by remote host.", 805 host); 806 return; 807 } 808 } 809 quit_message("Read from remote host %s: %s", host, ssh_err(r)); 810 } 811 812 static void 813 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx) 814 { 815 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx; 816 char errmsg[256]; 817 int r, tochan; 818 819 /* 820 * If a TTY was explicitly requested, then a failure to allocate 821 * one is fatal. 822 */ 823 if (cr->action == CONFIRM_TTY && 824 (options.request_tty == REQUEST_TTY_FORCE || 825 options.request_tty == REQUEST_TTY_YES)) 826 cr->action = CONFIRM_CLOSE; 827 828 /* XXX suppress on mux _client_ quietmode */ 829 tochan = options.log_level >= SYSLOG_LEVEL_ERROR && 830 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE; 831 832 if (type == SSH2_MSG_CHANNEL_SUCCESS) { 833 debug2("%s request accepted on channel %d", 834 cr->request_type, c->self); 835 } else if (type == SSH2_MSG_CHANNEL_FAILURE) { 836 if (tochan) { 837 snprintf(errmsg, sizeof(errmsg), 838 "%s request failed\r\n", cr->request_type); 839 } else { 840 snprintf(errmsg, sizeof(errmsg), 841 "%s request failed on channel %d", 842 cr->request_type, c->self); 843 } 844 /* If error occurred on primary session channel, then exit */ 845 if (cr->action == CONFIRM_CLOSE && c->self == session_ident) 846 fatal("%s", errmsg); 847 /* 848 * If error occurred on mux client, append to 849 * their stderr. 850 */ 851 if (tochan) { 852 debug3_f("channel %d: mux request: %s", c->self, 853 cr->request_type); 854 if ((r = sshbuf_put(c->extended, errmsg, 855 strlen(errmsg))) != 0) 856 fatal_fr(r, "sshbuf_put"); 857 } else 858 error("%s", errmsg); 859 if (cr->action == CONFIRM_TTY) { 860 /* 861 * If a TTY allocation error occurred, then arrange 862 * for the correct TTY to leave raw mode. 863 */ 864 if (c->self == session_ident) 865 leave_raw_mode(0); 866 else 867 mux_tty_alloc_failed(ssh, c); 868 } else if (cr->action == CONFIRM_CLOSE) { 869 chan_read_failed(ssh, c); 870 chan_write_failed(ssh, c); 871 } 872 } 873 free(cr); 874 } 875 876 static void 877 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx) 878 { 879 free(ctx); 880 } 881 882 void 883 client_expect_confirm(struct ssh *ssh, int id, const char *request, 884 enum confirm_action action) 885 { 886 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr)); 887 888 cr->request_type = request; 889 cr->action = action; 890 891 channel_register_status_confirm(ssh, id, client_status_confirm, 892 client_abandon_status_confirm, cr); 893 } 894 895 void 896 client_register_global_confirm(global_confirm_cb *cb, void *ctx) 897 { 898 struct global_confirm *gc, *last_gc; 899 900 /* Coalesce identical callbacks */ 901 last_gc = TAILQ_LAST(&global_confirms, global_confirms); 902 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) { 903 if (++last_gc->ref_count >= INT_MAX) 904 fatal_f("last_gc->ref_count = %d", 905 last_gc->ref_count); 906 return; 907 } 908 909 gc = xcalloc(1, sizeof(*gc)); 910 gc->cb = cb; 911 gc->ctx = ctx; 912 gc->ref_count = 1; 913 TAILQ_INSERT_TAIL(&global_confirms, gc, entry); 914 } 915 916 /* 917 * Returns non-zero if the client is able to handle a hostkeys-00@openssh.com 918 * hostkey update request. 919 */ 920 static int 921 can_update_hostkeys(void) 922 { 923 if (hostkeys_update_complete) 924 return 0; 925 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK && 926 options.batch_mode) 927 return 0; /* won't ask in batchmode, so don't even try */ 928 if (!options.update_hostkeys || options.num_user_hostfiles <= 0) 929 return 0; 930 return 1; 931 } 932 933 static void 934 client_repledge(void) 935 { 936 debug3_f("enter"); 937 938 /* Might be able to tighten pledge now that session is established */ 939 if (options.control_master || options.control_path != NULL || 940 options.forward_x11 || options.fork_after_authentication || 941 can_update_hostkeys() || 942 (session_ident != -1 && !session_setup_complete)) { 943 /* Can't tighten */ 944 return; 945 } 946 #ifdef __OpenBSD__ 947 /* 948 * LocalCommand and UpdateHostkeys have finished, so can get rid of 949 * filesystem. 950 * 951 * XXX protocol allows a server can to change hostkeys during the 952 * connection at rekey time that could trigger a hostkeys update 953 * but AFAIK no implementations support this. Could improve by 954 * forcing known_hosts to be read-only or via unveil(2). 955 */ 956 if (options.num_local_forwards != 0 || 957 options.num_remote_forwards != 0 || 958 options.num_permitted_remote_opens != 0 || 959 options.enable_escape_commandline != 0) { 960 /* rfwd needs inet */ 961 debug("pledge: network"); 962 if (pledge("stdio unix inet dns proc tty", NULL) == -1) 963 fatal_f("pledge(): %s", strerror(errno)); 964 } else if (options.forward_agent != 0) { 965 /* agent forwarding needs to open $SSH_AUTH_SOCK at will */ 966 debug("pledge: agent"); 967 if (pledge("stdio unix proc tty", NULL) == -1) 968 fatal_f("pledge(): %s", strerror(errno)); 969 } else { 970 debug("pledge: fork"); 971 if (pledge("stdio proc tty", NULL) == -1) 972 fatal_f("pledge(): %s", strerror(errno)); 973 } 974 #endif 975 /* XXX further things to do: 976 * 977 * - might be able to get rid of proc if we kill ~^Z 978 * - ssh -N (no session) 979 * - stdio forwarding 980 * - sessions without tty 981 */ 982 } 983 984 static void 985 process_cmdline(struct ssh *ssh) 986 { 987 void (*handler)(int); 988 char *s, *cmd; 989 int ok, delete = 0, local = 0, remote = 0, dynamic = 0; 990 struct Forward fwd; 991 992 memset(&fwd, 0, sizeof(fwd)); 993 994 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 995 handler = ssh_signal(SIGINT, SIG_IGN); 996 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO); 997 if (s == NULL) 998 goto out; 999 while (isspace((u_char)*s)) 1000 s++; 1001 if (*s == '-') 1002 s++; /* Skip cmdline '-', if any */ 1003 if (*s == '\0') 1004 goto out; 1005 1006 if (*s == 'h' || *s == 'H' || *s == '?') { 1007 logit("Commands:"); 1008 logit(" -L[bind_address:]port:host:hostport " 1009 "Request local forward"); 1010 logit(" -R[bind_address:]port:host:hostport " 1011 "Request remote forward"); 1012 logit(" -D[bind_address:]port " 1013 "Request dynamic forward"); 1014 logit(" -KL[bind_address:]port " 1015 "Cancel local forward"); 1016 logit(" -KR[bind_address:]port " 1017 "Cancel remote forward"); 1018 logit(" -KD[bind_address:]port " 1019 "Cancel dynamic forward"); 1020 if (!options.permit_local_command) 1021 goto out; 1022 logit(" !args " 1023 "Execute local command"); 1024 goto out; 1025 } 1026 1027 if (*s == '!' && options.permit_local_command) { 1028 s++; 1029 ssh_local_cmd(s); 1030 goto out; 1031 } 1032 1033 if (*s == 'K') { 1034 delete = 1; 1035 s++; 1036 } 1037 if (*s == 'L') 1038 local = 1; 1039 else if (*s == 'R') 1040 remote = 1; 1041 else if (*s == 'D') 1042 dynamic = 1; 1043 else { 1044 logit("Invalid command."); 1045 goto out; 1046 } 1047 1048 while (isspace((u_char)*++s)) 1049 ; 1050 1051 /* XXX update list of forwards in options */ 1052 if (delete) { 1053 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */ 1054 if (!parse_forward(&fwd, s, 1, 0)) { 1055 logit("Bad forwarding close specification."); 1056 goto out; 1057 } 1058 if (remote) 1059 ok = channel_request_rforward_cancel(ssh, &fwd) == 0; 1060 else if (dynamic) 1061 ok = channel_cancel_lport_listener(ssh, &fwd, 1062 0, &options.fwd_opts) > 0; 1063 else 1064 ok = channel_cancel_lport_listener(ssh, &fwd, 1065 CHANNEL_CANCEL_PORT_STATIC, 1066 &options.fwd_opts) > 0; 1067 if (!ok) { 1068 logit("Unknown port forwarding."); 1069 goto out; 1070 } 1071 logit("Canceled forwarding."); 1072 } else { 1073 /* -R specs can be both dynamic or not, so check both. */ 1074 if (remote) { 1075 if (!parse_forward(&fwd, s, 0, remote) && 1076 !parse_forward(&fwd, s, 1, remote)) { 1077 logit("Bad remote forwarding specification."); 1078 goto out; 1079 } 1080 } else if (!parse_forward(&fwd, s, dynamic, remote)) { 1081 logit("Bad local forwarding specification."); 1082 goto out; 1083 } 1084 if (local || dynamic) { 1085 if (!channel_setup_local_fwd_listener(ssh, &fwd, 1086 &options.fwd_opts)) { 1087 logit("Port forwarding failed."); 1088 goto out; 1089 } 1090 } else { 1091 if (channel_request_remote_forwarding(ssh, &fwd) < 0) { 1092 logit("Port forwarding failed."); 1093 goto out; 1094 } 1095 } 1096 logit("Forwarding port."); 1097 } 1098 1099 out: 1100 ssh_signal(SIGINT, handler); 1101 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1102 free(cmd); 1103 free(fwd.listen_host); 1104 free(fwd.listen_path); 1105 free(fwd.connect_host); 1106 free(fwd.connect_path); 1107 } 1108 1109 /* reasons to suppress output of an escape command in help output */ 1110 #define SUPPRESS_NEVER 0 /* never suppress, always show */ 1111 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */ 1112 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */ 1113 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */ 1114 #define SUPPRESS_NOCMDLINE 8 /* don't show when cmdline disabled*/ 1115 struct escape_help_text { 1116 const char *cmd; 1117 const char *text; 1118 unsigned int flags; 1119 }; 1120 static struct escape_help_text esc_txt[] = { 1121 {".", "terminate session", SUPPRESS_MUXMASTER}, 1122 {".", "terminate connection (and any multiplexed sessions)", 1123 SUPPRESS_MUXCLIENT}, 1124 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER}, 1125 {"C", "open a command line", SUPPRESS_MUXCLIENT|SUPPRESS_NOCMDLINE}, 1126 {"R", "request rekey", SUPPRESS_NEVER}, 1127 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT}, 1128 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT}, 1129 {"#", "list forwarded connections", SUPPRESS_NEVER}, 1130 {"&", "background ssh (when waiting for connections to terminate)", 1131 SUPPRESS_MUXCLIENT}, 1132 {"?", "this message", SUPPRESS_NEVER}, 1133 }; 1134 1135 static void 1136 print_escape_help(struct sshbuf *b, int escape_char, int mux_client, 1137 int using_stderr) 1138 { 1139 unsigned int i, suppress_flags; 1140 int r; 1141 1142 if ((r = sshbuf_putf(b, 1143 "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0) 1144 fatal_fr(r, "sshbuf_putf"); 1145 1146 suppress_flags = 1147 (mux_client ? SUPPRESS_MUXCLIENT : 0) | 1148 (mux_client ? 0 : SUPPRESS_MUXMASTER) | 1149 (using_stderr ? 0 : SUPPRESS_SYSLOG) | 1150 (options.enable_escape_commandline == 0 ? SUPPRESS_NOCMDLINE : 0); 1151 1152 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) { 1153 if (esc_txt[i].flags & suppress_flags) 1154 continue; 1155 if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n", 1156 escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0) 1157 fatal_fr(r, "sshbuf_putf"); 1158 } 1159 1160 if ((r = sshbuf_putf(b, 1161 " %c%c - send the escape character by typing it twice\r\n" 1162 "(Note that escapes are only recognized immediately after " 1163 "newline.)\r\n", escape_char, escape_char)) != 0) 1164 fatal_fr(r, "sshbuf_putf"); 1165 } 1166 1167 /* 1168 * Process the characters one by one. 1169 */ 1170 static int 1171 process_escapes(struct ssh *ssh, Channel *c, 1172 struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr, 1173 const char *buf, int len) 1174 { 1175 pid_t pid; 1176 int r, bytes = 0; 1177 u_int i; 1178 u_char ch; 1179 char *s; 1180 struct escape_filter_ctx *efc; 1181 1182 if (c == NULL || c->filter_ctx == NULL || len <= 0) 1183 return 0; 1184 1185 efc = (struct escape_filter_ctx *)c->filter_ctx; 1186 1187 for (i = 0; i < (u_int)len; i++) { 1188 /* Get one character at a time. */ 1189 ch = buf[i]; 1190 1191 if (efc->escape_pending) { 1192 /* We have previously seen an escape character. */ 1193 /* Clear the flag now. */ 1194 efc->escape_pending = 0; 1195 1196 /* Process the escaped character. */ 1197 switch (ch) { 1198 case '.': 1199 /* Terminate the connection. */ 1200 if ((r = sshbuf_putf(berr, "%c.\r\n", 1201 efc->escape_char)) != 0) 1202 fatal_fr(r, "sshbuf_putf"); 1203 if (c && c->ctl_chan != -1) { 1204 channel_force_close(ssh, c, 1); 1205 return 0; 1206 } else 1207 quit_pending = 1; 1208 return -1; 1209 1210 case 'Z' - 64: 1211 /* XXX support this for mux clients */ 1212 if (c && c->ctl_chan != -1) { 1213 char b[16]; 1214 noescape: 1215 if (ch == 'Z' - 64) 1216 snprintf(b, sizeof b, "^Z"); 1217 else 1218 snprintf(b, sizeof b, "%c", ch); 1219 if ((r = sshbuf_putf(berr, 1220 "%c%s escape not available to " 1221 "multiplexed sessions\r\n", 1222 efc->escape_char, b)) != 0) 1223 fatal_fr(r, "sshbuf_putf"); 1224 continue; 1225 } 1226 /* Suspend the program. Inform the user */ 1227 if ((r = sshbuf_putf(berr, 1228 "%c^Z [suspend ssh]\r\n", 1229 efc->escape_char)) != 0) 1230 fatal_fr(r, "sshbuf_putf"); 1231 1232 /* Restore terminal modes and suspend. */ 1233 client_suspend_self(bin, bout, berr); 1234 1235 /* We have been continued. */ 1236 continue; 1237 1238 case 'B': 1239 if ((r = sshbuf_putf(berr, 1240 "%cB\r\n", efc->escape_char)) != 0) 1241 fatal_fr(r, "sshbuf_putf"); 1242 channel_request_start(ssh, c->self, "break", 0); 1243 if ((r = sshpkt_put_u32(ssh, 1000)) != 0 || 1244 (r = sshpkt_send(ssh)) != 0) 1245 fatal_fr(r, "send packet"); 1246 continue; 1247 1248 case 'R': 1249 if (ssh->compat & SSH_BUG_NOREKEY) 1250 logit("Server does not " 1251 "support re-keying"); 1252 else 1253 need_rekeying = 1; 1254 continue; 1255 1256 case 'V': 1257 /* FALLTHROUGH */ 1258 case 'v': 1259 if (c && c->ctl_chan != -1) 1260 goto noescape; 1261 if (!log_is_on_stderr()) { 1262 if ((r = sshbuf_putf(berr, 1263 "%c%c [Logging to syslog]\r\n", 1264 efc->escape_char, ch)) != 0) 1265 fatal_fr(r, "sshbuf_putf"); 1266 continue; 1267 } 1268 if (ch == 'V' && options.log_level > 1269 SYSLOG_LEVEL_QUIET) 1270 log_change_level(--options.log_level); 1271 if (ch == 'v' && options.log_level < 1272 SYSLOG_LEVEL_DEBUG3) 1273 log_change_level(++options.log_level); 1274 if ((r = sshbuf_putf(berr, 1275 "%c%c [LogLevel %s]\r\n", 1276 efc->escape_char, ch, 1277 log_level_name(options.log_level))) != 0) 1278 fatal_fr(r, "sshbuf_putf"); 1279 continue; 1280 1281 case '&': 1282 if (c->ctl_chan != -1) 1283 goto noescape; 1284 /* 1285 * Detach the program (continue to serve 1286 * connections, but put in background and no 1287 * more new connections). 1288 */ 1289 /* Restore tty modes. */ 1290 leave_raw_mode( 1291 options.request_tty == REQUEST_TTY_FORCE); 1292 1293 /* Stop listening for new connections. */ 1294 channel_stop_listening(ssh); 1295 1296 if ((r = sshbuf_putf(berr, "%c& " 1297 "[backgrounded]\n", efc->escape_char)) != 0) 1298 fatal_fr(r, "sshbuf_putf"); 1299 1300 /* Fork into background. */ 1301 pid = fork(); 1302 if (pid == -1) { 1303 error("fork: %.100s", strerror(errno)); 1304 continue; 1305 } 1306 if (pid != 0) { /* This is the parent. */ 1307 /* The parent just exits. */ 1308 exit(0); 1309 } 1310 /* The child continues serving connections. */ 1311 /* fake EOF on stdin */ 1312 if ((r = sshbuf_put_u8(bin, 4)) != 0) 1313 fatal_fr(r, "sshbuf_put_u8"); 1314 return -1; 1315 case '?': 1316 print_escape_help(berr, efc->escape_char, 1317 (c && c->ctl_chan != -1), 1318 log_is_on_stderr()); 1319 continue; 1320 1321 case '#': 1322 if ((r = sshbuf_putf(berr, "%c#\r\n", 1323 efc->escape_char)) != 0) 1324 fatal_fr(r, "sshbuf_putf"); 1325 s = channel_open_message(ssh); 1326 if ((r = sshbuf_put(berr, s, strlen(s))) != 0) 1327 fatal_fr(r, "sshbuf_put"); 1328 free(s); 1329 continue; 1330 1331 case 'C': 1332 if (c && c->ctl_chan != -1) 1333 goto noescape; 1334 if (options.enable_escape_commandline == 0) { 1335 if ((r = sshbuf_putf(berr, 1336 "commandline disabled\r\n")) != 0) 1337 fatal_fr(r, "sshbuf_putf"); 1338 continue; 1339 } 1340 process_cmdline(ssh); 1341 continue; 1342 1343 default: 1344 if (ch != efc->escape_char) { 1345 if ((r = sshbuf_put_u8(bin, 1346 efc->escape_char)) != 0) 1347 fatal_fr(r, "sshbuf_put_u8"); 1348 bytes++; 1349 } 1350 /* Escaped characters fall through here */ 1351 break; 1352 } 1353 } else { 1354 /* 1355 * The previous character was not an escape char. 1356 * Check if this is an escape. 1357 */ 1358 if (last_was_cr && ch == efc->escape_char) { 1359 /* 1360 * It is. Set the flag and continue to 1361 * next character. 1362 */ 1363 efc->escape_pending = 1; 1364 continue; 1365 } 1366 } 1367 1368 /* 1369 * Normal character. Record whether it was a newline, 1370 * and append it to the buffer. 1371 */ 1372 last_was_cr = (ch == '\r' || ch == '\n'); 1373 if ((r = sshbuf_put_u8(bin, ch)) != 0) 1374 fatal_fr(r, "sshbuf_put_u8"); 1375 bytes++; 1376 } 1377 return bytes; 1378 } 1379 1380 /* 1381 * Get packets from the connection input buffer, and process them as long as 1382 * there are packets available. 1383 * 1384 * Any unknown packets received during the actual 1385 * session cause the session to terminate. This is 1386 * intended to make debugging easier since no 1387 * confirmations are sent. Any compatible protocol 1388 * extensions must be negotiated during the 1389 * preparatory phase. 1390 */ 1391 1392 static void 1393 client_process_buffered_input_packets(struct ssh *ssh) 1394 { 1395 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending); 1396 } 1397 1398 /* scan buf[] for '~' before sending data to the peer */ 1399 1400 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */ 1401 void * 1402 client_new_escape_filter_ctx(int escape_char) 1403 { 1404 struct escape_filter_ctx *ret; 1405 1406 ret = xcalloc(1, sizeof(*ret)); 1407 ret->escape_pending = 0; 1408 ret->escape_char = escape_char; 1409 return (void *)ret; 1410 } 1411 1412 /* Free the escape filter context on channel free */ 1413 void 1414 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx) 1415 { 1416 free(ctx); 1417 } 1418 1419 int 1420 client_simple_escape_filter(struct ssh *ssh, Channel *c, const char *buf, 1421 int len) 1422 { 1423 if (c->extended_usage != CHAN_EXTENDED_WRITE) 1424 return 0; 1425 1426 return process_escapes(ssh, c, c->input, c->output, c->extended, 1427 buf, len); 1428 } 1429 1430 static void 1431 client_channel_closed(struct ssh *ssh, int id, int force, void *arg) 1432 { 1433 channel_cancel_cleanup(ssh, id); 1434 session_closed = 1; 1435 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1436 } 1437 1438 /* 1439 * Implements the interactive session with the server. This is called after 1440 * the user has been authenticated, and a command has been started on the 1441 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character 1442 * used as an escape character for terminating or suspending the session. 1443 */ 1444 int 1445 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg, 1446 int ssh2_chan_id) 1447 { 1448 struct pollfd *pfd = NULL; 1449 u_int npfd_alloc = 0, npfd_active = 0; 1450 double start_time, total_time; 1451 int channel_did_enqueue = 0, r; 1452 u_int64_t ibytes, obytes; 1453 int conn_in_ready, conn_out_ready; 1454 sigset_t bsigset, osigset; 1455 1456 debug("Entering interactive session."); 1457 session_ident = ssh2_chan_id; 1458 1459 #ifdef __OpenBSD__ 1460 if (options.control_master && 1461 !option_clear_or_none(options.control_path)) { 1462 debug("pledge: id"); 1463 if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty", 1464 NULL) == -1) 1465 fatal_f("pledge(): %s", strerror(errno)); 1466 1467 } else if (options.forward_x11 || options.permit_local_command) { 1468 debug("pledge: exec"); 1469 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty", 1470 NULL) == -1) 1471 fatal_f("pledge(): %s", strerror(errno)); 1472 1473 } else if (options.update_hostkeys) { 1474 debug("pledge: filesystem"); 1475 if (pledge("stdio rpath wpath cpath unix inet dns proc tty", 1476 NULL) == -1) 1477 fatal_f("pledge(): %s", strerror(errno)); 1478 1479 } else if (!option_clear_or_none(options.proxy_command) || 1480 options.fork_after_authentication) { 1481 debug("pledge: proc"); 1482 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1) 1483 fatal_f("pledge(): %s", strerror(errno)); 1484 1485 } else { 1486 debug("pledge: network"); 1487 if (pledge("stdio unix inet dns proc tty", NULL) == -1) 1488 fatal_f("pledge(): %s", strerror(errno)); 1489 } 1490 #endif 1491 1492 /* might be able to tighten now */ 1493 client_repledge(); 1494 1495 start_time = monotime_double(); 1496 1497 /* Initialize variables. */ 1498 last_was_cr = 1; 1499 exit_status = -1; 1500 connection_in = ssh_packet_get_connection_in(ssh); 1501 connection_out = ssh_packet_get_connection_out(ssh); 1502 1503 quit_pending = 0; 1504 1505 client_init_dispatch(ssh); 1506 1507 /* 1508 * Set signal handlers, (e.g. to restore non-blocking mode) 1509 * but don't overwrite SIG_IGN, matches behaviour from rsh(1) 1510 */ 1511 if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN) 1512 ssh_signal(SIGHUP, signal_handler); 1513 if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN) 1514 ssh_signal(SIGINT, signal_handler); 1515 if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN) 1516 ssh_signal(SIGQUIT, signal_handler); 1517 if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN) 1518 ssh_signal(SIGTERM, signal_handler); 1519 ssh_signal(SIGWINCH, window_change_handler); 1520 1521 if (have_pty) 1522 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1523 1524 if (session_ident != -1) { 1525 if (escape_char_arg != SSH_ESCAPECHAR_NONE) { 1526 channel_register_filter(ssh, session_ident, 1527 client_simple_escape_filter, NULL, 1528 client_filter_cleanup, 1529 client_new_escape_filter_ctx( 1530 escape_char_arg)); 1531 } 1532 channel_register_cleanup(ssh, session_ident, 1533 client_channel_closed, 0); 1534 } 1535 1536 schedule_server_alive_check(); 1537 1538 if (sigemptyset(&bsigset) == -1 || 1539 sigaddset(&bsigset, SIGHUP) == -1 || 1540 sigaddset(&bsigset, SIGINT) == -1 || 1541 sigaddset(&bsigset, SIGQUIT) == -1 || 1542 sigaddset(&bsigset, SIGTERM) == -1) 1543 error_f("bsigset setup: %s", strerror(errno)); 1544 1545 /* Main loop of the client for the interactive session mode. */ 1546 while (!quit_pending) { 1547 channel_did_enqueue = 0; 1548 1549 /* Process buffered packets sent by the server. */ 1550 client_process_buffered_input_packets(ssh); 1551 1552 if (session_closed && !channel_still_open(ssh)) 1553 break; 1554 1555 if (ssh_packet_is_rekeying(ssh)) { 1556 debug("rekeying in progress"); 1557 } else if (need_rekeying) { 1558 /* manual rekey request */ 1559 debug("need rekeying"); 1560 if ((r = kex_start_rekex(ssh)) != 0) 1561 fatal_fr(r, "kex_start_rekex"); 1562 need_rekeying = 0; 1563 } else { 1564 /* 1565 * Make packets from buffered channel data, and 1566 * enqueue them for sending to the server. 1567 */ 1568 if (ssh_packet_not_very_much_data_to_write(ssh)) 1569 channel_did_enqueue = channel_output_poll(ssh); 1570 1571 /* 1572 * Check if the window size has changed, and buffer a 1573 * message about it to the server if so. 1574 */ 1575 client_check_window_change(ssh); 1576 } 1577 /* 1578 * Wait until we have something to do (something becomes 1579 * available on one of the descriptors). 1580 */ 1581 if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1) 1582 error_f("bsigset sigprocmask: %s", strerror(errno)); 1583 if (quit_pending) 1584 break; 1585 client_wait_until_can_do_something(ssh, &pfd, &npfd_alloc, 1586 &npfd_active, channel_did_enqueue, &osigset, 1587 &conn_in_ready, &conn_out_ready); 1588 if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1) 1589 error_f("osigset sigprocmask: %s", strerror(errno)); 1590 1591 if (quit_pending) 1592 break; 1593 1594 /* Do channel operations. */ 1595 channel_after_poll(ssh, pfd, npfd_active); 1596 1597 /* Buffer input from the connection. */ 1598 if (conn_in_ready) 1599 client_process_net_input(ssh); 1600 1601 if (quit_pending) 1602 break; 1603 1604 /* A timeout may have triggered rekeying */ 1605 if ((r = ssh_packet_check_rekey(ssh)) != 0) 1606 fatal_fr(r, "cannot start rekeying"); 1607 1608 /* 1609 * Send as much buffered packet data as possible to the 1610 * sender. 1611 */ 1612 if (conn_out_ready) { 1613 if ((r = ssh_packet_write_poll(ssh)) < 0) { 1614 sshpkt_fatal(ssh, r, 1615 "%s: ssh_packet_write_poll", __func__); 1616 } 1617 } 1618 1619 /* 1620 * If we are a backgrounded control master, and the 1621 * timeout has expired without any active client 1622 * connections, then quit. 1623 */ 1624 if (control_persist_exit_time > 0) { 1625 if (monotime() >= control_persist_exit_time) { 1626 debug("ControlPersist timeout expired"); 1627 break; 1628 } 1629 } 1630 } 1631 free(pfd); 1632 1633 /* Terminate the session. */ 1634 1635 /* 1636 * In interactive mode (with pseudo tty) display a message indicating 1637 * that the connection has been closed. 1638 */ 1639 if (have_pty && options.log_level >= SYSLOG_LEVEL_INFO) 1640 quit_message("Connection to %s closed.", host); 1641 1642 1643 /* Stop watching for window change. */ 1644 ssh_signal(SIGWINCH, SIG_DFL); 1645 1646 if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 || 1647 (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 || 1648 (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 || 1649 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language tag */ 1650 (r = sshpkt_send(ssh)) != 0 || 1651 (r = ssh_packet_write_wait(ssh)) < 0) 1652 fatal_fr(r, "send disconnect"); 1653 1654 channel_free_all(ssh); 1655 1656 if (have_pty) 1657 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1658 1659 /* 1660 * If there was no shell or command requested, there will be no remote 1661 * exit status to be returned. In that case, clear error code if the 1662 * connection was deliberately terminated at this end. 1663 */ 1664 if (options.session_type == SESSION_TYPE_NONE && 1665 received_signal == SIGTERM) { 1666 received_signal = 0; 1667 exit_status = 0; 1668 } 1669 1670 if (received_signal) { 1671 verbose("Killed by signal %d.", (int) received_signal); 1672 cleanup_exit(255); 1673 } 1674 1675 /* Report bytes transferred, and transfer rates. */ 1676 total_time = monotime_double() - start_time; 1677 ssh_packet_get_bytes(ssh, &ibytes, &obytes); 1678 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds", 1679 (unsigned long long)obytes, (unsigned long long)ibytes, total_time); 1680 if (total_time > 0) 1681 verbose("Bytes per second: sent %.1f, received %.1f", 1682 obytes / total_time, ibytes / total_time); 1683 /* Return the exit status of the program. */ 1684 debug("Exit status %d", exit_status); 1685 return exit_status; 1686 } 1687 1688 /*********/ 1689 1690 static Channel * 1691 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type, 1692 int rchan, u_int rwindow, u_int rmaxpack) 1693 { 1694 Channel *c = NULL; 1695 struct sshbuf *b = NULL; 1696 char *listen_address, *originator_address; 1697 u_int listen_port, originator_port; 1698 int r; 1699 1700 /* Get rest of the packet */ 1701 if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 || 1702 (r = sshpkt_get_u32(ssh, &listen_port)) != 0 || 1703 (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 || 1704 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 || 1705 (r = sshpkt_get_end(ssh)) != 0) 1706 fatal_fr(r, "parse packet"); 1707 1708 debug_f("listen %s port %d, originator %s port %d", 1709 listen_address, listen_port, originator_address, originator_port); 1710 1711 if (listen_port > 0xffff) 1712 error_f("invalid listen port"); 1713 else if (originator_port > 0xffff) 1714 error_f("invalid originator port"); 1715 else { 1716 c = channel_connect_by_listen_address(ssh, 1717 listen_address, listen_port, "forwarded-tcpip", 1718 originator_address); 1719 } 1720 1721 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) { 1722 if ((b = sshbuf_new()) == NULL) { 1723 error_f("alloc reply"); 1724 goto out; 1725 } 1726 /* reconstruct and send to muxclient */ 1727 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */ 1728 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 || 1729 (r = sshbuf_put_cstring(b, request_type)) != 0 || 1730 (r = sshbuf_put_u32(b, rchan)) != 0 || 1731 (r = sshbuf_put_u32(b, rwindow)) != 0 || 1732 (r = sshbuf_put_u32(b, rmaxpack)) != 0 || 1733 (r = sshbuf_put_cstring(b, listen_address)) != 0 || 1734 (r = sshbuf_put_u32(b, listen_port)) != 0 || 1735 (r = sshbuf_put_cstring(b, originator_address)) != 0 || 1736 (r = sshbuf_put_u32(b, originator_port)) != 0 || 1737 (r = sshbuf_put_stringb(c->output, b)) != 0) { 1738 error_fr(r, "compose for muxclient"); 1739 goto out; 1740 } 1741 } 1742 1743 out: 1744 sshbuf_free(b); 1745 free(originator_address); 1746 free(listen_address); 1747 return c; 1748 } 1749 1750 static Channel * 1751 client_request_forwarded_streamlocal(struct ssh *ssh, 1752 const char *request_type, int rchan) 1753 { 1754 Channel *c = NULL; 1755 char *listen_path; 1756 int r; 1757 1758 /* Get the remote path. */ 1759 if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 || 1760 (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* reserved */ 1761 (r = sshpkt_get_end(ssh)) != 0) 1762 fatal_fr(r, "parse packet"); 1763 1764 debug_f("request: %s", listen_path); 1765 1766 c = channel_connect_by_listen_path(ssh, listen_path, 1767 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal"); 1768 free(listen_path); 1769 return c; 1770 } 1771 1772 static Channel * 1773 client_request_x11(struct ssh *ssh, const char *request_type, int rchan) 1774 { 1775 Channel *c = NULL; 1776 char *originator; 1777 u_int originator_port; 1778 int r, sock; 1779 1780 if (!options.forward_x11) { 1781 error("Warning: ssh server tried X11 forwarding."); 1782 error("Warning: this is probably a break-in attempt by a " 1783 "malicious server."); 1784 return NULL; 1785 } 1786 if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) { 1787 verbose("Rejected X11 connection after ForwardX11Timeout " 1788 "expired"); 1789 return NULL; 1790 } 1791 if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 || 1792 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 || 1793 (r = sshpkt_get_end(ssh)) != 0) 1794 fatal_fr(r, "parse packet"); 1795 /* XXX check permission */ 1796 /* XXX range check originator port? */ 1797 debug("client_request_x11: request from %s %u", originator, 1798 originator_port); 1799 free(originator); 1800 sock = x11_connect_display(ssh); 1801 if (sock < 0) 1802 return NULL; 1803 /* again is this really necessary for X11? */ 1804 if (options.hpn_disabled) 1805 c = channel_new(ssh, "x11-connection", 1806 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 1807 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1); 1808 else 1809 c = channel_new(ssh, "x11-connection", 1810 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 1811 options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1); 1812 c->force_drain = 1; 1813 return c; 1814 } 1815 1816 static Channel * 1817 client_request_agent(struct ssh *ssh, const char *request_type, int rchan) 1818 { 1819 Channel *c = NULL; 1820 int r, sock; 1821 1822 if (!options.forward_agent) { 1823 error("Warning: ssh server tried agent forwarding."); 1824 error("Warning: this is probably a break-in attempt by a " 1825 "malicious server."); 1826 return NULL; 1827 } 1828 if (forward_agent_sock_path == NULL) { 1829 r = ssh_get_authentication_socket(&sock); 1830 } else { 1831 r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock); 1832 } 1833 if (r != 0) { 1834 if (r != SSH_ERR_AGENT_NOT_PRESENT) 1835 debug_fr(r, "ssh_get_authentication_socket"); 1836 return NULL; 1837 } 1838 if ((r = ssh_agent_bind_hostkey(sock, ssh->kex->initial_hostkey, 1839 ssh->kex->session_id, ssh->kex->initial_sig, 1)) == 0) 1840 debug_f("bound agent to hostkey"); 1841 else 1842 debug2_fr(r, "ssh_agent_bind_hostkey"); 1843 1844 if (options.hpn_disabled) 1845 c = channel_new(ssh, "agent-connection", 1846 SSH_CHANNEL_OPEN, sock, sock, -1, 1847 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, 1848 "authentication agent connection", 1); 1849 else 1850 c = channel_new(ssh, "agent connection", 1851 SSH_CHANNEL_OPEN, sock, sock, -1, 1852 options.hpn_buffer_size, options.hpn_buffer_size, 0, 1853 "authentication agent connection", 1); 1854 c->force_drain = 1; 1855 return c; 1856 } 1857 1858 char * 1859 client_request_tun_fwd(struct ssh *ssh, int tun_mode, 1860 int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx) 1861 { 1862 Channel *c; 1863 int r, fd; 1864 char *ifname = NULL; 1865 1866 if (tun_mode == SSH_TUNMODE_NO) 1867 return 0; 1868 1869 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode); 1870 1871 /* Open local tunnel device */ 1872 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) { 1873 error("Tunnel device open failed."); 1874 return NULL; 1875 } 1876 debug("Tunnel forwarding using interface %s", ifname); 1877 1878 if(options.hpn_disabled) 1879 c = channel_new(ssh, "tun-connection", SSH_CHANNEL_OPENING, fd, fd, -1, 1880 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 1881 else 1882 c = channel_new(ssh, "tun-connection", SSH_CHANNEL_OPENING, fd, fd, -1, 1883 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 1884 c->datagram = 1; 1885 1886 if (cb != NULL) 1887 channel_register_open_confirm(ssh, c->self, cb, cbctx); 1888 1889 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 || 1890 (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 || 1891 (r = sshpkt_put_u32(ssh, c->self)) != 0 || 1892 (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 || 1893 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 || 1894 (r = sshpkt_put_u32(ssh, tun_mode)) != 0 || 1895 (r = sshpkt_put_u32(ssh, remote_tun)) != 0 || 1896 (r = sshpkt_send(ssh)) != 0) 1897 sshpkt_fatal(ssh, r, "%s: send reply", __func__); 1898 1899 return ifname; 1900 } 1901 1902 /* XXXX move to generic input handler */ 1903 static int 1904 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh) 1905 { 1906 Channel *c = NULL; 1907 char *ctype = NULL; 1908 int r; 1909 u_int rchan; 1910 size_t len; 1911 u_int rmaxpack, rwindow; 1912 1913 if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 || 1914 (r = sshpkt_get_u32(ssh, &rchan)) != 0 || 1915 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 || 1916 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0) 1917 goto out; 1918 1919 debug("client_input_channel_open: ctype %s rchan %d win %d max %d", 1920 ctype, rchan, rwindow, rmaxpack); 1921 1922 if (strcmp(ctype, "forwarded-tcpip") == 0) { 1923 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow, 1924 rmaxpack); 1925 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) { 1926 c = client_request_forwarded_streamlocal(ssh, ctype, rchan); 1927 } else if (strcmp(ctype, "x11") == 0) { 1928 c = client_request_x11(ssh, ctype, rchan); 1929 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) { 1930 c = client_request_agent(ssh, ctype, rchan); 1931 } 1932 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) { 1933 debug3("proxied to downstream: %s", ctype); 1934 } else if (c != NULL) { 1935 debug("confirm %s", ctype); 1936 c->remote_id = rchan; 1937 c->have_remote_id = 1; 1938 c->remote_window = rwindow; 1939 c->remote_maxpacket = rmaxpack; 1940 if (c->type != SSH_CHANNEL_CONNECTING) { 1941 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 || 1942 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 || 1943 (r = sshpkt_put_u32(ssh, c->self)) != 0 || 1944 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 || 1945 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 || 1946 (r = sshpkt_send(ssh)) != 0) 1947 sshpkt_fatal(ssh, r, "%s: send reply", __func__); 1948 } 1949 } else { 1950 debug("failure %s", ctype); 1951 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 || 1952 (r = sshpkt_put_u32(ssh, rchan)) != 0 || 1953 (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 || 1954 (r = sshpkt_put_cstring(ssh, "open failed")) != 0 || 1955 (r = sshpkt_put_cstring(ssh, "")) != 0 || 1956 (r = sshpkt_send(ssh)) != 0) 1957 sshpkt_fatal(ssh, r, "%s: send failure", __func__); 1958 } 1959 r = 0; 1960 out: 1961 free(ctype); 1962 return r; 1963 } 1964 1965 static int 1966 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh) 1967 { 1968 Channel *c = NULL; 1969 char *rtype = NULL; 1970 u_char reply; 1971 u_int id, exitval; 1972 int r, success = 0; 1973 1974 if ((r = sshpkt_get_u32(ssh, &id)) != 0) 1975 return r; 1976 if (id <= INT_MAX) 1977 c = channel_lookup(ssh, id); 1978 if (channel_proxy_upstream(c, type, seq, ssh)) 1979 return 0; 1980 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 || 1981 (r = sshpkt_get_u8(ssh, &reply)) != 0) 1982 goto out; 1983 1984 debug("client_input_channel_req: channel %u rtype %s reply %d", 1985 id, rtype, reply); 1986 1987 if (c == NULL) { 1988 error("client_input_channel_req: channel %d: " 1989 "unknown channel", id); 1990 } else if (strcmp(rtype, "eow@openssh.com") == 0) { 1991 if ((r = sshpkt_get_end(ssh)) != 0) 1992 goto out; 1993 chan_rcvd_eow(ssh, c); 1994 } else if (strcmp(rtype, "exit-status") == 0) { 1995 if ((r = sshpkt_get_u32(ssh, &exitval)) != 0) 1996 goto out; 1997 if (c->ctl_chan != -1) { 1998 mux_exit_message(ssh, c, exitval); 1999 success = 1; 2000 } else if ((int)id == session_ident) { 2001 /* Record exit value of local session */ 2002 success = 1; 2003 exit_status = exitval; 2004 } else { 2005 /* Probably for a mux channel that has already closed */ 2006 debug_f("no sink for exit-status on channel %d", 2007 id); 2008 } 2009 if ((r = sshpkt_get_end(ssh)) != 0) 2010 goto out; 2011 } 2012 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) { 2013 if (!c->have_remote_id) 2014 fatal_f("channel %d: no remote_id", c->self); 2015 if ((r = sshpkt_start(ssh, success ? 2016 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 || 2017 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 || 2018 (r = sshpkt_send(ssh)) != 0) 2019 sshpkt_fatal(ssh, r, "%s: send failure", __func__); 2020 } 2021 r = 0; 2022 out: 2023 free(rtype); 2024 return r; 2025 } 2026 2027 struct hostkeys_update_ctx { 2028 /* The hostname and (optionally) IP address string for the server */ 2029 char *host_str, *ip_str; 2030 2031 /* 2032 * Keys received from the server and a flag for each indicating 2033 * whether they already exist in known_hosts. 2034 * keys_match is filled in by hostkeys_find() and later (for new 2035 * keys) by client_global_hostkeys_prove_confirm(). 2036 */ 2037 struct sshkey **keys; 2038 u_int *keys_match; /* mask of HKF_MATCH_* from hostfile.h */ 2039 int *keys_verified; /* flag for new keys verified by server */ 2040 size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */ 2041 2042 /* 2043 * Keys that are in known_hosts, but were not present in the update 2044 * from the server (i.e. scheduled to be deleted). 2045 * Filled in by hostkeys_find(). 2046 */ 2047 struct sshkey **old_keys; 2048 size_t nold; 2049 2050 /* Various special cases. */ 2051 int complex_hostspec; /* wildcard or manual pattern-list host name */ 2052 int ca_available; /* saw CA key for this host */ 2053 int old_key_seen; /* saw old key with other name/addr */ 2054 int other_name_seen; /* saw key with other name/addr */ 2055 }; 2056 2057 static void 2058 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx) 2059 { 2060 size_t i; 2061 2062 if (ctx == NULL) 2063 return; 2064 for (i = 0; i < ctx->nkeys; i++) 2065 sshkey_free(ctx->keys[i]); 2066 free(ctx->keys); 2067 free(ctx->keys_match); 2068 free(ctx->keys_verified); 2069 for (i = 0; i < ctx->nold; i++) 2070 sshkey_free(ctx->old_keys[i]); 2071 free(ctx->old_keys); 2072 free(ctx->host_str); 2073 free(ctx->ip_str); 2074 free(ctx); 2075 } 2076 2077 /* 2078 * Returns non-zero if a known_hosts hostname list is not of a form that 2079 * can be handled by UpdateHostkeys. These include wildcard hostnames and 2080 * hostnames lists that do not follow the form host[,ip]. 2081 */ 2082 static int 2083 hostspec_is_complex(const char *hosts) 2084 { 2085 char *cp; 2086 2087 /* wildcard */ 2088 if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL) 2089 return 1; 2090 /* single host/ip = ok */ 2091 if ((cp = strchr(hosts, ',')) == NULL) 2092 return 0; 2093 /* more than two entries on the line */ 2094 if (strchr(cp + 1, ',') != NULL) 2095 return 1; 2096 /* XXX maybe parse cp+1 and ensure it is an IP? */ 2097 return 0; 2098 } 2099 2100 /* callback to search for ctx->keys in known_hosts */ 2101 static int 2102 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx) 2103 { 2104 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx; 2105 size_t i; 2106 struct sshkey **tmp; 2107 2108 if (l->key == NULL) 2109 return 0; 2110 if (l->status != HKF_STATUS_MATCHED) { 2111 /* Record if one of the keys appears on a non-matching line */ 2112 for (i = 0; i < ctx->nkeys; i++) { 2113 if (sshkey_equal(l->key, ctx->keys[i])) { 2114 ctx->other_name_seen = 1; 2115 debug3_f("found %s key under different " 2116 "name/addr at %s:%ld", 2117 sshkey_ssh_name(ctx->keys[i]), 2118 l->path, l->linenum); 2119 return 0; 2120 } 2121 } 2122 return 0; 2123 } 2124 /* Don't proceed if revocation or CA markers are present */ 2125 /* XXX relax this */ 2126 if (l->marker != MRK_NONE) { 2127 debug3_f("hostkeys file %s:%ld has CA/revocation marker", 2128 l->path, l->linenum); 2129 ctx->complex_hostspec = 1; 2130 return 0; 2131 } 2132 2133 /* If CheckHostIP is enabled, then check for mismatched hostname/addr */ 2134 if (ctx->ip_str != NULL && strchr(l->hosts, ',') != NULL) { 2135 if ((l->match & HKF_MATCH_HOST) == 0) { 2136 /* Record if address matched a different hostname. */ 2137 ctx->other_name_seen = 1; 2138 debug3_f("found address %s against different hostname " 2139 "at %s:%ld", ctx->ip_str, l->path, l->linenum); 2140 return 0; 2141 } else if ((l->match & HKF_MATCH_IP) == 0) { 2142 /* Record if hostname matched a different address. */ 2143 ctx->other_name_seen = 1; 2144 debug3_f("found hostname %s against different address " 2145 "at %s:%ld", ctx->host_str, l->path, l->linenum); 2146 } 2147 } 2148 2149 /* 2150 * UpdateHostkeys is skipped for wildcard host names and hostnames 2151 * that contain more than two entries (ssh never writes these). 2152 */ 2153 if (hostspec_is_complex(l->hosts)) { 2154 debug3_f("hostkeys file %s:%ld complex host specification", 2155 l->path, l->linenum); 2156 ctx->complex_hostspec = 1; 2157 return 0; 2158 } 2159 2160 /* Mark off keys we've already seen for this host */ 2161 for (i = 0; i < ctx->nkeys; i++) { 2162 if (!sshkey_equal(l->key, ctx->keys[i])) 2163 continue; 2164 debug3_f("found %s key at %s:%ld", 2165 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum); 2166 ctx->keys_match[i] |= l->match; 2167 return 0; 2168 } 2169 /* This line contained a key that not offered by the server */ 2170 debug3_f("deprecated %s key at %s:%ld", sshkey_ssh_name(l->key), 2171 l->path, l->linenum); 2172 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1, 2173 sizeof(*ctx->old_keys))) == NULL) 2174 fatal_f("recallocarray failed nold = %zu", ctx->nold); 2175 ctx->old_keys = tmp; 2176 ctx->old_keys[ctx->nold++] = l->key; 2177 l->key = NULL; 2178 2179 return 0; 2180 } 2181 2182 /* callback to search for ctx->old_keys in known_hosts under other names */ 2183 static int 2184 hostkeys_check_old(struct hostkey_foreach_line *l, void *_ctx) 2185 { 2186 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx; 2187 size_t i; 2188 int hashed; 2189 2190 /* only care about lines that *don't* match the active host spec */ 2191 if (l->status == HKF_STATUS_MATCHED || l->key == NULL) 2192 return 0; 2193 2194 hashed = l->match & (HKF_MATCH_HOST_HASHED|HKF_MATCH_IP_HASHED); 2195 for (i = 0; i < ctx->nold; i++) { 2196 if (!sshkey_equal(l->key, ctx->old_keys[i])) 2197 continue; 2198 debug3_f("found deprecated %s key at %s:%ld as %s", 2199 sshkey_ssh_name(ctx->old_keys[i]), l->path, l->linenum, 2200 hashed ? "[HASHED]" : l->hosts); 2201 ctx->old_key_seen = 1; 2202 break; 2203 } 2204 return 0; 2205 } 2206 2207 /* 2208 * Check known_hosts files for deprecated keys under other names. Returns 0 2209 * on success or -1 on failure. Updates ctx->old_key_seen if deprecated keys 2210 * exist under names other than the active hostname/IP. 2211 */ 2212 static int 2213 check_old_keys_othernames(struct hostkeys_update_ctx *ctx) 2214 { 2215 size_t i; 2216 int r; 2217 2218 debug2_f("checking for %zu deprecated keys", ctx->nold); 2219 for (i = 0; i < options.num_user_hostfiles; i++) { 2220 debug3_f("searching %s for %s / %s", 2221 options.user_hostfiles[i], ctx->host_str, 2222 ctx->ip_str ? ctx->ip_str : "(none)"); 2223 if ((r = hostkeys_foreach(options.user_hostfiles[i], 2224 hostkeys_check_old, ctx, ctx->host_str, ctx->ip_str, 2225 HKF_WANT_PARSE_KEY, 0)) != 0) { 2226 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) { 2227 debug_f("hostkeys file %s does not exist", 2228 options.user_hostfiles[i]); 2229 continue; 2230 } 2231 error_fr(r, "hostkeys_foreach failed for %s", 2232 options.user_hostfiles[i]); 2233 return -1; 2234 } 2235 } 2236 return 0; 2237 } 2238 2239 static void 2240 hostkey_change_preamble(LogLevel loglevel) 2241 { 2242 do_log2(loglevel, "The server has updated its host keys."); 2243 do_log2(loglevel, "These changes were verified by the server's " 2244 "existing trusted key."); 2245 } 2246 2247 static void 2248 update_known_hosts(struct hostkeys_update_ctx *ctx) 2249 { 2250 int r, was_raw = 0, first = 1; 2251 int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK; 2252 LogLevel loglevel = asking ? SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE; 2253 char *fp, *response; 2254 size_t i; 2255 struct stat sb; 2256 2257 for (i = 0; i < ctx->nkeys; i++) { 2258 if (!ctx->keys_verified[i]) 2259 continue; 2260 if ((fp = sshkey_fingerprint(ctx->keys[i], 2261 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 2262 fatal_f("sshkey_fingerprint failed"); 2263 if (first && asking) 2264 hostkey_change_preamble(loglevel); 2265 do_log2(loglevel, "Learned new hostkey: %s %s", 2266 sshkey_type(ctx->keys[i]), fp); 2267 first = 0; 2268 free(fp); 2269 } 2270 for (i = 0; i < ctx->nold; i++) { 2271 if ((fp = sshkey_fingerprint(ctx->old_keys[i], 2272 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 2273 fatal_f("sshkey_fingerprint failed"); 2274 if (first && asking) 2275 hostkey_change_preamble(loglevel); 2276 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s", 2277 sshkey_type(ctx->old_keys[i]), fp); 2278 first = 0; 2279 free(fp); 2280 } 2281 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) { 2282 if (get_saved_tio() != NULL) { 2283 leave_raw_mode(1); 2284 was_raw = 1; 2285 } 2286 response = NULL; 2287 for (i = 0; !quit_pending && i < 3; i++) { 2288 free(response); 2289 response = read_passphrase("Accept updated hostkeys? " 2290 "(yes/no): ", RP_ECHO); 2291 if (response != NULL && strcasecmp(response, "yes") == 0) 2292 break; 2293 else if (quit_pending || response == NULL || 2294 strcasecmp(response, "no") == 0) { 2295 options.update_hostkeys = 0; 2296 break; 2297 } else { 2298 do_log2(loglevel, "Please enter " 2299 "\"yes\" or \"no\""); 2300 } 2301 } 2302 if (quit_pending || i >= 3 || response == NULL) 2303 options.update_hostkeys = 0; 2304 free(response); 2305 if (was_raw) 2306 enter_raw_mode(1); 2307 } 2308 if (options.update_hostkeys == 0) 2309 return; 2310 /* 2311 * Now that all the keys are verified, we can go ahead and replace 2312 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't 2313 * cancel the operation). 2314 */ 2315 for (i = 0; i < options.num_user_hostfiles; i++) { 2316 /* 2317 * NB. keys are only added to hostfiles[0], for the rest we 2318 * just delete the hostname entries. 2319 */ 2320 if (stat(options.user_hostfiles[i], &sb) != 0) { 2321 if (errno == ENOENT) { 2322 debug_f("known hosts file %s does not " 2323 "exist", options.user_hostfiles[i]); 2324 } else { 2325 error_f("known hosts file %s " 2326 "inaccessible: %s", 2327 options.user_hostfiles[i], strerror(errno)); 2328 } 2329 continue; 2330 } 2331 if ((r = hostfile_replace_entries(options.user_hostfiles[i], 2332 ctx->host_str, ctx->ip_str, 2333 i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0, 2334 options.hash_known_hosts, 0, 2335 options.fingerprint_hash)) != 0) { 2336 error_fr(r, "hostfile_replace_entries failed for %s", 2337 options.user_hostfiles[i]); 2338 } 2339 } 2340 } 2341 2342 static void 2343 client_global_hostkeys_prove_confirm(struct ssh *ssh, int type, 2344 u_int32_t seq, void *_ctx) 2345 { 2346 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx; 2347 size_t i, ndone; 2348 struct sshbuf *signdata; 2349 int r, plaintype; 2350 const u_char *sig; 2351 const char *rsa_kexalg = NULL; 2352 char *alg = NULL; 2353 size_t siglen; 2354 2355 if (ctx->nnew == 0) 2356 fatal_f("ctx->nnew == 0"); /* sanity */ 2357 if (type != SSH2_MSG_REQUEST_SUCCESS) { 2358 error("Server failed to confirm ownership of " 2359 "private host keys"); 2360 hostkeys_update_ctx_free(ctx); 2361 return; 2362 } 2363 if (sshkey_type_plain(sshkey_type_from_name( 2364 ssh->kex->hostkey_alg)) == KEY_RSA) 2365 rsa_kexalg = ssh->kex->hostkey_alg; 2366 if ((signdata = sshbuf_new()) == NULL) 2367 fatal_f("sshbuf_new failed"); 2368 /* 2369 * Expect a signature for each of the ctx->nnew private keys we 2370 * haven't seen before. They will be in the same order as the 2371 * ctx->keys where the corresponding ctx->keys_match[i] == 0. 2372 */ 2373 for (ndone = i = 0; i < ctx->nkeys; i++) { 2374 if (ctx->keys_match[i]) 2375 continue; 2376 plaintype = sshkey_type_plain(ctx->keys[i]->type); 2377 /* Prepare data to be signed: session ID, unique string, key */ 2378 sshbuf_reset(signdata); 2379 if ( (r = sshbuf_put_cstring(signdata, 2380 "hostkeys-prove-00@openssh.com")) != 0 || 2381 (r = sshbuf_put_stringb(signdata, 2382 ssh->kex->session_id)) != 0 || 2383 (r = sshkey_puts(ctx->keys[i], signdata)) != 0) 2384 fatal_fr(r, "compose signdata"); 2385 /* Extract and verify signature */ 2386 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) { 2387 error_fr(r, "parse sig"); 2388 goto out; 2389 } 2390 if ((r = sshkey_get_sigtype(sig, siglen, &alg)) != 0) { 2391 error_fr(r, "server gave unintelligible signature " 2392 "for %s key %zu", sshkey_type(ctx->keys[i]), i); 2393 goto out; 2394 } 2395 /* 2396 * Special case for RSA keys: if a RSA hostkey was negotiated, 2397 * then use its signature type for verification of RSA hostkey 2398 * proofs. Otherwise, accept only RSA-SHA256/512 signatures. 2399 */ 2400 if (plaintype == KEY_RSA && rsa_kexalg == NULL && 2401 match_pattern_list(alg, HOSTKEY_PROOF_RSA_ALGS, 0) != 1) { 2402 debug_f("server used untrusted RSA signature algorithm " 2403 "%s for key %zu, disregarding", alg, i); 2404 free(alg); 2405 /* zap the key from the list */ 2406 sshkey_free(ctx->keys[i]); 2407 ctx->keys[i] = NULL; 2408 ndone++; 2409 continue; 2410 } 2411 debug3_f("verify %s key %zu using sigalg %s", 2412 sshkey_type(ctx->keys[i]), i, alg); 2413 free(alg); 2414 if ((r = sshkey_verify(ctx->keys[i], sig, siglen, 2415 sshbuf_ptr(signdata), sshbuf_len(signdata), 2416 plaintype == KEY_RSA ? rsa_kexalg : NULL, 0, NULL)) != 0) { 2417 error_fr(r, "server gave bad signature for %s key %zu", 2418 sshkey_type(ctx->keys[i]), i); 2419 goto out; 2420 } 2421 /* Key is good. Mark it as 'seen' */ 2422 ctx->keys_verified[i] = 1; 2423 ndone++; 2424 } 2425 /* Shouldn't happen */ 2426 if (ndone != ctx->nnew) 2427 fatal_f("ndone != ctx->nnew (%zu / %zu)", ndone, ctx->nnew); 2428 if ((r = sshpkt_get_end(ssh)) != 0) { 2429 error_f("protocol error"); 2430 goto out; 2431 } 2432 2433 /* Make the edits to known_hosts */ 2434 update_known_hosts(ctx); 2435 out: 2436 hostkeys_update_ctx_free(ctx); 2437 hostkeys_update_complete = 1; 2438 client_repledge(); 2439 } 2440 2441 /* 2442 * Handle hostkeys-00@openssh.com global request to inform the client of all 2443 * the server's hostkeys. The keys are checked against the user's 2444 * HostkeyAlgorithms preference before they are accepted. 2445 */ 2446 static int 2447 client_input_hostkeys(struct ssh *ssh) 2448 { 2449 const u_char *blob = NULL; 2450 size_t i, len = 0; 2451 struct sshbuf *buf = NULL; 2452 struct sshkey *key = NULL, **tmp; 2453 int r, prove_sent = 0; 2454 char *fp; 2455 static int hostkeys_seen = 0; /* XXX use struct ssh */ 2456 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */ 2457 struct hostkeys_update_ctx *ctx = NULL; 2458 u_int want; 2459 2460 if (hostkeys_seen) 2461 fatal_f("server already sent hostkeys"); 2462 if (!can_update_hostkeys()) 2463 return 1; 2464 hostkeys_seen = 1; 2465 2466 ctx = xcalloc(1, sizeof(*ctx)); 2467 while (ssh_packet_remaining(ssh) > 0) { 2468 sshkey_free(key); 2469 key = NULL; 2470 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) { 2471 error_fr(r, "parse key"); 2472 goto out; 2473 } 2474 if ((r = sshkey_from_blob(blob, len, &key)) != 0) { 2475 do_log2_fr(r, r == SSH_ERR_KEY_TYPE_UNKNOWN ? 2476 SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR, 2477 "convert key"); 2478 continue; 2479 } 2480 fp = sshkey_fingerprint(key, options.fingerprint_hash, 2481 SSH_FP_DEFAULT); 2482 debug3_f("received %s key %s", sshkey_type(key), fp); 2483 free(fp); 2484 2485 if (!hostkey_accepted_by_hostkeyalgs(key)) { 2486 debug3_f("%s key not permitted by " 2487 "HostkeyAlgorithms", sshkey_ssh_name(key)); 2488 continue; 2489 } 2490 /* Skip certs */ 2491 if (sshkey_is_cert(key)) { 2492 debug3_f("%s key is a certificate; skipping", 2493 sshkey_ssh_name(key)); 2494 continue; 2495 } 2496 /* Ensure keys are unique */ 2497 for (i = 0; i < ctx->nkeys; i++) { 2498 if (sshkey_equal(key, ctx->keys[i])) { 2499 error_f("received duplicated %s host key", 2500 sshkey_ssh_name(key)); 2501 goto out; 2502 } 2503 } 2504 /* Key is good, record it */ 2505 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1, 2506 sizeof(*ctx->keys))) == NULL) 2507 fatal_f("recallocarray failed nkeys = %zu", 2508 ctx->nkeys); 2509 ctx->keys = tmp; 2510 ctx->keys[ctx->nkeys++] = key; 2511 key = NULL; 2512 } 2513 2514 if (ctx->nkeys == 0) { 2515 debug_f("server sent no hostkeys"); 2516 goto out; 2517 } 2518 2519 if ((ctx->keys_match = calloc(ctx->nkeys, 2520 sizeof(*ctx->keys_match))) == NULL || 2521 (ctx->keys_verified = calloc(ctx->nkeys, 2522 sizeof(*ctx->keys_verified))) == NULL) 2523 fatal_f("calloc failed"); 2524 2525 get_hostfile_hostname_ipaddr(host, 2526 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL, 2527 options.port, &ctx->host_str, 2528 options.check_host_ip ? &ctx->ip_str : NULL); 2529 2530 /* Find which keys we already know about. */ 2531 for (i = 0; i < options.num_user_hostfiles; i++) { 2532 debug_f("searching %s for %s / %s", 2533 options.user_hostfiles[i], ctx->host_str, 2534 ctx->ip_str ? ctx->ip_str : "(none)"); 2535 if ((r = hostkeys_foreach(options.user_hostfiles[i], 2536 hostkeys_find, ctx, ctx->host_str, ctx->ip_str, 2537 HKF_WANT_PARSE_KEY, 0)) != 0) { 2538 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) { 2539 debug_f("hostkeys file %s does not exist", 2540 options.user_hostfiles[i]); 2541 continue; 2542 } 2543 error_fr(r, "hostkeys_foreach failed for %s", 2544 options.user_hostfiles[i]); 2545 goto out; 2546 } 2547 } 2548 2549 /* Figure out if we have any new keys to add */ 2550 ctx->nnew = ctx->nincomplete = 0; 2551 want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0); 2552 for (i = 0; i < ctx->nkeys; i++) { 2553 if (ctx->keys_match[i] == 0) 2554 ctx->nnew++; 2555 if ((ctx->keys_match[i] & want) != want) 2556 ctx->nincomplete++; 2557 } 2558 2559 debug3_f("%zu server keys: %zu new, %zu retained, " 2560 "%zu incomplete match. %zu to remove", ctx->nkeys, ctx->nnew, 2561 ctx->nkeys - ctx->nnew - ctx->nincomplete, 2562 ctx->nincomplete, ctx->nold); 2563 2564 if (ctx->nnew == 0 && ctx->nold == 0) { 2565 debug_f("no new or deprecated keys from server"); 2566 goto out; 2567 } 2568 2569 /* Various reasons why we cannot proceed with the update */ 2570 if (ctx->complex_hostspec) { 2571 debug_f("CA/revocation marker, manual host list or wildcard " 2572 "host pattern found, skipping UserKnownHostsFile update"); 2573 goto out; 2574 } 2575 if (ctx->other_name_seen) { 2576 debug_f("host key found matching a different name/address, " 2577 "skipping UserKnownHostsFile update"); 2578 goto out; 2579 } 2580 /* 2581 * If removing keys, check whether they appear under different 2582 * names/addresses and refuse to proceed if they do. This avoids 2583 * cases such as hosts with multiple names becoming inconsistent 2584 * with regards to CheckHostIP entries. 2585 * XXX UpdateHostkeys=force to override this (and other) checks? 2586 */ 2587 if (ctx->nold != 0) { 2588 if (check_old_keys_othernames(ctx) != 0) 2589 goto out; /* error already logged */ 2590 if (ctx->old_key_seen) { 2591 debug_f("key(s) for %s%s%s exist under other names; " 2592 "skipping UserKnownHostsFile update", 2593 ctx->host_str, ctx->ip_str == NULL ? "" : ",", 2594 ctx->ip_str == NULL ? "" : ctx->ip_str); 2595 goto out; 2596 } 2597 } 2598 2599 if (ctx->nnew == 0) { 2600 /* 2601 * We have some keys to remove or fix matching for. 2602 * We can proceed to do this without requiring a fresh proof 2603 * from the server. 2604 */ 2605 update_known_hosts(ctx); 2606 goto out; 2607 } 2608 /* 2609 * We have received previously-unseen keys from the server. 2610 * Ask the server to confirm ownership of the private halves. 2611 */ 2612 debug3_f("asking server to prove ownership for %zu keys", ctx->nnew); 2613 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 2614 (r = sshpkt_put_cstring(ssh, 2615 "hostkeys-prove-00@openssh.com")) != 0 || 2616 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */ 2617 fatal_fr(r, "prepare hostkeys-prove"); 2618 if ((buf = sshbuf_new()) == NULL) 2619 fatal_f("sshbuf_new"); 2620 for (i = 0; i < ctx->nkeys; i++) { 2621 if (ctx->keys_match[i]) 2622 continue; 2623 sshbuf_reset(buf); 2624 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0 || 2625 (r = sshpkt_put_stringb(ssh, buf)) != 0) 2626 fatal_fr(r, "assemble hostkeys-prove"); 2627 } 2628 if ((r = sshpkt_send(ssh)) != 0) 2629 fatal_fr(r, "send hostkeys-prove"); 2630 client_register_global_confirm( 2631 client_global_hostkeys_prove_confirm, ctx); 2632 ctx = NULL; /* will be freed in callback */ 2633 prove_sent = 1; 2634 2635 /* Success */ 2636 out: 2637 hostkeys_update_ctx_free(ctx); 2638 sshkey_free(key); 2639 sshbuf_free(buf); 2640 if (!prove_sent) { 2641 /* UpdateHostkeys handling completed */ 2642 hostkeys_update_complete = 1; 2643 client_repledge(); 2644 } 2645 /* 2646 * NB. Return success for all cases. The server doesn't need to know 2647 * what the client does with its hosts file. 2648 */ 2649 return 1; 2650 } 2651 2652 static int 2653 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh) 2654 { 2655 char *rtype; 2656 u_char want_reply; 2657 int r, success = 0; 2658 2659 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 || 2660 (r = sshpkt_get_u8(ssh, &want_reply)) != 0) 2661 goto out; 2662 debug("client_input_global_request: rtype %s want_reply %d", 2663 rtype, want_reply); 2664 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0) 2665 success = client_input_hostkeys(ssh); 2666 if (want_reply) { 2667 if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS : 2668 SSH2_MSG_REQUEST_FAILURE)) != 0 || 2669 (r = sshpkt_send(ssh)) != 0 || 2670 (r = ssh_packet_write_wait(ssh)) != 0) 2671 goto out; 2672 } 2673 r = 0; 2674 out: 2675 free(rtype); 2676 return r; 2677 } 2678 2679 static void 2680 client_send_env(struct ssh *ssh, int id, const char *name, const char *val) 2681 { 2682 int r; 2683 2684 debug("channel %d: setting env %s = \"%s\"", id, name, val); 2685 channel_request_start(ssh, id, "env", 0); 2686 if ((r = sshpkt_put_cstring(ssh, name)) != 0 || 2687 (r = sshpkt_put_cstring(ssh, val)) != 0 || 2688 (r = sshpkt_send(ssh)) != 0) 2689 fatal_fr(r, "send setenv"); 2690 } 2691 2692 void 2693 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem, 2694 const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd, 2695 char **env) 2696 { 2697 size_t i, j, len; 2698 int matched, r; 2699 char *name, *val; 2700 Channel *c = NULL; 2701 2702 debug2_f("id %d", id); 2703 2704 if ((c = channel_lookup(ssh, id)) == NULL) 2705 fatal_f("channel %d: unknown channel", id); 2706 2707 ssh_packet_set_interactive(ssh, want_tty, 2708 options.ip_qos_interactive, options.ip_qos_bulk); 2709 2710 if (want_tty) { 2711 struct winsize ws; 2712 2713 /* Store window size in the packet. */ 2714 if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1) 2715 memset(&ws, 0, sizeof(ws)); 2716 2717 channel_request_start(ssh, id, "pty-req", 1); 2718 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY); 2719 if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : "")) 2720 != 0 || 2721 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 || 2722 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 || 2723 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 || 2724 (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0) 2725 fatal_fr(r, "build pty-req"); 2726 if (tiop == NULL) 2727 tiop = get_saved_tio(); 2728 ssh_tty_make_modes(ssh, -1, tiop); 2729 if ((r = sshpkt_send(ssh)) != 0) 2730 fatal_fr(r, "send pty-req"); 2731 /* XXX wait for reply */ 2732 c->client_tty = 1; 2733 } 2734 2735 /* Transfer any environment variables from client to server */ 2736 if (options.num_send_env != 0 && env != NULL) { 2737 debug("Sending environment."); 2738 for (i = 0; env[i] != NULL; i++) { 2739 /* Split */ 2740 name = xstrdup(env[i]); 2741 if ((val = strchr(name, '=')) == NULL) { 2742 free(name); 2743 continue; 2744 } 2745 *val++ = '\0'; 2746 2747 matched = 0; 2748 for (j = 0; j < options.num_send_env; j++) { 2749 if (match_pattern(name, options.send_env[j])) { 2750 matched = 1; 2751 break; 2752 } 2753 } 2754 if (!matched) { 2755 debug3("Ignored env %s", name); 2756 free(name); 2757 continue; 2758 } 2759 client_send_env(ssh, id, name, val); 2760 free(name); 2761 } 2762 } 2763 for (i = 0; i < options.num_setenv; i++) { 2764 /* Split */ 2765 name = xstrdup(options.setenv[i]); 2766 if ((val = strchr(name, '=')) == NULL) { 2767 free(name); 2768 continue; 2769 } 2770 *val++ = '\0'; 2771 client_send_env(ssh, id, name, val); 2772 free(name); 2773 } 2774 2775 len = sshbuf_len(cmd); 2776 if (len > 0) { 2777 if (len > 900) 2778 len = 900; 2779 if (want_subsystem) { 2780 debug("Sending subsystem: %.*s", 2781 (int)len, (const u_char*)sshbuf_ptr(cmd)); 2782 channel_request_start(ssh, id, "subsystem", 1); 2783 client_expect_confirm(ssh, id, "subsystem", 2784 CONFIRM_CLOSE); 2785 } else { 2786 debug("Sending command: %.*s", 2787 (int)len, (const u_char*)sshbuf_ptr(cmd)); 2788 channel_request_start(ssh, id, "exec", 1); 2789 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE); 2790 } 2791 if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 || 2792 (r = sshpkt_send(ssh)) != 0) 2793 fatal_fr(r, "send command"); 2794 } else { 2795 channel_request_start(ssh, id, "shell", 1); 2796 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE); 2797 if ((r = sshpkt_send(ssh)) != 0) 2798 fatal_fr(r, "send shell"); 2799 } 2800 2801 session_setup_complete = 1; 2802 client_repledge(); 2803 } 2804 2805 static void 2806 client_init_dispatch(struct ssh *ssh) 2807 { 2808 ssh_dispatch_init(ssh, &dispatch_protocol_error); 2809 2810 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 2811 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data); 2812 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof); 2813 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data); 2814 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open); 2815 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 2816 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 2817 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req); 2818 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust); 2819 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm); 2820 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm); 2821 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request); 2822 2823 /* rekeying */ 2824 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit); 2825 2826 /* global request reply messages */ 2827 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply); 2828 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply); 2829 } 2830 2831 void 2832 client_stop_mux(void) 2833 { 2834 if (options.control_path != NULL && muxserver_sock != -1) 2835 unlink(options.control_path); 2836 /* 2837 * If we are in persist mode, or don't have a shell, signal that we 2838 * should close when all active channels are closed. 2839 */ 2840 if (options.control_persist || options.session_type == SESSION_TYPE_NONE) { 2841 session_closed = 1; 2842 setproctitle("[stopped mux]"); 2843 } 2844 } 2845 2846 /* client specific fatal cleanup */ 2847 void 2848 cleanup_exit(int i) 2849 { 2850 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 2851 if (options.control_path != NULL && muxserver_sock != -1) 2852 unlink(options.control_path); 2853 ssh_kill_proxy_command(); 2854 _exit(i); 2855 } 2856