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