1 /* $OpenBSD: clientloop.c,v 1.310 2018/01/23 05:27:21 djm 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 <signal.h> 74 #include <stdio.h> 75 #include <stdlib.h> 76 #include <string.h> 77 #include <termios.h> 78 #include <pwd.h> 79 #include <unistd.h> 80 #include <limits.h> 81 82 #include "xmalloc.h" 83 #include "ssh.h" 84 #include "ssh2.h" 85 #include "packet.h" 86 #include "buffer.h" 87 #include "compat.h" 88 #include "channels.h" 89 #include "dispatch.h" 90 #include "key.h" 91 #include "cipher.h" 92 #include "kex.h" 93 #include "myproposal.h" 94 #include "log.h" 95 #include "misc.h" 96 #include "readconf.h" 97 #include "clientloop.h" 98 #include "sshconnect.h" 99 #include "authfd.h" 100 #include "atomicio.h" 101 #include "sshpty.h" 102 #include "match.h" 103 #include "msg.h" 104 #include "ssherr.h" 105 #include "hostfile.h" 106 107 /* import options */ 108 extern Options options; 109 110 /* Flag indicating that stdin should be redirected from /dev/null. */ 111 extern int stdin_null_flag; 112 113 /* Flag indicating that no shell has been requested */ 114 extern int no_shell_flag; 115 116 /* Flag indicating that ssh should daemonise after authentication is complete */ 117 extern int fork_after_authentication_flag; 118 119 /* Control socket */ 120 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */ 121 122 /* 123 * Name of the host we are connecting to. This is the name given on the 124 * command line, or the HostName specified for the user-supplied name in a 125 * configuration file. 126 */ 127 extern char *host; 128 129 /* 130 * Flag to indicate that we have received a window change signal which has 131 * not yet been processed. This will cause a message indicating the new 132 * window size to be sent to the server a little later. This is volatile 133 * because this is updated in a signal handler. 134 */ 135 static volatile sig_atomic_t received_window_change_signal = 0; 136 static volatile sig_atomic_t received_signal = 0; 137 138 /* Flag indicating whether the user's terminal is in non-blocking mode. */ 139 static int in_non_blocking_mode = 0; 140 141 /* Time when backgrounded control master using ControlPersist should exit */ 142 static time_t control_persist_exit_time = 0; 143 144 /* Common data for the client loop code. */ 145 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */ 146 static int last_was_cr; /* Last character was a newline. */ 147 static int exit_status; /* Used to store the command exit status. */ 148 static Buffer stderr_buffer; /* Used for final exit message. */ 149 static int connection_in; /* Connection to server (input). */ 150 static int connection_out; /* Connection to server (output). */ 151 static int need_rekeying; /* Set to non-zero if rekeying is requested. */ 152 static int session_closed; /* In SSH2: login session closed. */ 153 static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */ 154 155 static void client_init_dispatch(void); 156 int session_ident = -1; 157 158 /* Track escape per proto2 channel */ 159 struct escape_filter_ctx { 160 int escape_pending; 161 int escape_char; 162 }; 163 164 /* Context for channel confirmation replies */ 165 struct channel_reply_ctx { 166 const char *request_type; 167 int id; 168 enum confirm_action action; 169 }; 170 171 /* Global request success/failure callbacks */ 172 /* XXX move to struct ssh? */ 173 struct global_confirm { 174 TAILQ_ENTRY(global_confirm) entry; 175 global_confirm_cb *cb; 176 void *ctx; 177 int ref_count; 178 }; 179 TAILQ_HEAD(global_confirms, global_confirm); 180 static struct global_confirms global_confirms = 181 TAILQ_HEAD_INITIALIZER(global_confirms); 182 183 void ssh_process_session2_setup(int, int, int, Buffer *); 184 185 /* Restores stdin to blocking mode. */ 186 187 static void 188 leave_non_blocking(void) 189 { 190 if (in_non_blocking_mode) { 191 unset_nonblock(fileno(stdin)); 192 in_non_blocking_mode = 0; 193 } 194 } 195 196 /* 197 * Signal handler for the window change signal (SIGWINCH). This just sets a 198 * flag indicating that the window has changed. 199 */ 200 /*ARGSUSED */ 201 static void 202 window_change_handler(int sig) 203 { 204 received_window_change_signal = 1; 205 signal(SIGWINCH, window_change_handler); 206 } 207 208 /* 209 * Signal handler for signals that cause the program to terminate. These 210 * signals must be trapped to restore terminal modes. 211 */ 212 /*ARGSUSED */ 213 static void 214 signal_handler(int sig) 215 { 216 received_signal = sig; 217 quit_pending = 1; 218 } 219 220 /* 221 * Sets control_persist_exit_time to the absolute time when the 222 * backgrounded control master should exit due to expiry of the 223 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded 224 * control master process, or if there is no ControlPersist timeout. 225 */ 226 static void 227 set_control_persist_exit_time(struct ssh *ssh) 228 { 229 if (muxserver_sock == -1 || !options.control_persist 230 || options.control_persist_timeout == 0) { 231 /* not using a ControlPersist timeout */ 232 control_persist_exit_time = 0; 233 } else if (channel_still_open(ssh)) { 234 /* some client connections are still open */ 235 if (control_persist_exit_time > 0) 236 debug2("%s: cancel scheduled exit", __func__); 237 control_persist_exit_time = 0; 238 } else if (control_persist_exit_time <= 0) { 239 /* a client connection has recently closed */ 240 control_persist_exit_time = monotime() + 241 (time_t)options.control_persist_timeout; 242 debug2("%s: schedule exit in %d seconds", __func__, 243 options.control_persist_timeout); 244 } 245 /* else we are already counting down to the timeout */ 246 } 247 248 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_" 249 static int 250 client_x11_display_valid(const char *display) 251 { 252 size_t i, dlen; 253 254 if (display == NULL) 255 return 0; 256 257 dlen = strlen(display); 258 for (i = 0; i < dlen; i++) { 259 if (!isalnum((u_char)display[i]) && 260 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) { 261 debug("Invalid character '%c' in DISPLAY", display[i]); 262 return 0; 263 } 264 } 265 return 1; 266 } 267 268 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1" 269 #define X11_TIMEOUT_SLACK 60 270 int 271 client_x11_get_proto(struct ssh *ssh, const char *display, 272 const char *xauth_path, u_int trusted, u_int timeout, 273 char **_proto, char **_data) 274 { 275 char cmd[1024], line[512], xdisplay[512]; 276 char xauthfile[PATH_MAX], xauthdir[PATH_MAX]; 277 static char proto[512], data[512]; 278 FILE *f; 279 int got_data = 0, generated = 0, do_unlink = 0, r; 280 struct stat st; 281 u_int now, x11_timeout_real; 282 283 *_proto = proto; 284 *_data = data; 285 proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0'; 286 287 if (!client_x11_display_valid(display)) { 288 if (display != NULL) 289 logit("DISPLAY \"%s\" invalid; disabling X11 forwarding", 290 display); 291 return -1; 292 } 293 if (xauth_path != NULL && stat(xauth_path, &st) == -1) { 294 debug("No xauth program."); 295 xauth_path = NULL; 296 } 297 298 if (xauth_path != NULL) { 299 /* 300 * Handle FamilyLocal case where $DISPLAY does 301 * not match an authorization entry. For this we 302 * just try "xauth list unix:displaynum.screennum". 303 * XXX: "localhost" match to determine FamilyLocal 304 * is not perfect. 305 */ 306 if (strncmp(display, "localhost:", 10) == 0) { 307 if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s", 308 display + 10)) < 0 || 309 (size_t)r >= sizeof(xdisplay)) { 310 error("%s: display name too long", __func__); 311 return -1; 312 } 313 display = xdisplay; 314 } 315 if (trusted == 0) { 316 /* 317 * Generate an untrusted X11 auth cookie. 318 * 319 * The authentication cookie should briefly outlive 320 * ssh's willingness to forward X11 connections to 321 * avoid nasty fail-open behaviour in the X server. 322 */ 323 mktemp_proto(xauthdir, sizeof(xauthdir)); 324 if (mkdtemp(xauthdir) == NULL) { 325 error("%s: mkdtemp: %s", 326 __func__, strerror(errno)); 327 return -1; 328 } 329 do_unlink = 1; 330 if ((r = snprintf(xauthfile, sizeof(xauthfile), 331 "%s/xauthfile", xauthdir)) < 0 || 332 (size_t)r >= sizeof(xauthfile)) { 333 error("%s: xauthfile path too long", __func__); 334 unlink(xauthfile); 335 rmdir(xauthdir); 336 return -1; 337 } 338 339 if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK) 340 x11_timeout_real = UINT_MAX; 341 else 342 x11_timeout_real = timeout + X11_TIMEOUT_SLACK; 343 if ((r = snprintf(cmd, sizeof(cmd), 344 "%s -f %s generate %s " SSH_X11_PROTO 345 " untrusted timeout %u 2>" _PATH_DEVNULL, 346 xauth_path, xauthfile, display, 347 x11_timeout_real)) < 0 || 348 (size_t)r >= sizeof(cmd)) 349 fatal("%s: cmd too long", __func__); 350 debug2("%s: %s", __func__, cmd); 351 if (x11_refuse_time == 0) { 352 now = monotime() + 1; 353 if (UINT_MAX - timeout < now) 354 x11_refuse_time = UINT_MAX; 355 else 356 x11_refuse_time = now + timeout; 357 channel_set_x11_refuse_time(ssh, 358 x11_refuse_time); 359 } 360 if (system(cmd) == 0) 361 generated = 1; 362 } 363 364 /* 365 * When in untrusted mode, we read the cookie only if it was 366 * successfully generated as an untrusted one in the step 367 * above. 368 */ 369 if (trusted || generated) { 370 snprintf(cmd, sizeof(cmd), 371 "%s %s%s list %s 2>" _PATH_DEVNULL, 372 xauth_path, 373 generated ? "-f " : "" , 374 generated ? xauthfile : "", 375 display); 376 debug2("x11_get_proto: %s", cmd); 377 f = popen(cmd, "r"); 378 if (f && fgets(line, sizeof(line), f) && 379 sscanf(line, "%*s %511s %511s", proto, data) == 2) 380 got_data = 1; 381 if (f) 382 pclose(f); 383 } 384 } 385 386 if (do_unlink) { 387 unlink(xauthfile); 388 rmdir(xauthdir); 389 } 390 391 /* Don't fall back to fake X11 data for untrusted forwarding */ 392 if (!trusted && !got_data) { 393 error("Warning: untrusted X11 forwarding setup failed: " 394 "xauth key data not generated"); 395 return -1; 396 } 397 398 /* 399 * If we didn't get authentication data, just make up some 400 * data. The forwarding code will check the validity of the 401 * response anyway, and substitute this data. The X11 402 * server, however, will ignore this fake data and use 403 * whatever authentication mechanisms it was using otherwise 404 * for the local connection. 405 */ 406 if (!got_data) { 407 u_int8_t rnd[16]; 408 u_int i; 409 410 logit("Warning: No xauth data; " 411 "using fake authentication data for X11 forwarding."); 412 strlcpy(proto, SSH_X11_PROTO, sizeof proto); 413 arc4random_buf(rnd, sizeof(rnd)); 414 for (i = 0; i < sizeof(rnd); i++) { 415 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", 416 rnd[i]); 417 } 418 } 419 420 return 0; 421 } 422 423 /* 424 * Checks if the client window has changed, and sends a packet about it to 425 * the server if so. The actual change is detected elsewhere (by a software 426 * interrupt on Unix); this just checks the flag and sends a message if 427 * appropriate. 428 */ 429 430 static void 431 client_check_window_change(struct ssh *ssh) 432 { 433 if (!received_window_change_signal) 434 return; 435 /** XXX race */ 436 received_window_change_signal = 0; 437 438 debug2("%s: changed", __func__); 439 440 channel_send_window_changes(ssh); 441 } 442 443 static int 444 client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh) 445 { 446 struct global_confirm *gc; 447 448 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL) 449 return 0; 450 if (gc->cb != NULL) 451 gc->cb(ssh, type, seq, gc->ctx); 452 if (--gc->ref_count <= 0) { 453 TAILQ_REMOVE(&global_confirms, gc, entry); 454 explicit_bzero(gc, sizeof(*gc)); 455 free(gc); 456 } 457 458 packet_set_alive_timeouts(0); 459 return 0; 460 } 461 462 static void 463 server_alive_check(void) 464 { 465 if (packet_inc_alive_timeouts() > options.server_alive_count_max) { 466 logit("Timeout, server %s not responding.", host); 467 cleanup_exit(255); 468 } 469 packet_start(SSH2_MSG_GLOBAL_REQUEST); 470 packet_put_cstring("keepalive@openssh.com"); 471 packet_put_char(1); /* boolean: want reply */ 472 packet_send(); 473 /* Insert an empty placeholder to maintain ordering */ 474 client_register_global_confirm(NULL, NULL); 475 } 476 477 /* 478 * Waits until the client can do something (some data becomes available on 479 * one of the file descriptors). 480 */ 481 static void 482 client_wait_until_can_do_something(struct ssh *ssh, 483 fd_set **readsetp, fd_set **writesetp, 484 int *maxfdp, u_int *nallocp, int rekeying) 485 { 486 struct timeval tv, *tvp; 487 int timeout_secs; 488 time_t minwait_secs = 0, server_alive_time = 0, now = monotime(); 489 int ret; 490 491 /* Add any selections by the channel mechanism. */ 492 channel_prepare_select(active_state, readsetp, writesetp, maxfdp, 493 nallocp, &minwait_secs); 494 495 /* channel_prepare_select could have closed the last channel */ 496 if (session_closed && !channel_still_open(ssh) && 497 !packet_have_data_to_write()) { 498 /* clear mask since we did not call select() */ 499 memset(*readsetp, 0, *nallocp); 500 memset(*writesetp, 0, *nallocp); 501 return; 502 } 503 504 FD_SET(connection_in, *readsetp); 505 506 /* Select server connection if have data to write to the server. */ 507 if (packet_have_data_to_write()) 508 FD_SET(connection_out, *writesetp); 509 510 /* 511 * Wait for something to happen. This will suspend the process until 512 * some selected descriptor can be read, written, or has some other 513 * event pending, or a timeout expires. 514 */ 515 516 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */ 517 if (options.server_alive_interval > 0) { 518 timeout_secs = options.server_alive_interval; 519 server_alive_time = now + options.server_alive_interval; 520 } 521 if (options.rekey_interval > 0 && !rekeying) 522 timeout_secs = MINIMUM(timeout_secs, packet_get_rekey_timeout()); 523 set_control_persist_exit_time(ssh); 524 if (control_persist_exit_time > 0) { 525 timeout_secs = MINIMUM(timeout_secs, 526 control_persist_exit_time - now); 527 if (timeout_secs < 0) 528 timeout_secs = 0; 529 } 530 if (minwait_secs != 0) 531 timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs); 532 if (timeout_secs == INT_MAX) 533 tvp = NULL; 534 else { 535 tv.tv_sec = timeout_secs; 536 tv.tv_usec = 0; 537 tvp = &tv; 538 } 539 540 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp); 541 if (ret < 0) { 542 char buf[100]; 543 544 /* 545 * We have to clear the select masks, because we return. 546 * We have to return, because the mainloop checks for the flags 547 * set by the signal handlers. 548 */ 549 memset(*readsetp, 0, *nallocp); 550 memset(*writesetp, 0, *nallocp); 551 552 if (errno == EINTR) 553 return; 554 /* Note: we might still have data in the buffers. */ 555 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno)); 556 buffer_append(&stderr_buffer, buf, strlen(buf)); 557 quit_pending = 1; 558 } else if (ret == 0) { 559 /* 560 * Timeout. Could have been either keepalive or rekeying. 561 * Keepalive we check here, rekeying is checked in clientloop. 562 */ 563 if (server_alive_time != 0 && server_alive_time <= monotime()) 564 server_alive_check(); 565 } 566 567 } 568 569 static void 570 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr) 571 { 572 /* Flush stdout and stderr buffers. */ 573 if (buffer_len(bout) > 0) 574 atomicio(vwrite, fileno(stdout), buffer_ptr(bout), 575 buffer_len(bout)); 576 if (buffer_len(berr) > 0) 577 atomicio(vwrite, fileno(stderr), buffer_ptr(berr), 578 buffer_len(berr)); 579 580 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 581 582 sshbuf_reset(bin); 583 sshbuf_reset(bout); 584 sshbuf_reset(berr); 585 586 /* Send the suspend signal to the program itself. */ 587 kill(getpid(), SIGTSTP); 588 589 /* Reset window sizes in case they have changed */ 590 received_window_change_signal = 1; 591 592 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 593 } 594 595 static void 596 client_process_net_input(fd_set *readset) 597 { 598 int len; 599 char buf[8192]; 600 601 /* 602 * Read input from the server, and add any such data to the buffer of 603 * the packet subsystem. 604 */ 605 if (FD_ISSET(connection_in, readset)) { 606 /* Read as much as possible. */ 607 len = read(connection_in, buf, sizeof(buf)); 608 if (len == 0) { 609 /* 610 * Received EOF. The remote host has closed the 611 * connection. 612 */ 613 snprintf(buf, sizeof buf, 614 "Connection to %.300s closed by remote host.\r\n", 615 host); 616 buffer_append(&stderr_buffer, buf, strlen(buf)); 617 quit_pending = 1; 618 return; 619 } 620 /* 621 * There is a kernel bug on Solaris that causes select to 622 * sometimes wake up even though there is no data available. 623 */ 624 if (len < 0 && (errno == EAGAIN || errno == EINTR)) 625 len = 0; 626 627 if (len < 0) { 628 /* 629 * An error has encountered. Perhaps there is a 630 * network problem. 631 */ 632 snprintf(buf, sizeof buf, 633 "Read from remote host %.300s: %.100s\r\n", 634 host, strerror(errno)); 635 buffer_append(&stderr_buffer, buf, strlen(buf)); 636 quit_pending = 1; 637 return; 638 } 639 packet_process_incoming(buf, len); 640 } 641 } 642 643 static void 644 client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx) 645 { 646 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx; 647 char errmsg[256]; 648 int tochan; 649 650 /* 651 * If a TTY was explicitly requested, then a failure to allocate 652 * one is fatal. 653 */ 654 if (cr->action == CONFIRM_TTY && 655 (options.request_tty == REQUEST_TTY_FORCE || 656 options.request_tty == REQUEST_TTY_YES)) 657 cr->action = CONFIRM_CLOSE; 658 659 /* XXX supress on mux _client_ quietmode */ 660 tochan = options.log_level >= SYSLOG_LEVEL_ERROR && 661 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE; 662 663 if (type == SSH2_MSG_CHANNEL_SUCCESS) { 664 debug2("%s request accepted on channel %d", 665 cr->request_type, c->self); 666 } else if (type == SSH2_MSG_CHANNEL_FAILURE) { 667 if (tochan) { 668 snprintf(errmsg, sizeof(errmsg), 669 "%s request failed\r\n", cr->request_type); 670 } else { 671 snprintf(errmsg, sizeof(errmsg), 672 "%s request failed on channel %d", 673 cr->request_type, c->self); 674 } 675 /* If error occurred on primary session channel, then exit */ 676 if (cr->action == CONFIRM_CLOSE && c->self == session_ident) 677 fatal("%s", errmsg); 678 /* 679 * If error occurred on mux client, append to 680 * their stderr. 681 */ 682 if (tochan) { 683 buffer_append(c->extended, errmsg, strlen(errmsg)); 684 } else 685 error("%s", errmsg); 686 if (cr->action == CONFIRM_TTY) { 687 /* 688 * If a TTY allocation error occurred, then arrange 689 * for the correct TTY to leave raw mode. 690 */ 691 if (c->self == session_ident) 692 leave_raw_mode(0); 693 else 694 mux_tty_alloc_failed(ssh, c); 695 } else if (cr->action == CONFIRM_CLOSE) { 696 chan_read_failed(ssh, c); 697 chan_write_failed(ssh, c); 698 } 699 } 700 free(cr); 701 } 702 703 static void 704 client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx) 705 { 706 free(ctx); 707 } 708 709 void 710 client_expect_confirm(struct ssh *ssh, int id, const char *request, 711 enum confirm_action action) 712 { 713 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr)); 714 715 cr->request_type = request; 716 cr->action = action; 717 718 channel_register_status_confirm(ssh, id, client_status_confirm, 719 client_abandon_status_confirm, cr); 720 } 721 722 void 723 client_register_global_confirm(global_confirm_cb *cb, void *ctx) 724 { 725 struct global_confirm *gc, *last_gc; 726 727 /* Coalesce identical callbacks */ 728 last_gc = TAILQ_LAST(&global_confirms, global_confirms); 729 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) { 730 if (++last_gc->ref_count >= INT_MAX) 731 fatal("%s: last_gc->ref_count = %d", 732 __func__, last_gc->ref_count); 733 return; 734 } 735 736 gc = xcalloc(1, sizeof(*gc)); 737 gc->cb = cb; 738 gc->ctx = ctx; 739 gc->ref_count = 1; 740 TAILQ_INSERT_TAIL(&global_confirms, gc, entry); 741 } 742 743 static void 744 process_cmdline(struct ssh *ssh) 745 { 746 void (*handler)(int); 747 char *s, *cmd; 748 int ok, delete = 0, local = 0, remote = 0, dynamic = 0; 749 struct Forward fwd; 750 751 memset(&fwd, 0, sizeof(fwd)); 752 753 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 754 handler = signal(SIGINT, SIG_IGN); 755 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO); 756 if (s == NULL) 757 goto out; 758 while (isspace((u_char)*s)) 759 s++; 760 if (*s == '-') 761 s++; /* Skip cmdline '-', if any */ 762 if (*s == '\0') 763 goto out; 764 765 if (*s == 'h' || *s == 'H' || *s == '?') { 766 logit("Commands:"); 767 logit(" -L[bind_address:]port:host:hostport " 768 "Request local forward"); 769 logit(" -R[bind_address:]port:host:hostport " 770 "Request remote forward"); 771 logit(" -D[bind_address:]port " 772 "Request dynamic forward"); 773 logit(" -KL[bind_address:]port " 774 "Cancel local forward"); 775 logit(" -KR[bind_address:]port " 776 "Cancel remote forward"); 777 logit(" -KD[bind_address:]port " 778 "Cancel dynamic forward"); 779 if (!options.permit_local_command) 780 goto out; 781 logit(" !args " 782 "Execute local command"); 783 goto out; 784 } 785 786 if (*s == '!' && options.permit_local_command) { 787 s++; 788 ssh_local_cmd(s); 789 goto out; 790 } 791 792 if (*s == 'K') { 793 delete = 1; 794 s++; 795 } 796 if (*s == 'L') 797 local = 1; 798 else if (*s == 'R') 799 remote = 1; 800 else if (*s == 'D') 801 dynamic = 1; 802 else { 803 logit("Invalid command."); 804 goto out; 805 } 806 807 while (isspace((u_char)*++s)) 808 ; 809 810 /* XXX update list of forwards in options */ 811 if (delete) { 812 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */ 813 if (!parse_forward(&fwd, s, 1, 0)) { 814 logit("Bad forwarding close specification."); 815 goto out; 816 } 817 if (remote) 818 ok = channel_request_rforward_cancel(ssh, &fwd) == 0; 819 else if (dynamic) 820 ok = channel_cancel_lport_listener(ssh, &fwd, 821 0, &options.fwd_opts) > 0; 822 else 823 ok = channel_cancel_lport_listener(ssh, &fwd, 824 CHANNEL_CANCEL_PORT_STATIC, 825 &options.fwd_opts) > 0; 826 if (!ok) { 827 logit("Unknown port forwarding."); 828 goto out; 829 } 830 logit("Canceled forwarding."); 831 } else { 832 if (!parse_forward(&fwd, s, dynamic, remote)) { 833 logit("Bad forwarding specification."); 834 goto out; 835 } 836 if (local || dynamic) { 837 if (!channel_setup_local_fwd_listener(ssh, &fwd, 838 &options.fwd_opts)) { 839 logit("Port forwarding failed."); 840 goto out; 841 } 842 } else { 843 if (channel_request_remote_forwarding(ssh, &fwd) < 0) { 844 logit("Port forwarding failed."); 845 goto out; 846 } 847 } 848 logit("Forwarding port."); 849 } 850 851 out: 852 signal(SIGINT, handler); 853 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 854 free(cmd); 855 free(fwd.listen_host); 856 free(fwd.listen_path); 857 free(fwd.connect_host); 858 free(fwd.connect_path); 859 } 860 861 /* reasons to suppress output of an escape command in help output */ 862 #define SUPPRESS_NEVER 0 /* never suppress, always show */ 863 #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */ 864 #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */ 865 #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */ 866 struct escape_help_text { 867 const char *cmd; 868 const char *text; 869 unsigned int flags; 870 }; 871 static struct escape_help_text esc_txt[] = { 872 {".", "terminate session", SUPPRESS_MUXMASTER}, 873 {".", "terminate connection (and any multiplexed sessions)", 874 SUPPRESS_MUXCLIENT}, 875 {"B", "send a BREAK to the remote system", SUPPRESS_NEVER}, 876 {"C", "open a command line", SUPPRESS_MUXCLIENT}, 877 {"R", "request rekey", SUPPRESS_NEVER}, 878 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT}, 879 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT}, 880 {"#", "list forwarded connections", SUPPRESS_NEVER}, 881 {"&", "background ssh (when waiting for connections to terminate)", 882 SUPPRESS_MUXCLIENT}, 883 {"?", "this message", SUPPRESS_NEVER}, 884 }; 885 886 static void 887 print_escape_help(Buffer *b, int escape_char, int mux_client, int using_stderr) 888 { 889 unsigned int i, suppress_flags; 890 char string[1024]; 891 892 snprintf(string, sizeof string, "%c?\r\n" 893 "Supported escape sequences:\r\n", escape_char); 894 buffer_append(b, string, strlen(string)); 895 896 suppress_flags = 897 (mux_client ? SUPPRESS_MUXCLIENT : 0) | 898 (mux_client ? 0 : SUPPRESS_MUXMASTER) | 899 (using_stderr ? 0 : SUPPRESS_SYSLOG); 900 901 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) { 902 if (esc_txt[i].flags & suppress_flags) 903 continue; 904 snprintf(string, sizeof string, " %c%-3s - %s\r\n", 905 escape_char, esc_txt[i].cmd, esc_txt[i].text); 906 buffer_append(b, string, strlen(string)); 907 } 908 909 snprintf(string, sizeof string, 910 " %c%c - send the escape character by typing it twice\r\n" 911 "(Note that escapes are only recognized immediately after " 912 "newline.)\r\n", escape_char, escape_char); 913 buffer_append(b, string, strlen(string)); 914 } 915 916 /* 917 * Process the characters one by one. 918 */ 919 static int 920 process_escapes(struct ssh *ssh, Channel *c, 921 Buffer *bin, Buffer *bout, Buffer *berr, 922 char *buf, int len) 923 { 924 char string[1024]; 925 pid_t pid; 926 int bytes = 0; 927 u_int i; 928 u_char ch; 929 char *s; 930 struct escape_filter_ctx *efc = c->filter_ctx == NULL ? 931 NULL : (struct escape_filter_ctx *)c->filter_ctx; 932 933 if (c->filter_ctx == NULL) 934 return 0; 935 936 if (len <= 0) 937 return (0); 938 939 for (i = 0; i < (u_int)len; i++) { 940 /* Get one character at a time. */ 941 ch = buf[i]; 942 943 if (efc->escape_pending) { 944 /* We have previously seen an escape character. */ 945 /* Clear the flag now. */ 946 efc->escape_pending = 0; 947 948 /* Process the escaped character. */ 949 switch (ch) { 950 case '.': 951 /* Terminate the connection. */ 952 snprintf(string, sizeof string, "%c.\r\n", 953 efc->escape_char); 954 buffer_append(berr, string, strlen(string)); 955 956 if (c && c->ctl_chan != -1) { 957 chan_read_failed(ssh, c); 958 chan_write_failed(ssh, c); 959 if (c->detach_user) { 960 c->detach_user(ssh, 961 c->self, NULL); 962 } 963 c->type = SSH_CHANNEL_ABANDONED; 964 buffer_clear(c->input); 965 chan_ibuf_empty(ssh, c); 966 return 0; 967 } else 968 quit_pending = 1; 969 return -1; 970 971 case 'Z' - 64: 972 /* XXX support this for mux clients */ 973 if (c && c->ctl_chan != -1) { 974 char b[16]; 975 noescape: 976 if (ch == 'Z' - 64) 977 snprintf(b, sizeof b, "^Z"); 978 else 979 snprintf(b, sizeof b, "%c", ch); 980 snprintf(string, sizeof string, 981 "%c%s escape not available to " 982 "multiplexed sessions\r\n", 983 efc->escape_char, b); 984 buffer_append(berr, string, 985 strlen(string)); 986 continue; 987 } 988 /* Suspend the program. Inform the user */ 989 snprintf(string, sizeof string, 990 "%c^Z [suspend ssh]\r\n", efc->escape_char); 991 buffer_append(berr, string, strlen(string)); 992 993 /* Restore terminal modes and suspend. */ 994 client_suspend_self(bin, bout, berr); 995 996 /* We have been continued. */ 997 continue; 998 999 case 'B': 1000 snprintf(string, sizeof string, 1001 "%cB\r\n", efc->escape_char); 1002 buffer_append(berr, string, strlen(string)); 1003 channel_request_start(ssh, c->self, "break", 0); 1004 packet_put_int(1000); 1005 packet_send(); 1006 continue; 1007 1008 case 'R': 1009 if (datafellows & SSH_BUG_NOREKEY) 1010 logit("Server does not " 1011 "support re-keying"); 1012 else 1013 need_rekeying = 1; 1014 continue; 1015 1016 case 'V': 1017 /* FALLTHROUGH */ 1018 case 'v': 1019 if (c && c->ctl_chan != -1) 1020 goto noescape; 1021 if (!log_is_on_stderr()) { 1022 snprintf(string, sizeof string, 1023 "%c%c [Logging to syslog]\r\n", 1024 efc->escape_char, ch); 1025 buffer_append(berr, string, 1026 strlen(string)); 1027 continue; 1028 } 1029 if (ch == 'V' && options.log_level > 1030 SYSLOG_LEVEL_QUIET) 1031 log_change_level(--options.log_level); 1032 if (ch == 'v' && options.log_level < 1033 SYSLOG_LEVEL_DEBUG3) 1034 log_change_level(++options.log_level); 1035 snprintf(string, sizeof string, 1036 "%c%c [LogLevel %s]\r\n", 1037 efc->escape_char, ch, 1038 log_level_name(options.log_level)); 1039 buffer_append(berr, string, strlen(string)); 1040 continue; 1041 1042 case '&': 1043 if (c && c->ctl_chan != -1) 1044 goto noescape; 1045 /* 1046 * Detach the program (continue to serve 1047 * connections, but put in background and no 1048 * more new connections). 1049 */ 1050 /* Restore tty modes. */ 1051 leave_raw_mode( 1052 options.request_tty == REQUEST_TTY_FORCE); 1053 1054 /* Stop listening for new connections. */ 1055 channel_stop_listening(ssh); 1056 1057 snprintf(string, sizeof string, 1058 "%c& [backgrounded]\n", efc->escape_char); 1059 buffer_append(berr, string, strlen(string)); 1060 1061 /* Fork into background. */ 1062 pid = fork(); 1063 if (pid < 0) { 1064 error("fork: %.100s", strerror(errno)); 1065 continue; 1066 } 1067 if (pid != 0) { /* This is the parent. */ 1068 /* The parent just exits. */ 1069 exit(0); 1070 } 1071 /* The child continues serving connections. */ 1072 buffer_append(bin, "\004", 1); 1073 /* fake EOF on stdin */ 1074 return -1; 1075 case '?': 1076 print_escape_help(berr, efc->escape_char, 1077 (c && c->ctl_chan != -1), 1078 log_is_on_stderr()); 1079 continue; 1080 1081 case '#': 1082 snprintf(string, sizeof string, "%c#\r\n", 1083 efc->escape_char); 1084 buffer_append(berr, string, strlen(string)); 1085 s = channel_open_message(ssh); 1086 buffer_append(berr, s, strlen(s)); 1087 free(s); 1088 continue; 1089 1090 case 'C': 1091 if (c && c->ctl_chan != -1) 1092 goto noescape; 1093 process_cmdline(ssh); 1094 continue; 1095 1096 default: 1097 if (ch != efc->escape_char) { 1098 buffer_put_char(bin, efc->escape_char); 1099 bytes++; 1100 } 1101 /* Escaped characters fall through here */ 1102 break; 1103 } 1104 } else { 1105 /* 1106 * The previous character was not an escape char. 1107 * Check if this is an escape. 1108 */ 1109 if (last_was_cr && ch == efc->escape_char) { 1110 /* 1111 * It is. Set the flag and continue to 1112 * next character. 1113 */ 1114 efc->escape_pending = 1; 1115 continue; 1116 } 1117 } 1118 1119 /* 1120 * Normal character. Record whether it was a newline, 1121 * and append it to the buffer. 1122 */ 1123 last_was_cr = (ch == '\r' || ch == '\n'); 1124 buffer_put_char(bin, ch); 1125 bytes++; 1126 } 1127 return bytes; 1128 } 1129 1130 /* 1131 * Get packets from the connection input buffer, and process them as long as 1132 * there are packets available. 1133 * 1134 * Any unknown packets received during the actual 1135 * session cause the session to terminate. This is 1136 * intended to make debugging easier since no 1137 * confirmations are sent. Any compatible protocol 1138 * extensions must be negotiated during the 1139 * preparatory phase. 1140 */ 1141 1142 static void 1143 client_process_buffered_input_packets(void) 1144 { 1145 ssh_dispatch_run_fatal(active_state, DISPATCH_NONBLOCK, &quit_pending); 1146 } 1147 1148 /* scan buf[] for '~' before sending data to the peer */ 1149 1150 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */ 1151 void * 1152 client_new_escape_filter_ctx(int escape_char) 1153 { 1154 struct escape_filter_ctx *ret; 1155 1156 ret = xcalloc(1, sizeof(*ret)); 1157 ret->escape_pending = 0; 1158 ret->escape_char = escape_char; 1159 return (void *)ret; 1160 } 1161 1162 /* Free the escape filter context on channel free */ 1163 void 1164 client_filter_cleanup(struct ssh *ssh, int cid, void *ctx) 1165 { 1166 free(ctx); 1167 } 1168 1169 int 1170 client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len) 1171 { 1172 if (c->extended_usage != CHAN_EXTENDED_WRITE) 1173 return 0; 1174 1175 return process_escapes(ssh, c, c->input, c->output, c->extended, 1176 buf, len); 1177 } 1178 1179 static void 1180 client_channel_closed(struct ssh *ssh, int id, void *arg) 1181 { 1182 channel_cancel_cleanup(ssh, id); 1183 session_closed = 1; 1184 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1185 } 1186 1187 /* 1188 * Implements the interactive session with the server. This is called after 1189 * the user has been authenticated, and a command has been started on the 1190 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character 1191 * used as an escape character for terminating or suspending the session. 1192 */ 1193 int 1194 client_loop(struct ssh *ssh, int have_pty, int escape_char_arg, 1195 int ssh2_chan_id) 1196 { 1197 fd_set *readset = NULL, *writeset = NULL; 1198 double start_time, total_time; 1199 int r, max_fd = 0, max_fd2 = 0, len; 1200 u_int64_t ibytes, obytes; 1201 u_int nalloc = 0; 1202 char buf[100]; 1203 1204 debug("Entering interactive session."); 1205 1206 if (options.control_master && 1207 !option_clear_or_none(options.control_path)) { 1208 debug("pledge: id"); 1209 if (pledge("stdio rpath wpath cpath unix inet dns recvfd proc exec id tty", 1210 NULL) == -1) 1211 fatal("%s pledge(): %s", __func__, strerror(errno)); 1212 1213 } else if (options.forward_x11 || options.permit_local_command) { 1214 debug("pledge: exec"); 1215 if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty", 1216 NULL) == -1) 1217 fatal("%s pledge(): %s", __func__, strerror(errno)); 1218 1219 } else if (options.update_hostkeys) { 1220 debug("pledge: filesystem full"); 1221 if (pledge("stdio rpath wpath cpath unix inet dns proc tty", 1222 NULL) == -1) 1223 fatal("%s pledge(): %s", __func__, strerror(errno)); 1224 1225 } else if (!option_clear_or_none(options.proxy_command) || 1226 fork_after_authentication_flag) { 1227 debug("pledge: proc"); 1228 if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1) 1229 fatal("%s pledge(): %s", __func__, strerror(errno)); 1230 1231 } else { 1232 debug("pledge: network"); 1233 if (pledge("stdio unix inet dns proc tty", NULL) == -1) 1234 fatal("%s pledge(): %s", __func__, strerror(errno)); 1235 } 1236 1237 start_time = monotime_double(); 1238 1239 /* Initialize variables. */ 1240 last_was_cr = 1; 1241 exit_status = -1; 1242 connection_in = packet_get_connection_in(); 1243 connection_out = packet_get_connection_out(); 1244 max_fd = MAXIMUM(connection_in, connection_out); 1245 1246 quit_pending = 0; 1247 1248 /* Initialize buffers. */ 1249 buffer_init(&stderr_buffer); 1250 1251 client_init_dispatch(); 1252 1253 /* 1254 * Set signal handlers, (e.g. to restore non-blocking mode) 1255 * but don't overwrite SIG_IGN, matches behaviour from rsh(1) 1256 */ 1257 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) 1258 signal(SIGHUP, signal_handler); 1259 if (signal(SIGINT, SIG_IGN) != SIG_IGN) 1260 signal(SIGINT, signal_handler); 1261 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) 1262 signal(SIGQUIT, signal_handler); 1263 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) 1264 signal(SIGTERM, signal_handler); 1265 signal(SIGWINCH, window_change_handler); 1266 1267 if (have_pty) 1268 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1269 1270 session_ident = ssh2_chan_id; 1271 if (session_ident != -1) { 1272 if (escape_char_arg != SSH_ESCAPECHAR_NONE) { 1273 channel_register_filter(ssh, session_ident, 1274 client_simple_escape_filter, NULL, 1275 client_filter_cleanup, 1276 client_new_escape_filter_ctx( 1277 escape_char_arg)); 1278 } 1279 channel_register_cleanup(ssh, session_ident, 1280 client_channel_closed, 0); 1281 } 1282 1283 /* Main loop of the client for the interactive session mode. */ 1284 while (!quit_pending) { 1285 1286 /* Process buffered packets sent by the server. */ 1287 client_process_buffered_input_packets(); 1288 1289 if (session_closed && !channel_still_open(ssh)) 1290 break; 1291 1292 if (ssh_packet_is_rekeying(ssh)) { 1293 debug("rekeying in progress"); 1294 } else if (need_rekeying) { 1295 /* manual rekey request */ 1296 debug("need rekeying"); 1297 if ((r = kex_start_rekex(ssh)) != 0) 1298 fatal("%s: kex_start_rekex: %s", __func__, 1299 ssh_err(r)); 1300 need_rekeying = 0; 1301 } else { 1302 /* 1303 * Make packets from buffered channel data, and 1304 * enqueue them for sending to the server. 1305 */ 1306 if (packet_not_very_much_data_to_write()) 1307 channel_output_poll(ssh); 1308 1309 /* 1310 * Check if the window size has changed, and buffer a 1311 * message about it to the server if so. 1312 */ 1313 client_check_window_change(ssh); 1314 1315 if (quit_pending) 1316 break; 1317 } 1318 /* 1319 * Wait until we have something to do (something becomes 1320 * available on one of the descriptors). 1321 */ 1322 max_fd2 = max_fd; 1323 client_wait_until_can_do_something(ssh, &readset, &writeset, 1324 &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh)); 1325 1326 if (quit_pending) 1327 break; 1328 1329 /* Do channel operations unless rekeying in progress. */ 1330 if (!ssh_packet_is_rekeying(ssh)) 1331 channel_after_select(ssh, readset, writeset); 1332 1333 /* Buffer input from the connection. */ 1334 client_process_net_input(readset); 1335 1336 if (quit_pending) 1337 break; 1338 1339 /* 1340 * Send as much buffered packet data as possible to the 1341 * sender. 1342 */ 1343 if (FD_ISSET(connection_out, writeset)) 1344 packet_write_poll(); 1345 1346 /* 1347 * If we are a backgrounded control master, and the 1348 * timeout has expired without any active client 1349 * connections, then quit. 1350 */ 1351 if (control_persist_exit_time > 0) { 1352 if (monotime() >= control_persist_exit_time) { 1353 debug("ControlPersist timeout expired"); 1354 break; 1355 } 1356 } 1357 } 1358 free(readset); 1359 free(writeset); 1360 1361 /* Terminate the session. */ 1362 1363 /* Stop watching for window change. */ 1364 signal(SIGWINCH, SIG_DFL); 1365 1366 packet_start(SSH2_MSG_DISCONNECT); 1367 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION); 1368 packet_put_cstring("disconnected by user"); 1369 packet_put_cstring(""); /* language tag */ 1370 packet_send(); 1371 packet_write_wait(); 1372 1373 channel_free_all(ssh); 1374 1375 if (have_pty) 1376 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1377 1378 /* restore blocking io */ 1379 if (!isatty(fileno(stdin))) 1380 unset_nonblock(fileno(stdin)); 1381 if (!isatty(fileno(stdout))) 1382 unset_nonblock(fileno(stdout)); 1383 if (!isatty(fileno(stderr))) 1384 unset_nonblock(fileno(stderr)); 1385 1386 /* 1387 * If there was no shell or command requested, there will be no remote 1388 * exit status to be returned. In that case, clear error code if the 1389 * connection was deliberately terminated at this end. 1390 */ 1391 if (no_shell_flag && received_signal == SIGTERM) { 1392 received_signal = 0; 1393 exit_status = 0; 1394 } 1395 1396 if (received_signal) { 1397 verbose("Killed by signal %d.", (int) received_signal); 1398 cleanup_exit(0); 1399 } 1400 1401 /* 1402 * In interactive mode (with pseudo tty) display a message indicating 1403 * that the connection has been closed. 1404 */ 1405 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) { 1406 snprintf(buf, sizeof buf, 1407 "Connection to %.64s closed.\r\n", host); 1408 buffer_append(&stderr_buffer, buf, strlen(buf)); 1409 } 1410 1411 /* Output any buffered data for stderr. */ 1412 if (buffer_len(&stderr_buffer) > 0) { 1413 len = atomicio(vwrite, fileno(stderr), 1414 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer)); 1415 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer)) 1416 error("Write failed flushing stderr buffer."); 1417 else 1418 buffer_consume(&stderr_buffer, len); 1419 } 1420 1421 /* Clear and free any buffers. */ 1422 explicit_bzero(buf, sizeof(buf)); 1423 buffer_free(&stderr_buffer); 1424 1425 /* Report bytes transferred, and transfer rates. */ 1426 total_time = monotime_double() - start_time; 1427 packet_get_bytes(&ibytes, &obytes); 1428 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds", 1429 (unsigned long long)obytes, (unsigned long long)ibytes, total_time); 1430 if (total_time > 0) 1431 verbose("Bytes per second: sent %.1f, received %.1f", 1432 obytes / total_time, ibytes / total_time); 1433 /* Return the exit status of the program. */ 1434 debug("Exit status %d", exit_status); 1435 return exit_status; 1436 } 1437 1438 /*********/ 1439 1440 static Channel * 1441 client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type, 1442 int rchan, u_int rwindow, u_int rmaxpack) 1443 { 1444 Channel *c = NULL; 1445 struct sshbuf *b = NULL; 1446 char *listen_address, *originator_address; 1447 u_short listen_port, originator_port; 1448 int r; 1449 1450 /* Get rest of the packet */ 1451 listen_address = packet_get_string(NULL); 1452 listen_port = packet_get_int(); 1453 originator_address = packet_get_string(NULL); 1454 originator_port = packet_get_int(); 1455 packet_check_eom(); 1456 1457 debug("%s: listen %s port %d, originator %s port %d", __func__, 1458 listen_address, listen_port, originator_address, originator_port); 1459 1460 c = channel_connect_by_listen_address(ssh, listen_address, listen_port, 1461 "forwarded-tcpip", originator_address); 1462 1463 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) { 1464 if ((b = sshbuf_new()) == NULL) { 1465 error("%s: alloc reply", __func__); 1466 goto out; 1467 } 1468 /* reconstruct and send to muxclient */ 1469 if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */ 1470 (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 || 1471 (r = sshbuf_put_cstring(b, request_type)) != 0 || 1472 (r = sshbuf_put_u32(b, rchan)) != 0 || 1473 (r = sshbuf_put_u32(b, rwindow)) != 0 || 1474 (r = sshbuf_put_u32(b, rmaxpack)) != 0 || 1475 (r = sshbuf_put_cstring(b, listen_address)) != 0 || 1476 (r = sshbuf_put_u32(b, listen_port)) != 0 || 1477 (r = sshbuf_put_cstring(b, originator_address)) != 0 || 1478 (r = sshbuf_put_u32(b, originator_port)) != 0 || 1479 (r = sshbuf_put_stringb(c->output, b)) != 0) { 1480 error("%s: compose for muxclient %s", __func__, 1481 ssh_err(r)); 1482 goto out; 1483 } 1484 } 1485 1486 out: 1487 sshbuf_free(b); 1488 free(originator_address); 1489 free(listen_address); 1490 return c; 1491 } 1492 1493 static Channel * 1494 client_request_forwarded_streamlocal(struct ssh *ssh, 1495 const char *request_type, int rchan) 1496 { 1497 Channel *c = NULL; 1498 char *listen_path; 1499 1500 /* Get the remote path. */ 1501 listen_path = packet_get_string(NULL); 1502 /* XXX: Skip reserved field for now. */ 1503 if (packet_get_string_ptr(NULL) == NULL) 1504 fatal("%s: packet_get_string_ptr failed", __func__); 1505 packet_check_eom(); 1506 1507 debug("%s: %s", __func__, listen_path); 1508 1509 c = channel_connect_by_listen_path(ssh, listen_path, 1510 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal"); 1511 free(listen_path); 1512 return c; 1513 } 1514 1515 static Channel * 1516 client_request_x11(struct ssh *ssh, const char *request_type, int rchan) 1517 { 1518 Channel *c = NULL; 1519 char *originator; 1520 u_short originator_port; 1521 int sock; 1522 1523 if (!options.forward_x11) { 1524 error("Warning: ssh server tried X11 forwarding."); 1525 error("Warning: this is probably a break-in attempt by a " 1526 "malicious server."); 1527 return NULL; 1528 } 1529 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) { 1530 verbose("Rejected X11 connection after ForwardX11Timeout " 1531 "expired"); 1532 return NULL; 1533 } 1534 originator = packet_get_string(NULL); 1535 originator_port = packet_get_int(); 1536 packet_check_eom(); 1537 /* XXX check permission */ 1538 debug("client_request_x11: request from %s %d", originator, 1539 originator_port); 1540 free(originator); 1541 sock = x11_connect_display(ssh); 1542 if (sock < 0) 1543 return NULL; 1544 c = channel_new(ssh, "x11", 1545 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 1546 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1); 1547 c->force_drain = 1; 1548 return c; 1549 } 1550 1551 static Channel * 1552 client_request_agent(struct ssh *ssh, const char *request_type, int rchan) 1553 { 1554 Channel *c = NULL; 1555 int r, sock; 1556 1557 if (!options.forward_agent) { 1558 error("Warning: ssh server tried agent forwarding."); 1559 error("Warning: this is probably a break-in attempt by a " 1560 "malicious server."); 1561 return NULL; 1562 } 1563 if ((r = ssh_get_authentication_socket(&sock)) != 0) { 1564 if (r != SSH_ERR_AGENT_NOT_PRESENT) 1565 debug("%s: ssh_get_authentication_socket: %s", 1566 __func__, ssh_err(r)); 1567 return NULL; 1568 } 1569 c = channel_new(ssh, "authentication agent connection", 1570 SSH_CHANNEL_OPEN, sock, sock, -1, 1571 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, 1572 "authentication agent connection", 1); 1573 c->force_drain = 1; 1574 return c; 1575 } 1576 1577 char * 1578 client_request_tun_fwd(struct ssh *ssh, int tun_mode, 1579 int local_tun, int remote_tun) 1580 { 1581 Channel *c; 1582 int fd; 1583 char *ifname = NULL; 1584 1585 if (tun_mode == SSH_TUNMODE_NO) 1586 return 0; 1587 1588 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode); 1589 1590 /* Open local tunnel device */ 1591 if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) { 1592 error("Tunnel device open failed."); 1593 return NULL; 1594 } 1595 debug("Tunnel forwarding using interface %s", ifname); 1596 1597 c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1, 1598 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 1599 c->datagram = 1; 1600 1601 packet_start(SSH2_MSG_CHANNEL_OPEN); 1602 packet_put_cstring("tun@openssh.com"); 1603 packet_put_int(c->self); 1604 packet_put_int(c->local_window_max); 1605 packet_put_int(c->local_maxpacket); 1606 packet_put_int(tun_mode); 1607 packet_put_int(remote_tun); 1608 packet_send(); 1609 1610 return ifname; 1611 } 1612 1613 /* XXXX move to generic input handler */ 1614 static int 1615 client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh) 1616 { 1617 Channel *c = NULL; 1618 char *ctype; 1619 int rchan; 1620 u_int rmaxpack, rwindow, len; 1621 1622 ctype = packet_get_string(&len); 1623 rchan = packet_get_int(); 1624 rwindow = packet_get_int(); 1625 rmaxpack = packet_get_int(); 1626 1627 debug("client_input_channel_open: ctype %s rchan %d win %d max %d", 1628 ctype, rchan, rwindow, rmaxpack); 1629 1630 if (strcmp(ctype, "forwarded-tcpip") == 0) { 1631 c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow, 1632 rmaxpack); 1633 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) { 1634 c = client_request_forwarded_streamlocal(ssh, ctype, rchan); 1635 } else if (strcmp(ctype, "x11") == 0) { 1636 c = client_request_x11(ssh, ctype, rchan); 1637 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) { 1638 c = client_request_agent(ssh, ctype, rchan); 1639 } 1640 if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) { 1641 debug3("proxied to downstream: %s", ctype); 1642 } else if (c != NULL) { 1643 debug("confirm %s", ctype); 1644 c->remote_id = rchan; 1645 c->have_remote_id = 1; 1646 c->remote_window = rwindow; 1647 c->remote_maxpacket = rmaxpack; 1648 if (c->type != SSH_CHANNEL_CONNECTING) { 1649 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION); 1650 packet_put_int(c->remote_id); 1651 packet_put_int(c->self); 1652 packet_put_int(c->local_window); 1653 packet_put_int(c->local_maxpacket); 1654 packet_send(); 1655 } 1656 } else { 1657 debug("failure %s", ctype); 1658 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE); 1659 packet_put_int(rchan); 1660 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED); 1661 packet_put_cstring("open failed"); 1662 packet_put_cstring(""); 1663 packet_send(); 1664 } 1665 free(ctype); 1666 return 0; 1667 } 1668 1669 static int 1670 client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh) 1671 { 1672 Channel *c = NULL; 1673 int exitval, id, reply, success = 0; 1674 char *rtype; 1675 1676 id = packet_get_int(); 1677 c = channel_lookup(ssh, id); 1678 if (channel_proxy_upstream(c, type, seq, ssh)) 1679 return 0; 1680 rtype = packet_get_string(NULL); 1681 reply = packet_get_char(); 1682 1683 debug("client_input_channel_req: channel %d rtype %s reply %d", 1684 id, rtype, reply); 1685 1686 if (id == -1) { 1687 error("client_input_channel_req: request for channel -1"); 1688 } else if (c == NULL) { 1689 error("client_input_channel_req: channel %d: " 1690 "unknown channel", id); 1691 } else if (strcmp(rtype, "eow@openssh.com") == 0) { 1692 packet_check_eom(); 1693 chan_rcvd_eow(ssh, c); 1694 } else if (strcmp(rtype, "exit-status") == 0) { 1695 exitval = packet_get_int(); 1696 if (c->ctl_chan != -1) { 1697 mux_exit_message(ssh, c, exitval); 1698 success = 1; 1699 } else if (id == session_ident) { 1700 /* Record exit value of local session */ 1701 success = 1; 1702 exit_status = exitval; 1703 } else { 1704 /* Probably for a mux channel that has already closed */ 1705 debug("%s: no sink for exit-status on channel %d", 1706 __func__, id); 1707 } 1708 packet_check_eom(); 1709 } 1710 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) { 1711 if (!c->have_remote_id) 1712 fatal("%s: channel %d: no remote_id", 1713 __func__, c->self); 1714 packet_start(success ? 1715 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE); 1716 packet_put_int(c->remote_id); 1717 packet_send(); 1718 } 1719 free(rtype); 1720 return 0; 1721 } 1722 1723 struct hostkeys_update_ctx { 1724 /* The hostname and (optionally) IP address string for the server */ 1725 char *host_str, *ip_str; 1726 1727 /* 1728 * Keys received from the server and a flag for each indicating 1729 * whether they already exist in known_hosts. 1730 * keys_seen is filled in by hostkeys_find() and later (for new 1731 * keys) by client_global_hostkeys_private_confirm(). 1732 */ 1733 struct sshkey **keys; 1734 int *keys_seen; 1735 size_t nkeys, nnew; 1736 1737 /* 1738 * Keys that are in known_hosts, but were not present in the update 1739 * from the server (i.e. scheduled to be deleted). 1740 * Filled in by hostkeys_find(). 1741 */ 1742 struct sshkey **old_keys; 1743 size_t nold; 1744 }; 1745 1746 static void 1747 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx) 1748 { 1749 size_t i; 1750 1751 if (ctx == NULL) 1752 return; 1753 for (i = 0; i < ctx->nkeys; i++) 1754 sshkey_free(ctx->keys[i]); 1755 free(ctx->keys); 1756 free(ctx->keys_seen); 1757 for (i = 0; i < ctx->nold; i++) 1758 sshkey_free(ctx->old_keys[i]); 1759 free(ctx->old_keys); 1760 free(ctx->host_str); 1761 free(ctx->ip_str); 1762 free(ctx); 1763 } 1764 1765 static int 1766 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx) 1767 { 1768 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx; 1769 size_t i; 1770 struct sshkey **tmp; 1771 1772 if (l->status != HKF_STATUS_MATCHED || l->key == NULL) 1773 return 0; 1774 1775 /* Mark off keys we've already seen for this host */ 1776 for (i = 0; i < ctx->nkeys; i++) { 1777 if (sshkey_equal(l->key, ctx->keys[i])) { 1778 debug3("%s: found %s key at %s:%ld", __func__, 1779 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum); 1780 ctx->keys_seen[i] = 1; 1781 return 0; 1782 } 1783 } 1784 /* This line contained a key that not offered by the server */ 1785 debug3("%s: deprecated %s key at %s:%ld", __func__, 1786 sshkey_ssh_name(l->key), l->path, l->linenum); 1787 if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1, 1788 sizeof(*ctx->old_keys))) == NULL) 1789 fatal("%s: recallocarray failed nold = %zu", 1790 __func__, ctx->nold); 1791 ctx->old_keys = tmp; 1792 ctx->old_keys[ctx->nold++] = l->key; 1793 l->key = NULL; 1794 1795 return 0; 1796 } 1797 1798 static void 1799 update_known_hosts(struct hostkeys_update_ctx *ctx) 1800 { 1801 int r, was_raw = 0; 1802 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ? 1803 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE; 1804 char *fp, *response; 1805 size_t i; 1806 1807 for (i = 0; i < ctx->nkeys; i++) { 1808 if (ctx->keys_seen[i] != 2) 1809 continue; 1810 if ((fp = sshkey_fingerprint(ctx->keys[i], 1811 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 1812 fatal("%s: sshkey_fingerprint failed", __func__); 1813 do_log2(loglevel, "Learned new hostkey: %s %s", 1814 sshkey_type(ctx->keys[i]), fp); 1815 free(fp); 1816 } 1817 for (i = 0; i < ctx->nold; i++) { 1818 if ((fp = sshkey_fingerprint(ctx->old_keys[i], 1819 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 1820 fatal("%s: sshkey_fingerprint failed", __func__); 1821 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s", 1822 sshkey_type(ctx->old_keys[i]), fp); 1823 free(fp); 1824 } 1825 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) { 1826 if (get_saved_tio() != NULL) { 1827 leave_raw_mode(1); 1828 was_raw = 1; 1829 } 1830 response = NULL; 1831 for (i = 0; !quit_pending && i < 3; i++) { 1832 free(response); 1833 response = read_passphrase("Accept updated hostkeys? " 1834 "(yes/no): ", RP_ECHO); 1835 if (strcasecmp(response, "yes") == 0) 1836 break; 1837 else if (quit_pending || response == NULL || 1838 strcasecmp(response, "no") == 0) { 1839 options.update_hostkeys = 0; 1840 break; 1841 } else { 1842 do_log2(loglevel, "Please enter " 1843 "\"yes\" or \"no\""); 1844 } 1845 } 1846 if (quit_pending || i >= 3 || response == NULL) 1847 options.update_hostkeys = 0; 1848 free(response); 1849 if (was_raw) 1850 enter_raw_mode(1); 1851 } 1852 1853 /* 1854 * Now that all the keys are verified, we can go ahead and replace 1855 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't 1856 * cancel the operation). 1857 */ 1858 if (options.update_hostkeys != 0 && 1859 (r = hostfile_replace_entries(options.user_hostfiles[0], 1860 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys, 1861 options.hash_known_hosts, 0, 1862 options.fingerprint_hash)) != 0) 1863 error("%s: hostfile_replace_entries failed: %s", 1864 __func__, ssh_err(r)); 1865 } 1866 1867 static void 1868 client_global_hostkeys_private_confirm(struct ssh *ssh, int type, 1869 u_int32_t seq, void *_ctx) 1870 { 1871 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx; 1872 size_t i, ndone; 1873 struct sshbuf *signdata; 1874 int r, kexsigtype, use_kexsigtype; 1875 const u_char *sig; 1876 size_t siglen; 1877 1878 if (ctx->nnew == 0) 1879 fatal("%s: ctx->nnew == 0", __func__); /* sanity */ 1880 if (type != SSH2_MSG_REQUEST_SUCCESS) { 1881 error("Server failed to confirm ownership of " 1882 "private host keys"); 1883 hostkeys_update_ctx_free(ctx); 1884 return; 1885 } 1886 kexsigtype = sshkey_type_plain( 1887 sshkey_type_from_name(ssh->kex->hostkey_alg)); 1888 1889 if ((signdata = sshbuf_new()) == NULL) 1890 fatal("%s: sshbuf_new failed", __func__); 1891 /* Don't want to accidentally accept an unbound signature */ 1892 if (ssh->kex->session_id_len == 0) 1893 fatal("%s: ssh->kex->session_id_len == 0", __func__); 1894 /* 1895 * Expect a signature for each of the ctx->nnew private keys we 1896 * haven't seen before. They will be in the same order as the 1897 * ctx->keys where the corresponding ctx->keys_seen[i] == 0. 1898 */ 1899 for (ndone = i = 0; i < ctx->nkeys; i++) { 1900 if (ctx->keys_seen[i]) 1901 continue; 1902 /* Prepare data to be signed: session ID, unique string, key */ 1903 sshbuf_reset(signdata); 1904 if ( (r = sshbuf_put_cstring(signdata, 1905 "hostkeys-prove-00@openssh.com")) != 0 || 1906 (r = sshbuf_put_string(signdata, ssh->kex->session_id, 1907 ssh->kex->session_id_len)) != 0 || 1908 (r = sshkey_puts(ctx->keys[i], signdata)) != 0) 1909 fatal("%s: failed to prepare signature: %s", 1910 __func__, ssh_err(r)); 1911 /* Extract and verify signature */ 1912 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) { 1913 error("%s: couldn't parse message: %s", 1914 __func__, ssh_err(r)); 1915 goto out; 1916 } 1917 /* 1918 * For RSA keys, prefer to use the signature type negotiated 1919 * during KEX to the default (SHA1). 1920 */ 1921 use_kexsigtype = kexsigtype == KEY_RSA && 1922 sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA; 1923 if ((r = sshkey_verify(ctx->keys[i], sig, siglen, 1924 sshbuf_ptr(signdata), sshbuf_len(signdata), 1925 use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0)) != 0) { 1926 error("%s: server gave bad signature for %s key %zu", 1927 __func__, sshkey_type(ctx->keys[i]), i); 1928 goto out; 1929 } 1930 /* Key is good. Mark it as 'seen' */ 1931 ctx->keys_seen[i] = 2; 1932 ndone++; 1933 } 1934 if (ndone != ctx->nnew) 1935 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__, 1936 ndone, ctx->nnew); /* Shouldn't happen */ 1937 ssh_packet_check_eom(ssh); 1938 1939 /* Make the edits to known_hosts */ 1940 update_known_hosts(ctx); 1941 out: 1942 hostkeys_update_ctx_free(ctx); 1943 } 1944 1945 /* 1946 * Returns non-zero if the key is accepted by HostkeyAlgorithms. 1947 * Made slightly less trivial by the multiple RSA signature algorithm names. 1948 */ 1949 static int 1950 key_accepted_by_hostkeyalgs(const struct sshkey *key) 1951 { 1952 const char *ktype = sshkey_ssh_name(key); 1953 const char *hostkeyalgs = options.hostkeyalgorithms != NULL ? 1954 options.hostkeyalgorithms : KEX_DEFAULT_PK_ALG; 1955 1956 if (key == NULL || key->type == KEY_UNSPEC) 1957 return 0; 1958 if (key->type == KEY_RSA && 1959 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 || 1960 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1)) 1961 return 1; 1962 return match_pattern_list(ktype, hostkeyalgs, 0) == 1; 1963 } 1964 1965 /* 1966 * Handle hostkeys-00@openssh.com global request to inform the client of all 1967 * the server's hostkeys. The keys are checked against the user's 1968 * HostkeyAlgorithms preference before they are accepted. 1969 */ 1970 static int 1971 client_input_hostkeys(void) 1972 { 1973 struct ssh *ssh = active_state; /* XXX */ 1974 const u_char *blob = NULL; 1975 size_t i, len = 0; 1976 struct sshbuf *buf = NULL; 1977 struct sshkey *key = NULL, **tmp; 1978 int r; 1979 char *fp; 1980 static int hostkeys_seen = 0; /* XXX use struct ssh */ 1981 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */ 1982 struct hostkeys_update_ctx *ctx = NULL; 1983 1984 if (hostkeys_seen) 1985 fatal("%s: server already sent hostkeys", __func__); 1986 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK && 1987 options.batch_mode) 1988 return 1; /* won't ask in batchmode, so don't even try */ 1989 if (!options.update_hostkeys || options.num_user_hostfiles <= 0) 1990 return 1; 1991 1992 ctx = xcalloc(1, sizeof(*ctx)); 1993 while (ssh_packet_remaining(ssh) > 0) { 1994 sshkey_free(key); 1995 key = NULL; 1996 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) { 1997 error("%s: couldn't parse message: %s", 1998 __func__, ssh_err(r)); 1999 goto out; 2000 } 2001 if ((r = sshkey_from_blob(blob, len, &key)) != 0) { 2002 error("%s: parse key: %s", __func__, ssh_err(r)); 2003 goto out; 2004 } 2005 fp = sshkey_fingerprint(key, options.fingerprint_hash, 2006 SSH_FP_DEFAULT); 2007 debug3("%s: received %s key %s", __func__, 2008 sshkey_type(key), fp); 2009 free(fp); 2010 2011 if (!key_accepted_by_hostkeyalgs(key)) { 2012 debug3("%s: %s key not permitted by HostkeyAlgorithms", 2013 __func__, sshkey_ssh_name(key)); 2014 continue; 2015 } 2016 /* Skip certs */ 2017 if (sshkey_is_cert(key)) { 2018 debug3("%s: %s key is a certificate; skipping", 2019 __func__, sshkey_ssh_name(key)); 2020 continue; 2021 } 2022 /* Ensure keys are unique */ 2023 for (i = 0; i < ctx->nkeys; i++) { 2024 if (sshkey_equal(key, ctx->keys[i])) { 2025 error("%s: received duplicated %s host key", 2026 __func__, sshkey_ssh_name(key)); 2027 goto out; 2028 } 2029 } 2030 /* Key is good, record it */ 2031 if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1, 2032 sizeof(*ctx->keys))) == NULL) 2033 fatal("%s: recallocarray failed nkeys = %zu", 2034 __func__, ctx->nkeys); 2035 ctx->keys = tmp; 2036 ctx->keys[ctx->nkeys++] = key; 2037 key = NULL; 2038 } 2039 2040 if (ctx->nkeys == 0) { 2041 debug("%s: server sent no hostkeys", __func__); 2042 goto out; 2043 } 2044 2045 if ((ctx->keys_seen = calloc(ctx->nkeys, 2046 sizeof(*ctx->keys_seen))) == NULL) 2047 fatal("%s: calloc failed", __func__); 2048 2049 get_hostfile_hostname_ipaddr(host, 2050 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL, 2051 options.port, &ctx->host_str, 2052 options.check_host_ip ? &ctx->ip_str : NULL); 2053 2054 /* Find which keys we already know about. */ 2055 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find, 2056 ctx, ctx->host_str, ctx->ip_str, 2057 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) { 2058 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r)); 2059 goto out; 2060 } 2061 2062 /* Figure out if we have any new keys to add */ 2063 ctx->nnew = 0; 2064 for (i = 0; i < ctx->nkeys; i++) { 2065 if (!ctx->keys_seen[i]) 2066 ctx->nnew++; 2067 } 2068 2069 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove", 2070 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold); 2071 2072 if (ctx->nnew == 0 && ctx->nold != 0) { 2073 /* We have some keys to remove. Just do it. */ 2074 update_known_hosts(ctx); 2075 } else if (ctx->nnew != 0) { 2076 /* 2077 * We have received hitherto-unseen keys from the server. 2078 * Ask the server to confirm ownership of the private halves. 2079 */ 2080 debug3("%s: asking server to prove ownership for %zu keys", 2081 __func__, ctx->nnew); 2082 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 2083 (r = sshpkt_put_cstring(ssh, 2084 "hostkeys-prove-00@openssh.com")) != 0 || 2085 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */ 2086 fatal("%s: cannot prepare packet: %s", 2087 __func__, ssh_err(r)); 2088 if ((buf = sshbuf_new()) == NULL) 2089 fatal("%s: sshbuf_new", __func__); 2090 for (i = 0; i < ctx->nkeys; i++) { 2091 if (ctx->keys_seen[i]) 2092 continue; 2093 sshbuf_reset(buf); 2094 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0) 2095 fatal("%s: sshkey_putb: %s", 2096 __func__, ssh_err(r)); 2097 if ((r = sshpkt_put_stringb(ssh, buf)) != 0) 2098 fatal("%s: sshpkt_put_string: %s", 2099 __func__, ssh_err(r)); 2100 } 2101 if ((r = sshpkt_send(ssh)) != 0) 2102 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r)); 2103 client_register_global_confirm( 2104 client_global_hostkeys_private_confirm, ctx); 2105 ctx = NULL; /* will be freed in callback */ 2106 } 2107 2108 /* Success */ 2109 out: 2110 hostkeys_update_ctx_free(ctx); 2111 sshkey_free(key); 2112 sshbuf_free(buf); 2113 /* 2114 * NB. Return success for all cases. The server doesn't need to know 2115 * what the client does with its hosts file. 2116 */ 2117 return 1; 2118 } 2119 2120 static int 2121 client_input_global_request(int type, u_int32_t seq, struct ssh *ssh) 2122 { 2123 char *rtype; 2124 int want_reply; 2125 int success = 0; 2126 2127 rtype = packet_get_cstring(NULL); 2128 want_reply = packet_get_char(); 2129 debug("client_input_global_request: rtype %s want_reply %d", 2130 rtype, want_reply); 2131 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0) 2132 success = client_input_hostkeys(); 2133 if (want_reply) { 2134 packet_start(success ? 2135 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE); 2136 packet_send(); 2137 packet_write_wait(); 2138 } 2139 free(rtype); 2140 return 0; 2141 } 2142 2143 void 2144 client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem, 2145 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env) 2146 { 2147 int len; 2148 Channel *c = NULL; 2149 2150 debug2("%s: id %d", __func__, id); 2151 2152 if ((c = channel_lookup(ssh, id)) == NULL) 2153 fatal("%s: channel %d: unknown channel", __func__, id); 2154 2155 packet_set_interactive(want_tty, 2156 options.ip_qos_interactive, options.ip_qos_bulk); 2157 2158 if (want_tty) { 2159 struct winsize ws; 2160 2161 /* Store window size in the packet. */ 2162 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0) 2163 memset(&ws, 0, sizeof(ws)); 2164 2165 channel_request_start(ssh, id, "pty-req", 1); 2166 client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY); 2167 packet_put_cstring(term != NULL ? term : ""); 2168 packet_put_int((u_int)ws.ws_col); 2169 packet_put_int((u_int)ws.ws_row); 2170 packet_put_int((u_int)ws.ws_xpixel); 2171 packet_put_int((u_int)ws.ws_ypixel); 2172 if (tiop == NULL) 2173 tiop = get_saved_tio(); 2174 tty_make_modes(-1, tiop); 2175 packet_send(); 2176 /* XXX wait for reply */ 2177 c->client_tty = 1; 2178 } 2179 2180 /* Transfer any environment variables from client to server */ 2181 if (options.num_send_env != 0 && env != NULL) { 2182 int i, j, matched; 2183 char *name, *val; 2184 2185 debug("Sending environment."); 2186 for (i = 0; env[i] != NULL; i++) { 2187 /* Split */ 2188 name = xstrdup(env[i]); 2189 if ((val = strchr(name, '=')) == NULL) { 2190 free(name); 2191 continue; 2192 } 2193 *val++ = '\0'; 2194 2195 matched = 0; 2196 for (j = 0; j < options.num_send_env; j++) { 2197 if (match_pattern(name, options.send_env[j])) { 2198 matched = 1; 2199 break; 2200 } 2201 } 2202 if (!matched) { 2203 debug3("Ignored env %s", name); 2204 free(name); 2205 continue; 2206 } 2207 2208 debug("Sending env %s = %s", name, val); 2209 channel_request_start(ssh, id, "env", 0); 2210 packet_put_cstring(name); 2211 packet_put_cstring(val); 2212 packet_send(); 2213 free(name); 2214 } 2215 } 2216 2217 len = buffer_len(cmd); 2218 if (len > 0) { 2219 if (len > 900) 2220 len = 900; 2221 if (want_subsystem) { 2222 debug("Sending subsystem: %.*s", 2223 len, (u_char*)buffer_ptr(cmd)); 2224 channel_request_start(ssh, id, "subsystem", 1); 2225 client_expect_confirm(ssh, id, "subsystem", 2226 CONFIRM_CLOSE); 2227 } else { 2228 debug("Sending command: %.*s", 2229 len, (u_char*)buffer_ptr(cmd)); 2230 channel_request_start(ssh, id, "exec", 1); 2231 client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE); 2232 } 2233 packet_put_string(buffer_ptr(cmd), buffer_len(cmd)); 2234 packet_send(); 2235 } else { 2236 channel_request_start(ssh, id, "shell", 1); 2237 client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE); 2238 packet_send(); 2239 } 2240 } 2241 2242 static void 2243 client_init_dispatch(void) 2244 { 2245 dispatch_init(&dispatch_protocol_error); 2246 2247 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 2248 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data); 2249 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof); 2250 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data); 2251 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open); 2252 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 2253 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 2254 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req); 2255 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust); 2256 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm); 2257 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm); 2258 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request); 2259 2260 /* rekeying */ 2261 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit); 2262 2263 /* global request reply messages */ 2264 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply); 2265 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply); 2266 } 2267 2268 void 2269 client_stop_mux(void) 2270 { 2271 if (options.control_path != NULL && muxserver_sock != -1) 2272 unlink(options.control_path); 2273 /* 2274 * If we are in persist mode, or don't have a shell, signal that we 2275 * should close when all active channels are closed. 2276 */ 2277 if (options.control_persist || no_shell_flag) { 2278 session_closed = 1; 2279 setproctitle("[stopped mux]"); 2280 } 2281 } 2282 2283 /* client specific fatal cleanup */ 2284 void 2285 cleanup_exit(int i) 2286 { 2287 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 2288 leave_non_blocking(); 2289 if (options.control_path != NULL && muxserver_sock != -1) 2290 unlink(options.control_path); 2291 ssh_kill_proxy_command(); 2292 _exit(i); 2293 } 2294