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