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