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