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