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