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