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