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