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