1 /* $NetBSD: clientloop.c,v 1.8 2012/12/12 17:42:39 christos Exp $ */ 2 /* $OpenBSD: clientloop.c,v 1.240 2012/06/20 04:42:58 djm Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * The main loop for the interactive session (client side). 8 * 9 * As far as I am concerned, the code I have written for this software 10 * can be used freely for any purpose. Any derived versions of this 11 * software must be clearly marked as such, and if the derived work is 12 * incompatible with the protocol description in the RFC file, it must be 13 * called by a name other than "ssh" or "Secure Shell". 14 * 15 * 16 * Copyright (c) 1999 Theo de Raadt. All rights reserved. 17 * 18 * Redistribution and use in source and binary forms, with or without 19 * modification, are permitted provided that the following conditions 20 * are met: 21 * 1. Redistributions of source code must retain the above copyright 22 * notice, this list of conditions and the following disclaimer. 23 * 2. Redistributions in binary form must reproduce the above copyright 24 * notice, this list of conditions and the following disclaimer in the 25 * documentation and/or other materials provided with the distribution. 26 * 27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 37 * 38 * 39 * SSH2 support added by Markus Friedl. 40 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved. 41 * 42 * Redistribution and use in source and binary forms, with or without 43 * modification, are permitted provided that the following conditions 44 * are met: 45 * 1. Redistributions of source code must retain the above copyright 46 * notice, this list of conditions and the following disclaimer. 47 * 2. Redistributions in binary form must reproduce the above copyright 48 * notice, this list of conditions and the following disclaimer in the 49 * documentation and/or other materials provided with the distribution. 50 * 51 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 52 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 53 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 54 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 55 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 56 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 57 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 58 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 59 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 60 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 61 */ 62 63 #include "includes.h" 64 __RCSID("$NetBSD: clientloop.c,v 1.8 2012/12/12 17:42:39 christos Exp $"); 65 #include <sys/types.h> 66 #include <sys/ioctl.h> 67 #include <sys/stat.h> 68 #include <sys/socket.h> 69 #include <sys/time.h> 70 #include <sys/param.h> 71 #include <sys/queue.h> 72 73 #include <ctype.h> 74 #include <errno.h> 75 #include <paths.h> 76 #include <signal.h> 77 #include <stdio.h> 78 #include <stdlib.h> 79 #include <string.h> 80 #include <termios.h> 81 #include <pwd.h> 82 #include <unistd.h> 83 84 #include "xmalloc.h" 85 #include "ssh.h" 86 #include "ssh1.h" 87 #include "ssh2.h" 88 #include "packet.h" 89 #include "buffer.h" 90 #include "compat.h" 91 #include "channels.h" 92 #include "dispatch.h" 93 #include "key.h" 94 #include "cipher.h" 95 #include "kex.h" 96 #include "log.h" 97 #include "readconf.h" 98 #include "clientloop.h" 99 #include "sshconnect.h" 100 #include "authfd.h" 101 #include "atomicio.h" 102 #include "sshpty.h" 103 #include "misc.h" 104 #include "match.h" 105 #include "msg.h" 106 #include "roaming.h" 107 #include "getpeereid.h" 108 109 /* import options */ 110 extern Options options; 111 112 /* Flag indicating that stdin should be redirected from /dev/null. */ 113 extern int stdin_null_flag; 114 115 /* Flag indicating that no shell has been requested */ 116 extern int no_shell_flag; 117 118 /* Control socket */ 119 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */ 120 121 /* 122 * Name of the host we are connecting to. This is the name given on the 123 * command line, or the HostName specified for the user-supplied name in a 124 * configuration file. 125 */ 126 extern char *host; 127 128 /* 129 * Flag to indicate that we have received a window change signal which has 130 * not yet been processed. This will cause a message indicating the new 131 * window size to be sent to the server a little later. This is volatile 132 * because this is updated in a signal handler. 133 */ 134 static volatile sig_atomic_t received_window_change_signal = 0; 135 static volatile sig_atomic_t received_signal = 0; 136 137 /* Flag indicating whether the user's terminal is in non-blocking mode. */ 138 static int in_non_blocking_mode = 0; 139 140 /* Time when backgrounded control master using ControlPersist should exit */ 141 static time_t control_persist_exit_time = 0; 142 143 /* Common data for the client loop code. */ 144 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */ 145 static int escape_char1; /* Escape character. (proto1 only) */ 146 static int escape_pending1; /* Last character was an escape (proto1 only) */ 147 static int last_was_cr; /* Last character was a newline. */ 148 static int exit_status; /* Used to store the command exit status. */ 149 static int stdin_eof; /* EOF has been encountered on stderr. */ 150 static Buffer stdin_buffer; /* Buffer for stdin data. */ 151 static Buffer stdout_buffer; /* Buffer for stdout data. */ 152 static Buffer stderr_buffer; /* Buffer for stderr data. */ 153 static u_int buffer_high; /* Soft max buffer size. */ 154 static int connection_in; /* Connection to server (input). */ 155 static int connection_out; /* Connection to server (output). */ 156 static int need_rekeying; /* Set to non-zero if rekeying is requested. */ 157 static int session_closed; /* In SSH2: login session closed. */ 158 static int x11_refuse_time; /* If >0, refuse x11 opens after this time. */ 159 160 static void client_init_dispatch(void); 161 int session_ident = -1; 162 163 int session_resumed = 0; 164 165 /* Track escape per proto2 channel */ 166 struct escape_filter_ctx { 167 int escape_pending; 168 int escape_char; 169 }; 170 171 /* Context for channel confirmation replies */ 172 struct channel_reply_ctx { 173 const char *request_type; 174 int id; 175 enum confirm_action action; 176 }; 177 178 /* Global request success/failure callbacks */ 179 struct global_confirm { 180 TAILQ_ENTRY(global_confirm) entry; 181 global_confirm_cb *cb; 182 void *ctx; 183 int ref_count; 184 }; 185 TAILQ_HEAD(global_confirms, global_confirm); 186 static struct global_confirms global_confirms = 187 TAILQ_HEAD_INITIALIZER(global_confirms); 188 189 /*XXX*/ 190 extern Kex *xxx_kex; 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 = time(NULL) + 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 dlen = strlen(display); 286 for (i = 0; i < dlen; i++) { 287 if (!isalnum((unsigned char)display[i]) && 288 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) { 289 debug("Invalid character '%c' in DISPLAY", display[i]); 290 return 0; 291 } 292 } 293 return 1; 294 } 295 296 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1" 297 void 298 client_x11_get_proto(const char *display, const char *xauth_path, 299 u_int trusted, u_int timeout, char **_proto, char **_data) 300 { 301 char cmd[1024]; 302 char line[512]; 303 char xdisplay[512]; 304 static char proto[512], data[512]; 305 FILE *f; 306 int got_data = 0, generated = 0, do_unlink = 0, i; 307 char *xauthdir, *xauthfile; 308 struct stat st; 309 u_int now; 310 311 xauthdir = xauthfile = NULL; 312 *_proto = proto; 313 *_data = data; 314 proto[0] = data[0] = '\0'; 315 316 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) { 317 debug("No xauth program."); 318 } else if (!client_x11_display_valid(display)) { 319 logit("DISPLAY '%s' invalid, falling back to fake xauth data", 320 display); 321 } else { 322 if (display == NULL) { 323 debug("x11_get_proto: DISPLAY not set"); 324 return; 325 } 326 /* 327 * Handle FamilyLocal case where $DISPLAY does 328 * not match an authorization entry. For this we 329 * just try "xauth list unix:displaynum.screennum". 330 * XXX: "localhost" match to determine FamilyLocal 331 * is not perfect. 332 */ 333 if (strncmp(display, "localhost:", 10) == 0) { 334 snprintf(xdisplay, sizeof(xdisplay), "unix:%s", 335 display + 10); 336 display = xdisplay; 337 } 338 if (trusted == 0) { 339 xauthdir = xmalloc(MAXPATHLEN); 340 xauthfile = xmalloc(MAXPATHLEN); 341 mktemp_proto(xauthdir, MAXPATHLEN); 342 if (mkdtemp(xauthdir) != NULL) { 343 do_unlink = 1; 344 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile", 345 xauthdir); 346 snprintf(cmd, sizeof(cmd), 347 "%s -f %s generate %s " SSH_X11_PROTO 348 " untrusted timeout %u 2>" _PATH_DEVNULL, 349 xauth_path, xauthfile, display, timeout); 350 debug2("x11_get_proto: %s", cmd); 351 if (system(cmd) == 0) 352 generated = 1; 353 if (x11_refuse_time == 0) { 354 now = time(NULL) + 1; 355 if (UINT_MAX - timeout < now) 356 x11_refuse_time = UINT_MAX; 357 else 358 x11_refuse_time = now + timeout; 359 } 360 } 361 } 362 363 /* 364 * When in untrusted mode, we read the cookie only if it was 365 * successfully generated as an untrusted one in the step 366 * above. 367 */ 368 if (trusted || generated) { 369 snprintf(cmd, sizeof(cmd), 370 "%s %s%s list %s 2>" _PATH_DEVNULL, 371 xauth_path, 372 generated ? "-f " : "" , 373 generated ? xauthfile : "", 374 display); 375 debug2("x11_get_proto: %s", cmd); 376 f = popen(cmd, "r"); 377 if (f && fgets(line, sizeof(line), f) && 378 sscanf(line, "%*s %511s %511s", proto, data) == 2) 379 got_data = 1; 380 if (f) 381 pclose(f); 382 } else 383 error("Warning: untrusted X11 forwarding setup failed: " 384 "xauth key data not generated"); 385 } 386 387 if (do_unlink) { 388 unlink(xauthfile); 389 rmdir(xauthdir); 390 } 391 if (xauthdir) 392 xfree(xauthdir); 393 if (xauthfile) 394 xfree(xauthfile); 395 396 /* 397 * If we didn't get authentication data, just make up some 398 * data. The forwarding code will check the validity of the 399 * response anyway, and substitute this data. The X11 400 * server, however, will ignore this fake data and use 401 * whatever authentication mechanisms it was using otherwise 402 * for the local connection. 403 */ 404 if (!got_data) { 405 u_int32_t rnd = 0; 406 407 logit("Warning: No xauth data; " 408 "using fake authentication data for X11 forwarding."); 409 strlcpy(proto, SSH_X11_PROTO, sizeof proto); 410 for (i = 0; i < 16; i++) { 411 if (i % 4 == 0) 412 rnd = arc4random(); 413 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", 414 rnd & 0xff); 415 rnd >>= 8; 416 } 417 } 418 } 419 420 /* 421 * This is called when the interactive is entered. This checks if there is 422 * an EOF coming on stdin. We must check this explicitly, as select() does 423 * not appear to wake up when redirecting from /dev/null. 424 */ 425 426 static void 427 client_check_initial_eof_on_stdin(void) 428 { 429 int len; 430 char buf[1]; 431 432 /* 433 * If standard input is to be "redirected from /dev/null", we simply 434 * mark that we have seen an EOF and send an EOF message to the 435 * server. Otherwise, we try to read a single character; it appears 436 * that for some files, such /dev/null, select() never wakes up for 437 * read for this descriptor, which means that we never get EOF. This 438 * way we will get the EOF if stdin comes from /dev/null or similar. 439 */ 440 if (stdin_null_flag) { 441 /* Fake EOF on stdin. */ 442 debug("Sending eof."); 443 stdin_eof = 1; 444 packet_start(SSH_CMSG_EOF); 445 packet_send(); 446 } else { 447 enter_non_blocking(); 448 449 /* Check for immediate EOF on stdin. */ 450 len = read(fileno(stdin), buf, 1); 451 if (len == 0) { 452 /* 453 * EOF. Record that we have seen it and send 454 * EOF to server. 455 */ 456 debug("Sending eof."); 457 stdin_eof = 1; 458 packet_start(SSH_CMSG_EOF); 459 packet_send(); 460 } else if (len > 0) { 461 /* 462 * Got data. We must store the data in the buffer, 463 * and also process it as an escape character if 464 * appropriate. 465 */ 466 if ((u_char) buf[0] == escape_char1) 467 escape_pending1 = 1; 468 else 469 buffer_append(&stdin_buffer, buf, 1); 470 } 471 leave_non_blocking(); 472 } 473 } 474 475 476 /* 477 * Make packets from buffered stdin data, and buffer them for sending to the 478 * connection. 479 */ 480 481 static void 482 client_make_packets_from_stdin_data(void) 483 { 484 u_int len; 485 486 /* Send buffered stdin data to the server. */ 487 while (buffer_len(&stdin_buffer) > 0 && 488 packet_not_very_much_data_to_write()) { 489 len = buffer_len(&stdin_buffer); 490 /* Keep the packets at reasonable size. */ 491 if (len > packet_get_maxsize()) 492 len = packet_get_maxsize(); 493 packet_start(SSH_CMSG_STDIN_DATA); 494 packet_put_string(buffer_ptr(&stdin_buffer), len); 495 packet_send(); 496 buffer_consume(&stdin_buffer, len); 497 /* If we have a pending EOF, send it now. */ 498 if (stdin_eof && buffer_len(&stdin_buffer) == 0) { 499 packet_start(SSH_CMSG_EOF); 500 packet_send(); 501 } 502 } 503 } 504 505 /* 506 * Checks if the client window has changed, and sends a packet about it to 507 * the server if so. The actual change is detected elsewhere (by a software 508 * interrupt on Unix); this just checks the flag and sends a message if 509 * appropriate. 510 */ 511 512 static void 513 client_check_window_change(void) 514 { 515 struct winsize ws; 516 517 if (! received_window_change_signal) 518 return; 519 /** XXX race */ 520 received_window_change_signal = 0; 521 522 debug2("client_check_window_change: changed"); 523 524 if (compat20) { 525 channel_send_window_changes(); 526 } else { 527 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) 528 return; 529 packet_start(SSH_CMSG_WINDOW_SIZE); 530 packet_put_int((u_int)ws.ws_row); 531 packet_put_int((u_int)ws.ws_col); 532 packet_put_int((u_int)ws.ws_xpixel); 533 packet_put_int((u_int)ws.ws_ypixel); 534 packet_send(); 535 } 536 } 537 538 static void 539 client_global_request_reply(int type, u_int32_t seq, void *ctxt) 540 { 541 struct global_confirm *gc; 542 543 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL) 544 return; 545 if (gc->cb != NULL) 546 gc->cb(type, seq, gc->ctx); 547 if (--gc->ref_count <= 0) { 548 TAILQ_REMOVE(&global_confirms, gc, entry); 549 bzero(gc, sizeof(*gc)); 550 xfree(gc); 551 } 552 553 packet_set_alive_timeouts(0); 554 } 555 556 static void 557 server_alive_check(void) 558 { 559 if (packet_inc_alive_timeouts() > options.server_alive_count_max) { 560 logit("Timeout, server %s not responding.", host); 561 cleanup_exit(255); 562 } 563 packet_start(SSH2_MSG_GLOBAL_REQUEST); 564 packet_put_cstring("keepalive@openssh.com"); 565 packet_put_char(1); /* boolean: want reply */ 566 packet_send(); 567 /* Insert an empty placeholder to maintain ordering */ 568 client_register_global_confirm(NULL, NULL); 569 } 570 571 /* 572 * Waits until the client can do something (some data becomes available on 573 * one of the file descriptors). 574 */ 575 static void 576 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, 577 int *maxfdp, u_int *nallocp, int rekeying) 578 { 579 struct timeval tv, *tvp; 580 int timeout_secs; 581 time_t minwait_secs = 0; 582 int ret; 583 584 /* Add any selections by the channel mechanism. */ 585 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 586 &minwait_secs, rekeying); 587 588 if (!compat20) { 589 /* Read from the connection, unless our buffers are full. */ 590 if (buffer_len(&stdout_buffer) < buffer_high && 591 buffer_len(&stderr_buffer) < buffer_high && 592 channel_not_very_much_buffered_data()) 593 FD_SET(connection_in, *readsetp); 594 /* 595 * Read from stdin, unless we have seen EOF or have very much 596 * buffered data to send to the server. 597 */ 598 if (!stdin_eof && packet_not_very_much_data_to_write()) 599 if ((ret = fileno(stdin)) != -1) 600 FD_SET(ret, *readsetp); 601 602 /* Select stdout/stderr if have data in buffer. */ 603 if (buffer_len(&stdout_buffer) > 0) 604 if ((ret = fileno(stdout)) != -1) 605 FD_SET(ret, *writesetp); 606 if (buffer_len(&stderr_buffer) > 0) 607 if ((ret = fileno(stderr)) != -1) 608 FD_SET(ret, *writesetp); 609 } else { 610 /* channel_prepare_select could have closed the last channel */ 611 if (session_closed && !channel_still_open() && 612 !packet_have_data_to_write()) { 613 /* clear mask since we did not call select() */ 614 memset(*readsetp, 0, *nallocp); 615 memset(*writesetp, 0, *nallocp); 616 return; 617 } else { 618 FD_SET(connection_in, *readsetp); 619 } 620 } 621 622 /* Select server connection if have data to write to the server. */ 623 if (packet_have_data_to_write()) 624 FD_SET(connection_out, *writesetp); 625 626 /* 627 * Wait for something to happen. This will suspend the process until 628 * some selected descriptor can be read, written, or has some other 629 * event pending, or a timeout expires. 630 */ 631 632 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */ 633 if (options.server_alive_interval > 0 && compat20) 634 timeout_secs = options.server_alive_interval; 635 set_control_persist_exit_time(); 636 if (control_persist_exit_time > 0) { 637 timeout_secs = MIN(timeout_secs, 638 control_persist_exit_time - time(NULL)); 639 if (timeout_secs < 0) 640 timeout_secs = 0; 641 } 642 if (minwait_secs != 0) 643 timeout_secs = MIN(timeout_secs, (int)minwait_secs); 644 if (timeout_secs == INT_MAX) 645 tvp = NULL; 646 else { 647 tv.tv_sec = timeout_secs; 648 tv.tv_usec = 0; 649 tvp = &tv; 650 } 651 652 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp); 653 if (ret < 0) { 654 char buf[100]; 655 656 /* 657 * We have to clear the select masks, because we return. 658 * We have to return, because the mainloop checks for the flags 659 * set by the signal handlers. 660 */ 661 memset(*readsetp, 0, *nallocp); 662 memset(*writesetp, 0, *nallocp); 663 664 if (errno == EINTR) 665 return; 666 /* Note: we might still have data in the buffers. */ 667 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno)); 668 buffer_append(&stderr_buffer, buf, strlen(buf)); 669 quit_pending = 1; 670 } else if (ret == 0) 671 server_alive_check(); 672 } 673 674 static void 675 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr) 676 { 677 /* Flush stdout and stderr buffers. */ 678 if (buffer_len(bout) > 0) 679 atomicio(vwrite, fileno(stdout), buffer_ptr(bout), 680 buffer_len(bout)); 681 if (buffer_len(berr) > 0) 682 atomicio(vwrite, fileno(stderr), buffer_ptr(berr), 683 buffer_len(berr)); 684 685 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 686 687 /* 688 * Free (and clear) the buffer to reduce the amount of data that gets 689 * written to swap. 690 */ 691 buffer_free(bin); 692 buffer_free(bout); 693 buffer_free(berr); 694 695 /* Send the suspend signal to the program itself. */ 696 kill(getpid(), SIGTSTP); 697 698 /* Reset window sizes in case they have changed */ 699 received_window_change_signal = 1; 700 701 /* OK, we have been continued by the user. Reinitialize buffers. */ 702 buffer_init(bin); 703 buffer_init(bout); 704 buffer_init(berr); 705 706 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 707 } 708 709 static void 710 client_process_net_input(fd_set *readset) 711 { 712 int len, cont = 0; 713 char buf[8192]; 714 715 /* 716 * Read input from the server, and add any such data to the buffer of 717 * the packet subsystem. 718 */ 719 if (FD_ISSET(connection_in, readset)) { 720 /* Read as much as possible. */ 721 len = roaming_read(connection_in, buf, sizeof(buf), &cont); 722 if (len == 0 && cont == 0) { 723 /* 724 * Received EOF. The remote host has closed the 725 * connection. 726 */ 727 snprintf(buf, sizeof buf, 728 "Connection to %.300s closed by remote host.\r\n", 729 host); 730 buffer_append(&stderr_buffer, buf, strlen(buf)); 731 quit_pending = 1; 732 return; 733 } 734 /* 735 * There is a kernel bug on Solaris that causes select to 736 * sometimes wake up even though there is no data available. 737 */ 738 if (len < 0 && (errno == EAGAIN || errno == EINTR)) 739 len = 0; 740 741 if (len < 0) { 742 /* 743 * An error has encountered. Perhaps there is a 744 * network problem. 745 */ 746 snprintf(buf, sizeof buf, 747 "Read from remote host %.300s: %.100s\r\n", 748 host, strerror(errno)); 749 buffer_append(&stderr_buffer, buf, strlen(buf)); 750 quit_pending = 1; 751 return; 752 } 753 packet_process_incoming(buf, len); 754 } 755 } 756 757 static void 758 client_status_confirm(int type, Channel *c, void *ctx) 759 { 760 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx; 761 char errmsg[256]; 762 int tochan; 763 764 /* 765 * If a TTY was explicitly requested, then a failure to allocate 766 * one is fatal. 767 */ 768 if (cr->action == CONFIRM_TTY && 769 (options.request_tty == REQUEST_TTY_FORCE || 770 options.request_tty == REQUEST_TTY_YES)) 771 cr->action = CONFIRM_CLOSE; 772 773 /* XXX supress on mux _client_ quietmode */ 774 tochan = options.log_level >= SYSLOG_LEVEL_ERROR && 775 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE; 776 777 if (type == SSH2_MSG_CHANNEL_SUCCESS) { 778 debug2("%s request accepted on channel %d", 779 cr->request_type, c->self); 780 } else if (type == SSH2_MSG_CHANNEL_FAILURE) { 781 if (tochan) { 782 snprintf(errmsg, sizeof(errmsg), 783 "%s request failed\r\n", cr->request_type); 784 } else { 785 snprintf(errmsg, sizeof(errmsg), 786 "%s request failed on channel %d", 787 cr->request_type, c->self); 788 } 789 /* If error occurred on primary session channel, then exit */ 790 if (cr->action == CONFIRM_CLOSE && c->self == session_ident) 791 fatal("%s", errmsg); 792 /* 793 * If error occurred on mux client, append to 794 * their stderr. 795 */ 796 if (tochan) { 797 buffer_append(&c->extended, errmsg, 798 strlen(errmsg)); 799 } else 800 error("%s", errmsg); 801 if (cr->action == CONFIRM_TTY) { 802 /* 803 * If a TTY allocation error occurred, then arrange 804 * for the correct TTY to leave raw mode. 805 */ 806 if (c->self == session_ident) 807 leave_raw_mode(0); 808 else 809 mux_tty_alloc_failed(c); 810 } else if (cr->action == CONFIRM_CLOSE) { 811 chan_read_failed(c); 812 chan_write_failed(c); 813 } 814 } 815 xfree(cr); 816 } 817 818 static void 819 client_abandon_status_confirm(Channel *c, void *ctx) 820 { 821 xfree(ctx); 822 } 823 824 void 825 client_expect_confirm(int id, const char *request, 826 enum confirm_action action) 827 { 828 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr)); 829 830 cr->request_type = request; 831 cr->action = action; 832 833 channel_register_status_confirm(id, client_status_confirm, 834 client_abandon_status_confirm, cr); 835 } 836 837 void 838 client_register_global_confirm(global_confirm_cb *cb, void *ctx) 839 { 840 struct global_confirm *gc, *last_gc; 841 842 /* Coalesce identical callbacks */ 843 last_gc = TAILQ_LAST(&global_confirms, global_confirms); 844 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) { 845 if (++last_gc->ref_count >= INT_MAX) 846 fatal("%s: last_gc->ref_count = %d", 847 __func__, last_gc->ref_count); 848 return; 849 } 850 851 gc = xmalloc(sizeof(*gc)); 852 gc->cb = cb; 853 gc->ctx = ctx; 854 gc->ref_count = 1; 855 TAILQ_INSERT_TAIL(&global_confirms, gc, entry); 856 } 857 858 static void 859 process_cmdline(void) 860 { 861 void (*handler)(int); 862 char *s, *cmd, *cancel_host; 863 int delete = 0, local = 0, remote = 0, dynamic = 0; 864 int cancel_port, ok; 865 Forward fwd; 866 867 bzero(&fwd, sizeof(fwd)); 868 fwd.listen_host = fwd.connect_host = NULL; 869 870 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 871 handler = signal(SIGINT, SIG_IGN); 872 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO); 873 if (s == NULL) 874 goto out; 875 while (isspace((unsigned char)*s)) 876 s++; 877 if (*s == '-') 878 s++; /* Skip cmdline '-', if any */ 879 if (*s == '\0') 880 goto out; 881 882 if (*s == 'h' || *s == 'H' || *s == '?') { 883 logit("Commands:"); 884 logit(" -L[bind_address:]port:host:hostport " 885 "Request local forward"); 886 logit(" -R[bind_address:]port:host:hostport " 887 "Request remote forward"); 888 logit(" -D[bind_address:]port " 889 "Request dynamic forward"); 890 logit(" -KL[bind_address:]port " 891 "Cancel local forward"); 892 logit(" -KR[bind_address:]port " 893 "Cancel remote forward"); 894 logit(" -KD[bind_address:]port " 895 "Cancel dynamic forward"); 896 if (!options.permit_local_command) 897 goto out; 898 logit(" !args " 899 "Execute local command"); 900 goto out; 901 } 902 903 if (*s == '!' && options.permit_local_command) { 904 s++; 905 ssh_local_cmd(s); 906 goto out; 907 } 908 909 if (*s == 'K') { 910 delete = 1; 911 s++; 912 } 913 if (*s == 'L') 914 local = 1; 915 else if (*s == 'R') 916 remote = 1; 917 else if (*s == 'D') 918 dynamic = 1; 919 else { 920 logit("Invalid command."); 921 goto out; 922 } 923 924 if (delete && !compat20) { 925 logit("Not supported for SSH protocol version 1."); 926 goto out; 927 } 928 929 s++; 930 while (isspace((unsigned char)*s)) 931 s++; 932 933 /* XXX update list of forwards in options */ 934 if (delete) { 935 cancel_port = 0; 936 cancel_host = hpdelim(&s); /* may be NULL */ 937 if (s != NULL) { 938 cancel_port = a2port(s); 939 cancel_host = cleanhostname(cancel_host); 940 } else { 941 cancel_port = a2port(cancel_host); 942 cancel_host = NULL; 943 } 944 if (cancel_port <= 0) { 945 logit("Bad forwarding close port"); 946 goto out; 947 } 948 if (remote) 949 ok = channel_request_rforward_cancel(cancel_host, 950 cancel_port) == 0; 951 else if (dynamic) 952 ok = channel_cancel_lport_listener(cancel_host, 953 cancel_port, 0, options.gateway_ports) > 0; 954 else 955 ok = channel_cancel_lport_listener(cancel_host, 956 cancel_port, CHANNEL_CANCEL_PORT_STATIC, 957 options.gateway_ports) > 0; 958 if (!ok) { 959 logit("Unkown port forwarding."); 960 goto out; 961 } 962 logit("Canceled forwarding."); 963 } else { 964 if (!parse_forward(&fwd, s, dynamic, remote)) { 965 logit("Bad forwarding specification."); 966 goto out; 967 } 968 if (local || dynamic) { 969 if (channel_setup_local_fwd_listener(fwd.listen_host, 970 fwd.listen_port, fwd.connect_host, 971 fwd.connect_port, options.gateway_ports) < 0) { 972 logit("Port forwarding failed."); 973 goto out; 974 } 975 } else { 976 if (channel_request_remote_forwarding(fwd.listen_host, 977 fwd.listen_port, fwd.connect_host, 978 fwd.connect_port) < 0) { 979 logit("Port forwarding failed."); 980 goto out; 981 } 982 } 983 logit("Forwarding port."); 984 } 985 986 out: 987 signal(SIGINT, handler); 988 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 989 if (cmd) 990 xfree(cmd); 991 if (fwd.listen_host != NULL) 992 xfree(fwd.listen_host); 993 if (fwd.connect_host != NULL) 994 xfree(fwd.connect_host); 995 } 996 997 /* 998 * Process the characters one by one, call with c==NULL for proto1 case. 999 */ 1000 static int 1001 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr, 1002 const char *buf, int len) 1003 { 1004 char string[1024]; 1005 pid_t pid; 1006 int bytes = 0; 1007 u_int i; 1008 u_char ch; 1009 char *s; 1010 int *escape_pendingp, escape_char; 1011 struct escape_filter_ctx *efc; 1012 1013 if (c == NULL) { 1014 escape_pendingp = &escape_pending1; 1015 escape_char = escape_char1; 1016 } else { 1017 if (c->filter_ctx == NULL) 1018 return 0; 1019 efc = (struct escape_filter_ctx *)c->filter_ctx; 1020 escape_pendingp = &efc->escape_pending; 1021 escape_char = efc->escape_char; 1022 } 1023 1024 if (len <= 0) 1025 return (0); 1026 1027 for (i = 0; i < (u_int)len; i++) { 1028 /* Get one character at a time. */ 1029 ch = buf[i]; 1030 1031 if (*escape_pendingp) { 1032 /* We have previously seen an escape character. */ 1033 /* Clear the flag now. */ 1034 *escape_pendingp = 0; 1035 1036 /* Process the escaped character. */ 1037 switch (ch) { 1038 case '.': 1039 /* Terminate the connection. */ 1040 snprintf(string, sizeof string, "%c.\r\n", 1041 escape_char); 1042 buffer_append(berr, string, strlen(string)); 1043 1044 if (c && c->ctl_chan != -1) { 1045 chan_read_failed(c); 1046 chan_write_failed(c); 1047 return 0; 1048 } else 1049 quit_pending = 1; 1050 return -1; 1051 1052 case 'Z' - 64: 1053 /* XXX support this for mux clients */ 1054 if (c && c->ctl_chan != -1) { 1055 noescape: 1056 snprintf(string, sizeof string, 1057 "%c%c escape not available to " 1058 "multiplexed sessions\r\n", 1059 escape_char, ch); 1060 buffer_append(berr, string, 1061 strlen(string)); 1062 continue; 1063 } 1064 /* Suspend the program. Inform the user */ 1065 snprintf(string, sizeof string, 1066 "%c^Z [suspend ssh]\r\n", escape_char); 1067 buffer_append(berr, string, strlen(string)); 1068 1069 /* Restore terminal modes and suspend. */ 1070 client_suspend_self(bin, bout, berr); 1071 1072 /* We have been continued. */ 1073 continue; 1074 1075 case 'B': 1076 if (compat20) { 1077 snprintf(string, sizeof string, 1078 "%cB\r\n", escape_char); 1079 buffer_append(berr, string, 1080 strlen(string)); 1081 channel_request_start(session_ident, 1082 "break", 0); 1083 packet_put_int(1000); 1084 packet_send(); 1085 } 1086 continue; 1087 1088 case 'R': 1089 if (compat20) { 1090 if (datafellows & SSH_BUG_NOREKEY) 1091 logit("Server does not " 1092 "support re-keying"); 1093 else 1094 need_rekeying = 1; 1095 } 1096 continue; 1097 1098 case '&': 1099 if (c && c->ctl_chan != -1) 1100 goto noescape; 1101 /* 1102 * Detach the program (continue to serve 1103 * connections, but put in background and no 1104 * more new connections). 1105 */ 1106 /* Restore tty modes. */ 1107 leave_raw_mode( 1108 options.request_tty == REQUEST_TTY_FORCE); 1109 1110 /* Stop listening for new connections. */ 1111 channel_stop_listening(); 1112 1113 snprintf(string, sizeof string, 1114 "%c& [backgrounded]\n", escape_char); 1115 buffer_append(berr, string, strlen(string)); 1116 1117 /* Fork into background. */ 1118 pid = fork(); 1119 if (pid < 0) { 1120 error("fork: %.100s", strerror(errno)); 1121 continue; 1122 } 1123 if (pid != 0) { /* This is the parent. */ 1124 /* The parent just exits. */ 1125 exit(0); 1126 } 1127 /* The child continues serving connections. */ 1128 if (compat20) { 1129 buffer_append(bin, "\004", 1); 1130 /* fake EOF on stdin */ 1131 return -1; 1132 } else if (!stdin_eof) { 1133 /* 1134 * Sending SSH_CMSG_EOF alone does not 1135 * always appear to be enough. So we 1136 * try to send an EOF character first. 1137 */ 1138 packet_start(SSH_CMSG_STDIN_DATA); 1139 packet_put_string("\004", 1); 1140 packet_send(); 1141 /* Close stdin. */ 1142 stdin_eof = 1; 1143 if (buffer_len(bin) == 0) { 1144 packet_start(SSH_CMSG_EOF); 1145 packet_send(); 1146 } 1147 } 1148 continue; 1149 1150 case '?': 1151 if (c && c->ctl_chan != -1) { 1152 snprintf(string, sizeof string, 1153 "%c?\r\n\ 1154 Supported escape sequences:\r\n\ 1155 %c. - terminate session\r\n\ 1156 %cB - send a BREAK to the remote system\r\n\ 1157 %cR - Request rekey (SSH protocol 2 only)\r\n\ 1158 %c# - list forwarded connections\r\n\ 1159 %c? - this message\r\n\ 1160 %c%c - send the escape character by typing it twice\r\n\ 1161 (Note that escapes are only recognized immediately after newline.)\r\n", 1162 escape_char, escape_char, 1163 escape_char, escape_char, 1164 escape_char, escape_char, 1165 escape_char, escape_char); 1166 } else { 1167 snprintf(string, sizeof string, 1168 "%c?\r\n\ 1169 Supported escape sequences:\r\n\ 1170 %c. - terminate connection (and any multiplexed sessions)\r\n\ 1171 %cB - send a BREAK to the remote system\r\n\ 1172 %cC - open a command line\r\n\ 1173 %cR - Request rekey (SSH protocol 2 only)\r\n\ 1174 %c^Z - suspend ssh\r\n\ 1175 %c# - list forwarded connections\r\n\ 1176 %c& - background ssh (when waiting for connections to terminate)\r\n\ 1177 %c? - this message\r\n\ 1178 %c%c - send the escape character by typing it twice\r\n\ 1179 (Note that escapes are only recognized immediately after newline.)\r\n", 1180 escape_char, escape_char, 1181 escape_char, escape_char, 1182 escape_char, escape_char, 1183 escape_char, escape_char, 1184 escape_char, escape_char, 1185 escape_char); 1186 } 1187 buffer_append(berr, string, strlen(string)); 1188 continue; 1189 1190 case '#': 1191 snprintf(string, sizeof string, "%c#\r\n", 1192 escape_char); 1193 buffer_append(berr, string, strlen(string)); 1194 s = channel_open_message(); 1195 buffer_append(berr, s, strlen(s)); 1196 xfree(s); 1197 continue; 1198 1199 case 'C': 1200 if (c && c->ctl_chan != -1) 1201 goto noescape; 1202 process_cmdline(); 1203 continue; 1204 1205 default: 1206 if (ch != escape_char) { 1207 buffer_put_char(bin, escape_char); 1208 bytes++; 1209 } 1210 /* Escaped characters fall through here */ 1211 break; 1212 } 1213 } else { 1214 /* 1215 * The previous character was not an escape char. 1216 * Check if this is an escape. 1217 */ 1218 if (last_was_cr && ch == escape_char) { 1219 /* 1220 * It is. Set the flag and continue to 1221 * next character. 1222 */ 1223 *escape_pendingp = 1; 1224 continue; 1225 } 1226 } 1227 1228 /* 1229 * Normal character. Record whether it was a newline, 1230 * and append it to the buffer. 1231 */ 1232 last_was_cr = (ch == '\r' || ch == '\n'); 1233 buffer_put_char(bin, ch); 1234 bytes++; 1235 } 1236 return bytes; 1237 } 1238 1239 static void 1240 client_process_input(fd_set *readset) 1241 { 1242 int len, fd; 1243 char buf[8192]; 1244 1245 /* Read input from stdin. */ 1246 if ((fd = fileno(stdin)) == -1 || !FD_ISSET(fd, readset)) 1247 return; 1248 /* Read as much as possible. */ 1249 len = read(fd, buf, sizeof(buf)); 1250 if (len < 0 && (errno == EAGAIN || errno == EINTR)) 1251 return; /* we'll try again later */ 1252 if (len <= 0) { 1253 /* 1254 * Received EOF or error. They are treated 1255 * similarly, except that an error message is printed 1256 * if it was an error condition. 1257 */ 1258 if (len < 0) { 1259 snprintf(buf, sizeof buf, "read: %.100s\r\n", 1260 strerror(errno)); 1261 buffer_append(&stderr_buffer, buf, strlen(buf)); 1262 } 1263 /* Mark that we have seen EOF. */ 1264 stdin_eof = 1; 1265 /* 1266 * Send an EOF message to the server unless there is 1267 * data in the buffer. If there is data in the 1268 * buffer, no message will be sent now. Code 1269 * elsewhere will send the EOF when the buffer 1270 * becomes empty if stdin_eof is set. 1271 */ 1272 if (buffer_len(&stdin_buffer) == 0) { 1273 packet_start(SSH_CMSG_EOF); 1274 packet_send(); 1275 } 1276 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) { 1277 /* 1278 * Normal successful read, and no escape character. 1279 * Just append the data to buffer. 1280 */ 1281 buffer_append(&stdin_buffer, buf, len); 1282 } else { 1283 /* 1284 * Normal, successful read. But we have an escape 1285 * character and have to process the characters one 1286 * by one. 1287 */ 1288 if (process_escapes(NULL, &stdin_buffer, 1289 &stdout_buffer, &stderr_buffer, buf, len) == -1) 1290 return; 1291 } 1292 } 1293 1294 static void 1295 client_process_output(fd_set *writeset) 1296 { 1297 int len, fd; 1298 char buf[100]; 1299 1300 /* Write buffered output to stdout. */ 1301 if ((fd = fileno(stdout)) != -1 && FD_ISSET(fd, writeset)) { 1302 /* Write as much data as possible. */ 1303 len = write(fd, buffer_ptr(&stdout_buffer), 1304 buffer_len(&stdout_buffer)); 1305 if (len <= 0) { 1306 if (errno == EINTR || errno == EAGAIN) 1307 len = 0; 1308 else { 1309 /* 1310 * An error or EOF was encountered. Put an 1311 * error message to stderr buffer. 1312 */ 1313 snprintf(buf, sizeof buf, 1314 "write stdout: %.50s\r\n", strerror(errno)); 1315 buffer_append(&stderr_buffer, buf, strlen(buf)); 1316 quit_pending = 1; 1317 return; 1318 } 1319 } 1320 /* Consume printed data from the buffer. */ 1321 buffer_consume(&stdout_buffer, len); 1322 } 1323 /* Write buffered output to stderr. */ 1324 if ((fd = fileno(stderr)) != -1 && FD_ISSET(fd, writeset)) { 1325 /* Write as much data as possible. */ 1326 len = write(fd, buffer_ptr(&stderr_buffer), 1327 buffer_len(&stderr_buffer)); 1328 if (len <= 0) { 1329 if (errno == EINTR || errno == EAGAIN) 1330 len = 0; 1331 else { 1332 /* 1333 * EOF or error, but can't even print 1334 * error message. 1335 */ 1336 quit_pending = 1; 1337 return; 1338 } 1339 } 1340 /* Consume printed characters from the buffer. */ 1341 buffer_consume(&stderr_buffer, len); 1342 } 1343 } 1344 1345 /* 1346 * Get packets from the connection input buffer, and process them as long as 1347 * there are packets available. 1348 * 1349 * Any unknown packets received during the actual 1350 * session cause the session to terminate. This is 1351 * intended to make debugging easier since no 1352 * confirmations are sent. Any compatible protocol 1353 * extensions must be negotiated during the 1354 * preparatory phase. 1355 */ 1356 1357 static void 1358 client_process_buffered_input_packets(void) 1359 { 1360 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, 1361 compat20 ? xxx_kex : NULL); 1362 } 1363 1364 /* scan buf[] for '~' before sending data to the peer */ 1365 1366 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */ 1367 void * 1368 client_new_escape_filter_ctx(int escape_char) 1369 { 1370 struct escape_filter_ctx *ret; 1371 1372 ret = xmalloc(sizeof(*ret)); 1373 ret->escape_pending = 0; 1374 ret->escape_char = escape_char; 1375 return (void *)ret; 1376 } 1377 1378 /* Free the escape filter context on channel free */ 1379 void 1380 client_filter_cleanup(int cid, void *ctx) 1381 { 1382 xfree(ctx); 1383 } 1384 1385 int 1386 client_simple_escape_filter(Channel *c, const char *buf, int len) 1387 { 1388 if (c->extended_usage != CHAN_EXTENDED_WRITE) 1389 return 0; 1390 1391 return process_escapes(c, &c->input, &c->output, &c->extended, 1392 buf, len); 1393 } 1394 1395 static void 1396 client_channel_closed(int id, void *arg) 1397 { 1398 channel_cancel_cleanup(id); 1399 session_closed = 1; 1400 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1401 } 1402 1403 /* 1404 * Implements the interactive session with the server. This is called after 1405 * the user has been authenticated, and a command has been started on the 1406 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character 1407 * used as an escape character for terminating or suspending the session. 1408 */ 1409 1410 int 1411 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id) 1412 { 1413 fd_set *readset = NULL, *writeset = NULL; 1414 double start_time, total_time; 1415 int max_fd = 0, max_fd2 = 0, len, rekeying = 0; 1416 u_int64_t ibytes, obytes; 1417 u_int nalloc = 0; 1418 char buf[100]; 1419 1420 debug("Entering interactive session."); 1421 1422 start_time = get_current_time(); 1423 1424 /* Initialize variables. */ 1425 escape_pending1 = 0; 1426 last_was_cr = 1; 1427 exit_status = -1; 1428 stdin_eof = 0; 1429 buffer_high = 64 * 1024; 1430 connection_in = packet_get_connection_in(); 1431 connection_out = packet_get_connection_out(); 1432 max_fd = MAX(connection_in, connection_out); 1433 1434 if (!compat20) { 1435 /* enable nonblocking unless tty */ 1436 if (!isatty(fileno(stdin))) 1437 set_nonblock(fileno(stdin)); 1438 if (!isatty(fileno(stdout))) 1439 set_nonblock(fileno(stdout)); 1440 if (!isatty(fileno(stderr))) 1441 set_nonblock(fileno(stderr)); 1442 max_fd = MAX(max_fd, fileno(stdin)); 1443 max_fd = MAX(max_fd, fileno(stdout)); 1444 max_fd = MAX(max_fd, fileno(stderr)); 1445 } 1446 quit_pending = 0; 1447 escape_char1 = escape_char_arg; 1448 1449 /* Initialize buffers. */ 1450 buffer_init(&stdin_buffer); 1451 buffer_init(&stdout_buffer); 1452 buffer_init(&stderr_buffer); 1453 1454 client_init_dispatch(); 1455 1456 /* 1457 * Set signal handlers, (e.g. to restore non-blocking mode) 1458 * but don't overwrite SIG_IGN, matches behaviour from rsh(1) 1459 */ 1460 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) 1461 signal(SIGHUP, signal_handler); 1462 if (signal(SIGINT, SIG_IGN) != SIG_IGN) 1463 signal(SIGINT, signal_handler); 1464 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) 1465 signal(SIGQUIT, signal_handler); 1466 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) 1467 signal(SIGTERM, signal_handler); 1468 signal(SIGWINCH, window_change_handler); 1469 1470 if (have_pty) 1471 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1472 1473 if (compat20) { 1474 session_ident = ssh2_chan_id; 1475 if (session_ident != -1) { 1476 if (escape_char_arg != SSH_ESCAPECHAR_NONE) { 1477 channel_register_filter(session_ident, 1478 client_simple_escape_filter, NULL, 1479 client_filter_cleanup, 1480 client_new_escape_filter_ctx( 1481 escape_char_arg)); 1482 } 1483 channel_register_cleanup(session_ident, 1484 client_channel_closed, 0); 1485 } 1486 } else { 1487 /* Check if we should immediately send eof on stdin. */ 1488 client_check_initial_eof_on_stdin(); 1489 } 1490 1491 /* Main loop of the client for the interactive session mode. */ 1492 while (!quit_pending) { 1493 1494 /* Process buffered packets sent by the server. */ 1495 client_process_buffered_input_packets(); 1496 1497 if (compat20 && session_closed && !channel_still_open()) 1498 break; 1499 1500 rekeying = (xxx_kex != NULL && !xxx_kex->done); 1501 1502 if (rekeying) { 1503 debug("rekeying in progress"); 1504 } else { 1505 /* 1506 * Make packets of buffered stdin data, and buffer 1507 * them for sending to the server. 1508 */ 1509 if (!compat20) 1510 client_make_packets_from_stdin_data(); 1511 1512 /* 1513 * Make packets from buffered channel data, and 1514 * enqueue them for sending to the server. 1515 */ 1516 if (packet_not_very_much_data_to_write()) 1517 channel_output_poll(); 1518 1519 /* 1520 * Check if the window size has changed, and buffer a 1521 * message about it to the server if so. 1522 */ 1523 client_check_window_change(); 1524 1525 if (quit_pending) 1526 break; 1527 } 1528 /* 1529 * Wait until we have something to do (something becomes 1530 * available on one of the descriptors). 1531 */ 1532 max_fd2 = max_fd; 1533 client_wait_until_can_do_something(&readset, &writeset, 1534 &max_fd2, &nalloc, rekeying); 1535 1536 if (quit_pending) 1537 break; 1538 1539 /* Do channel operations unless rekeying in progress. */ 1540 if (!rekeying) { 1541 channel_after_select(readset, writeset); 1542 if (need_rekeying || packet_need_rekeying()) { 1543 debug("need rekeying"); 1544 xxx_kex->done = 0; 1545 kex_send_kexinit(xxx_kex); 1546 need_rekeying = 0; 1547 } 1548 } 1549 1550 /* Buffer input from the connection. */ 1551 client_process_net_input(readset); 1552 1553 if (quit_pending) 1554 break; 1555 1556 if (!compat20) { 1557 /* Buffer data from stdin */ 1558 client_process_input(readset); 1559 /* 1560 * Process output to stdout and stderr. Output to 1561 * the connection is processed elsewhere (above). 1562 */ 1563 client_process_output(writeset); 1564 } 1565 1566 if (session_resumed) { 1567 connection_in = packet_get_connection_in(); 1568 connection_out = packet_get_connection_out(); 1569 max_fd = MAX(max_fd, connection_out); 1570 max_fd = MAX(max_fd, connection_in); 1571 session_resumed = 0; 1572 } 1573 1574 /* 1575 * Send as much buffered packet data as possible to the 1576 * sender. 1577 */ 1578 if (FD_ISSET(connection_out, writeset)) 1579 packet_write_poll(); 1580 1581 /* 1582 * If we are a backgrounded control master, and the 1583 * timeout has expired without any active client 1584 * connections, then quit. 1585 */ 1586 if (control_persist_exit_time > 0) { 1587 if (time(NULL) >= control_persist_exit_time) { 1588 debug("ControlPersist timeout expired"); 1589 break; 1590 } 1591 } 1592 } 1593 if (readset) 1594 xfree(readset); 1595 if (writeset) 1596 xfree(writeset); 1597 1598 /* Terminate the session. */ 1599 1600 /* Stop watching for window change. */ 1601 signal(SIGWINCH, SIG_DFL); 1602 1603 if (compat20) { 1604 packet_start(SSH2_MSG_DISCONNECT); 1605 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION); 1606 packet_put_cstring("disconnected by user"); 1607 packet_put_cstring(""); /* language tag */ 1608 packet_send(); 1609 packet_write_wait(); 1610 } 1611 1612 channel_free_all(); 1613 1614 if (have_pty) 1615 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 1616 1617 /* restore blocking io */ 1618 if (!isatty(fileno(stdin))) 1619 unset_nonblock(fileno(stdin)); 1620 if (!isatty(fileno(stdout))) 1621 unset_nonblock(fileno(stdout)); 1622 if (!isatty(fileno(stderr))) 1623 unset_nonblock(fileno(stderr)); 1624 1625 /* 1626 * If there was no shell or command requested, there will be no remote 1627 * exit status to be returned. In that case, clear error code if the 1628 * connection was deliberately terminated at this end. 1629 */ 1630 if (no_shell_flag && received_signal == SIGTERM) { 1631 received_signal = 0; 1632 exit_status = 0; 1633 } 1634 1635 if (received_signal) 1636 fatal("Killed by signal %d.", (int) received_signal); 1637 1638 /* 1639 * In interactive mode (with pseudo tty) display a message indicating 1640 * that the connection has been closed. 1641 */ 1642 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) { 1643 snprintf(buf, sizeof buf, 1644 "Connection to %.64s closed.\r\n", host); 1645 buffer_append(&stderr_buffer, buf, strlen(buf)); 1646 } 1647 1648 /* Output any buffered data for stdout. */ 1649 if (buffer_len(&stdout_buffer) > 0) { 1650 len = atomicio(vwrite, fileno(stdout), 1651 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer)); 1652 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer)) 1653 error("Write failed flushing stdout buffer."); 1654 else 1655 buffer_consume(&stdout_buffer, len); 1656 } 1657 1658 /* Output any buffered data for stderr. */ 1659 if (buffer_len(&stderr_buffer) > 0) { 1660 len = atomicio(vwrite, fileno(stderr), 1661 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer)); 1662 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer)) 1663 error("Write failed flushing stderr buffer."); 1664 else 1665 buffer_consume(&stderr_buffer, len); 1666 } 1667 1668 /* Clear and free any buffers. */ 1669 memset(buf, 0, sizeof(buf)); 1670 buffer_free(&stdin_buffer); 1671 buffer_free(&stdout_buffer); 1672 buffer_free(&stderr_buffer); 1673 1674 /* Report bytes transferred, and transfer rates. */ 1675 total_time = get_current_time() - start_time; 1676 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes); 1677 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes); 1678 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds", 1679 (unsigned long long)obytes, (unsigned long long)ibytes, total_time); 1680 if (total_time > 0) 1681 verbose("Bytes per second: sent %.1f, received %.1f", 1682 obytes / total_time, ibytes / total_time); 1683 /* Return the exit status of the program. */ 1684 debug("Exit status %d", exit_status); 1685 return exit_status; 1686 } 1687 1688 /*********/ 1689 1690 static void 1691 client_input_stdout_data(int type, u_int32_t seq, void *ctxt) 1692 { 1693 u_int data_len; 1694 char *data = packet_get_string(&data_len); 1695 packet_check_eom(); 1696 buffer_append(&stdout_buffer, data, data_len); 1697 memset(data, 0, data_len); 1698 xfree(data); 1699 } 1700 static void 1701 client_input_stderr_data(int type, u_int32_t seq, void *ctxt) 1702 { 1703 u_int data_len; 1704 char *data = packet_get_string(&data_len); 1705 packet_check_eom(); 1706 buffer_append(&stderr_buffer, data, data_len); 1707 memset(data, 0, data_len); 1708 xfree(data); 1709 } 1710 static void 1711 client_input_exit_status(int type, u_int32_t seq, void *ctxt) 1712 { 1713 exit_status = packet_get_int(); 1714 packet_check_eom(); 1715 /* Acknowledge the exit. */ 1716 packet_start(SSH_CMSG_EXIT_CONFIRMATION); 1717 packet_send(); 1718 /* 1719 * Must wait for packet to be sent since we are 1720 * exiting the loop. 1721 */ 1722 packet_write_wait(); 1723 /* Flag that we want to exit. */ 1724 quit_pending = 1; 1725 } 1726 static void 1727 client_input_agent_open(int type, u_int32_t seq, void *ctxt) 1728 { 1729 Channel *c = NULL; 1730 int remote_id, sock; 1731 1732 /* Read the remote channel number from the message. */ 1733 remote_id = packet_get_int(); 1734 packet_check_eom(); 1735 1736 /* 1737 * Get a connection to the local authentication agent (this may again 1738 * get forwarded). 1739 */ 1740 sock = ssh_get_authentication_socket(); 1741 1742 /* 1743 * If we could not connect the agent, send an error message back to 1744 * the server. This should never happen unless the agent dies, 1745 * because authentication forwarding is only enabled if we have an 1746 * agent. 1747 */ 1748 if (sock >= 0) { 1749 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock, 1750 -1, 0, 0, 0, "authentication agent connection", 1); 1751 c->remote_id = remote_id; 1752 c->force_drain = 1; 1753 } 1754 if (c == NULL) { 1755 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE); 1756 packet_put_int(remote_id); 1757 } else { 1758 /* Send a confirmation to the remote host. */ 1759 debug("Forwarding authentication connection."); 1760 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1761 packet_put_int(remote_id); 1762 packet_put_int(c->self); 1763 } 1764 packet_send(); 1765 } 1766 1767 static Channel * 1768 client_request_forwarded_tcpip(const char *request_type, int rchan) 1769 { 1770 Channel *c = NULL; 1771 char *listen_address, *originator_address; 1772 u_short listen_port, originator_port; 1773 1774 /* Get rest of the packet */ 1775 listen_address = packet_get_string(NULL); 1776 listen_port = packet_get_int(); 1777 originator_address = packet_get_string(NULL); 1778 originator_port = packet_get_int(); 1779 packet_check_eom(); 1780 1781 debug("client_request_forwarded_tcpip: listen %s port %d, " 1782 "originator %s port %d", listen_address, listen_port, 1783 originator_address, originator_port); 1784 1785 c = channel_connect_by_listen_address(listen_port, 1786 "forwarded-tcpip", originator_address); 1787 1788 xfree(originator_address); 1789 xfree(listen_address); 1790 return c; 1791 } 1792 1793 static Channel * 1794 client_request_x11(const char *request_type, int rchan) 1795 { 1796 Channel *c = NULL; 1797 char *originator; 1798 u_short originator_port; 1799 int sock; 1800 1801 if (!options.forward_x11) { 1802 error("Warning: ssh server tried X11 forwarding."); 1803 error("Warning: this is probably a break-in attempt by a " 1804 "malicious server."); 1805 return NULL; 1806 } 1807 if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) { 1808 verbose("Rejected X11 connection after ForwardX11Timeout " 1809 "expired"); 1810 return NULL; 1811 } 1812 originator = packet_get_string(NULL); 1813 if (datafellows & SSH_BUG_X11FWD) { 1814 debug2("buggy server: x11 request w/o originator_port"); 1815 originator_port = 0; 1816 } else { 1817 originator_port = packet_get_int(); 1818 } 1819 packet_check_eom(); 1820 /* XXX check permission */ 1821 debug("client_request_x11: request from %s %d", originator, 1822 originator_port); 1823 xfree(originator); 1824 sock = x11_connect_display(); 1825 if (sock < 0) 1826 return NULL; 1827 /* again is this really necessary for X11? */ 1828 if (options.hpn_disabled) 1829 c = channel_new("x11", 1830 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 1831 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1); 1832 else 1833 c = channel_new("x11", 1834 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 1835 options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1); 1836 c->force_drain = 1; 1837 return c; 1838 } 1839 1840 static Channel * 1841 client_request_agent(const char *request_type, int rchan) 1842 { 1843 Channel *c = NULL; 1844 int sock; 1845 1846 if (!options.forward_agent) { 1847 error("Warning: ssh server tried agent forwarding."); 1848 error("Warning: this is probably a break-in attempt by a " 1849 "malicious server."); 1850 return NULL; 1851 } 1852 sock = ssh_get_authentication_socket(); 1853 if (sock < 0) 1854 return NULL; 1855 if (options.hpn_disabled) 1856 c = channel_new("authentication agent connection", 1857 SSH_CHANNEL_OPEN, sock, sock, -1, 1858 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, 1859 "authentication agent connection", 1); 1860 else 1861 c = channel_new("authentication agent connection", 1862 SSH_CHANNEL_OPEN, sock, sock, -1, 1863 options.hpn_buffer_size, options.hpn_buffer_size, 0, 1864 "authentication agent connection", 1); 1865 c->force_drain = 1; 1866 return c; 1867 } 1868 1869 int 1870 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun) 1871 { 1872 Channel *c; 1873 int fd; 1874 1875 if (tun_mode == SSH_TUNMODE_NO) 1876 return 0; 1877 1878 if (!compat20) { 1879 error("Tunnel forwarding is not supported for protocol 1"); 1880 return -1; 1881 } 1882 1883 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode); 1884 1885 /* Open local tunnel device */ 1886 if ((fd = tun_open(local_tun, tun_mode)) == -1) { 1887 error("Tunnel device open failed."); 1888 return -1; 1889 } 1890 1891 if(options.hpn_disabled) 1892 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1, 1893 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 1894 else 1895 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1, 1896 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1); 1897 c->datagram = 1; 1898 1899 packet_start(SSH2_MSG_CHANNEL_OPEN); 1900 packet_put_cstring("tun@openssh.com"); 1901 packet_put_int(c->self); 1902 packet_put_int(c->local_window_max); 1903 packet_put_int(c->local_maxpacket); 1904 packet_put_int(tun_mode); 1905 packet_put_int(remote_tun); 1906 packet_send(); 1907 1908 return 0; 1909 } 1910 1911 /* XXXX move to generic input handler */ 1912 static void 1913 client_input_channel_open(int type, u_int32_t seq, void *ctxt) 1914 { 1915 Channel *c = NULL; 1916 char *ctype; 1917 int rchan; 1918 u_int rmaxpack, rwindow, len; 1919 1920 ctype = packet_get_string(&len); 1921 rchan = packet_get_int(); 1922 rwindow = packet_get_int(); 1923 rmaxpack = packet_get_int(); 1924 1925 debug("client_input_channel_open: ctype %s rchan %d win %d max %d", 1926 ctype, rchan, rwindow, rmaxpack); 1927 1928 if (strcmp(ctype, "forwarded-tcpip") == 0) { 1929 c = client_request_forwarded_tcpip(ctype, rchan); 1930 } else if (strcmp(ctype, "x11") == 0) { 1931 c = client_request_x11(ctype, rchan); 1932 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) { 1933 c = client_request_agent(ctype, rchan); 1934 } 1935 /* XXX duplicate : */ 1936 if (c != NULL) { 1937 debug("confirm %s", ctype); 1938 c->remote_id = rchan; 1939 c->remote_window = rwindow; 1940 c->remote_maxpacket = rmaxpack; 1941 if (c->type != SSH_CHANNEL_CONNECTING) { 1942 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION); 1943 packet_put_int(c->remote_id); 1944 packet_put_int(c->self); 1945 packet_put_int(c->local_window); 1946 packet_put_int(c->local_maxpacket); 1947 packet_send(); 1948 } 1949 } else { 1950 debug("failure %s", ctype); 1951 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE); 1952 packet_put_int(rchan); 1953 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED); 1954 if (!(datafellows & SSH_BUG_OPENFAILURE)) { 1955 packet_put_cstring("open failed"); 1956 packet_put_cstring(""); 1957 } 1958 packet_send(); 1959 } 1960 xfree(ctype); 1961 } 1962 static void 1963 client_input_channel_req(int type, u_int32_t seq, void *ctxt) 1964 { 1965 Channel *c = NULL; 1966 int exitval, id, reply, success = 0; 1967 char *rtype; 1968 1969 id = packet_get_int(); 1970 rtype = packet_get_string(NULL); 1971 reply = packet_get_char(); 1972 1973 debug("client_input_channel_req: channel %d rtype %s reply %d", 1974 id, rtype, reply); 1975 1976 if (id == -1) { 1977 error("client_input_channel_req: request for channel -1"); 1978 } else if ((c = channel_lookup(id)) == NULL) { 1979 error("client_input_channel_req: channel %d: " 1980 "unknown channel", id); 1981 } else if (strcmp(rtype, "eow@openssh.com") == 0) { 1982 packet_check_eom(); 1983 chan_rcvd_eow(c); 1984 } else if (strcmp(rtype, "exit-status") == 0) { 1985 exitval = packet_get_int(); 1986 if (c->ctl_chan != -1) { 1987 mux_exit_message(c, exitval); 1988 success = 1; 1989 } else if (id == session_ident) { 1990 /* Record exit value of local session */ 1991 success = 1; 1992 exit_status = exitval; 1993 } else { 1994 /* Probably for a mux channel that has already closed */ 1995 debug("%s: no sink for exit-status on channel %d", 1996 __func__, id); 1997 } 1998 packet_check_eom(); 1999 } 2000 if (reply && c != NULL) { 2001 packet_start(success ? 2002 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE); 2003 packet_put_int(c->remote_id); 2004 packet_send(); 2005 } 2006 xfree(rtype); 2007 } 2008 static void 2009 client_input_global_request(int type, u_int32_t seq, void *ctxt) 2010 { 2011 char *rtype; 2012 int want_reply; 2013 int success = 0; 2014 2015 rtype = packet_get_string(NULL); 2016 want_reply = packet_get_char(); 2017 debug("client_input_global_request: rtype %s want_reply %d", 2018 rtype, want_reply); 2019 if (want_reply) { 2020 packet_start(success ? 2021 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE); 2022 packet_send(); 2023 packet_write_wait(); 2024 } 2025 xfree(rtype); 2026 } 2027 2028 void 2029 client_session2_setup(int id, int want_tty, int want_subsystem, 2030 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env) 2031 { 2032 int len; 2033 Channel *c = NULL; 2034 2035 debug2("%s: id %d", __func__, id); 2036 2037 if ((c = channel_lookup(id)) == NULL) 2038 fatal("client_session2_setup: channel %d: unknown channel", id); 2039 2040 packet_set_interactive(want_tty, 2041 options.ip_qos_interactive, options.ip_qos_bulk); 2042 2043 if (want_tty) { 2044 struct winsize ws; 2045 2046 /* Store window size in the packet. */ 2047 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0) 2048 memset(&ws, 0, sizeof(ws)); 2049 2050 channel_request_start(id, "pty-req", 1); 2051 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY); 2052 packet_put_cstring(term != NULL ? term : ""); 2053 packet_put_int((u_int)ws.ws_col); 2054 packet_put_int((u_int)ws.ws_row); 2055 packet_put_int((u_int)ws.ws_xpixel); 2056 packet_put_int((u_int)ws.ws_ypixel); 2057 if (tiop == NULL) 2058 tiop = get_saved_tio(); 2059 tty_make_modes(-1, tiop); 2060 packet_send(); 2061 /* XXX wait for reply */ 2062 c->client_tty = 1; 2063 } 2064 2065 /* Transfer any environment variables from client to server */ 2066 if (options.num_send_env != 0 && env != NULL) { 2067 int i, j, matched; 2068 char *name, *val; 2069 2070 debug("Sending environment."); 2071 for (i = 0; env[i] != NULL; i++) { 2072 /* Split */ 2073 name = xstrdup(env[i]); 2074 if ((val = strchr(name, '=')) == NULL) { 2075 xfree(name); 2076 continue; 2077 } 2078 *val++ = '\0'; 2079 2080 matched = 0; 2081 for (j = 0; j < options.num_send_env; j++) { 2082 if (match_pattern(name, options.send_env[j])) { 2083 matched = 1; 2084 break; 2085 } 2086 } 2087 if (!matched) { 2088 debug3("Ignored env %s", name); 2089 xfree(name); 2090 continue; 2091 } 2092 2093 debug("Sending env %s = %s", name, val); 2094 channel_request_start(id, "env", 0); 2095 packet_put_cstring(name); 2096 packet_put_cstring(val); 2097 packet_send(); 2098 xfree(name); 2099 } 2100 } 2101 2102 len = buffer_len(cmd); 2103 if (len > 0) { 2104 if (len > 900) 2105 len = 900; 2106 if (want_subsystem) { 2107 debug("Sending subsystem: %.*s", 2108 len, (u_char*)buffer_ptr(cmd)); 2109 channel_request_start(id, "subsystem", 1); 2110 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE); 2111 } else { 2112 debug("Sending command: %.*s", 2113 len, (u_char*)buffer_ptr(cmd)); 2114 channel_request_start(id, "exec", 1); 2115 client_expect_confirm(id, "exec", CONFIRM_CLOSE); 2116 } 2117 packet_put_string(buffer_ptr(cmd), buffer_len(cmd)); 2118 packet_send(); 2119 } else { 2120 channel_request_start(id, "shell", 1); 2121 client_expect_confirm(id, "shell", CONFIRM_CLOSE); 2122 packet_send(); 2123 } 2124 } 2125 2126 static void 2127 client_init_dispatch_20(void) 2128 { 2129 dispatch_init(&dispatch_protocol_error); 2130 2131 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 2132 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data); 2133 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof); 2134 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data); 2135 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open); 2136 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 2137 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 2138 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req); 2139 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust); 2140 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm); 2141 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm); 2142 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request); 2143 2144 /* rekeying */ 2145 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit); 2146 2147 /* global request reply messages */ 2148 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply); 2149 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply); 2150 } 2151 2152 static void 2153 client_init_dispatch_13(void) 2154 { 2155 dispatch_init(NULL); 2156 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close); 2157 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation); 2158 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data); 2159 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 2160 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 2161 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open); 2162 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status); 2163 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data); 2164 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data); 2165 2166 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ? 2167 &client_input_agent_open : &deny_input_open); 2168 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ? 2169 &x11_input_open : &deny_input_open); 2170 } 2171 2172 static void 2173 client_init_dispatch_15(void) 2174 { 2175 client_init_dispatch_13(); 2176 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof); 2177 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose); 2178 } 2179 2180 static void 2181 client_init_dispatch(void) 2182 { 2183 if (compat20) 2184 client_init_dispatch_20(); 2185 else if (compat13) 2186 client_init_dispatch_13(); 2187 else 2188 client_init_dispatch_15(); 2189 } 2190 2191 void 2192 client_stop_mux(void) 2193 { 2194 if (options.control_path != NULL && muxserver_sock != -1) 2195 unlink(options.control_path); 2196 /* 2197 * If we are in persist mode, signal that we should close when all 2198 * active channels are closed. 2199 */ 2200 if (options.control_persist) { 2201 session_closed = 1; 2202 setproctitle("[stopped mux]"); 2203 } 2204 } 2205 2206 /* client specific fatal cleanup */ 2207 void 2208 cleanup_exit(int i) 2209 { 2210 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE); 2211 leave_non_blocking(); 2212 if (options.control_path != NULL && muxserver_sock != -1) 2213 unlink(options.control_path); 2214 ssh_kill_proxy_command(); 2215 _exit(i); 2216 } 2217