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