1 /* 2 * Author: Tatu Ylonen <ylo@cs.hut.fi> 3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * All rights reserved 5 * The main loop for the interactive session (client side). 6 * 7 * As far as I am concerned, the code I have written for this software 8 * can be used freely for any purpose. Any derived versions of this 9 * software must be clearly marked as such, and if the derived work is 10 * incompatible with the protocol description in the RFC file, it must be 11 * called by a name other than "ssh" or "Secure Shell". 12 * 13 * 14 * Copyright (c) 1999 Theo de Raadt. All rights reserved. 15 * 16 * Redistribution and use in source and binary forms, with or without 17 * modification, are permitted provided that the following conditions 18 * are met: 19 * 1. Redistributions of source code must retain the above copyright 20 * notice, this list of conditions and the following disclaimer. 21 * 2. Redistributions in binary form must reproduce the above copyright 22 * notice, this list of conditions and the following disclaimer in the 23 * documentation and/or other materials provided with the distribution. 24 * 25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 * 36 * 37 * SSH2 support added by Markus Friedl. 38 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved. 39 * 40 * Redistribution and use in source and binary forms, with or without 41 * modification, are permitted provided that the following conditions 42 * are met: 43 * 1. Redistributions of source code must retain the above copyright 44 * notice, this list of conditions and the following disclaimer. 45 * 2. Redistributions in binary form must reproduce the above copyright 46 * notice, this list of conditions and the following disclaimer in the 47 * documentation and/or other materials provided with the distribution. 48 * 49 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 50 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 51 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 52 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 53 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 54 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 55 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 56 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 57 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 58 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 59 */ 60 61 /* 62 * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. 63 */ 64 65 #include "includes.h" 66 RCSID("$OpenBSD: clientloop.c,v 1.104 2002/08/22 19:38:42 stevesk Exp $"); 67 68 #include "ssh.h" 69 #include "ssh1.h" 70 #include "ssh2.h" 71 #include "xmalloc.h" 72 #include "packet.h" 73 #include "buffer.h" 74 #include "compat.h" 75 #include "channels.h" 76 #include "dispatch.h" 77 #include "buffer.h" 78 #include "bufaux.h" 79 #include "key.h" 80 #include "kex.h" 81 #include "log.h" 82 #include "readconf.h" 83 #include "clientloop.h" 84 #include "authfd.h" 85 #include "atomicio.h" 86 #include "sshtty.h" 87 #include "misc.h" 88 #include "readpass.h" 89 90 /* import options */ 91 extern Options options; 92 93 /* Flag indicating that stdin should be redirected from /dev/null. */ 94 extern int stdin_null_flag; 95 96 /* 97 * Name of the host we are connecting to. This is the name given on the 98 * command line, or the HostName specified for the user-supplied name in a 99 * configuration file. 100 */ 101 extern char *host; 102 103 /* 104 * Flag to indicate that we have received a window change signal which has 105 * not yet been processed. This will cause a message indicating the new 106 * window size to be sent to the server a little later. This is volatile 107 * because this is updated in a signal handler. 108 */ 109 static volatile sig_atomic_t received_window_change_signal = 0; 110 static volatile sig_atomic_t received_signal = 0; 111 112 /* Flag indicating whether the user's terminal is in non-blocking mode. */ 113 static int in_non_blocking_mode = 0; 114 115 /* Common data for the client loop code. */ 116 static int quit_pending; /* Set to non-zero to quit the client loop. */ 117 static int escape_char; /* Escape character. */ 118 static int escape_pending; /* Last character was the escape character */ 119 static int last_was_cr; /* Last character was a newline. */ 120 static int exit_status; /* Used to store the exit status of the command. */ 121 static int stdin_eof; /* EOF has been encountered on standard error. */ 122 static Buffer stdin_buffer; /* Buffer for stdin data. */ 123 static Buffer stdout_buffer; /* Buffer for stdout data. */ 124 static Buffer stderr_buffer; /* Buffer for stderr data. */ 125 static u_long stdin_bytes, stdout_bytes, stderr_bytes; 126 static u_int buffer_high; /* Soft max buffer size. */ 127 static int connection_in; /* Connection to server (input). */ 128 static int connection_out; /* Connection to server (output). */ 129 static int need_rekeying; /* Set to non-zero if rekeying is requested. */ 130 static int session_closed = 0; /* In SSH2: login session closed. */ 131 static int server_alive_timeouts = 0; /* Number of outstanding alive packets. */ 132 133 static void client_init_dispatch(void); 134 int session_ident = -1; 135 136 /*XXX*/ 137 extern Kex *xxx_kex; 138 139 extern int will_daemonize; 140 141 /* Restores stdin to blocking mode. */ 142 143 static void 144 leave_non_blocking(void) 145 { 146 if (in_non_blocking_mode) { 147 (void) fcntl(fileno(stdin), F_SETFL, 0); 148 in_non_blocking_mode = 0; 149 fatal_remove_cleanup((void (*) (void *)) leave_non_blocking, NULL); 150 } 151 } 152 153 /* Puts stdin terminal in non-blocking mode. */ 154 155 static void 156 enter_non_blocking(void) 157 { 158 in_non_blocking_mode = 1; 159 (void) fcntl(fileno(stdin), F_SETFL, O_NONBLOCK); 160 fatal_add_cleanup((void (*) (void *)) leave_non_blocking, NULL); 161 } 162 163 /* 164 * Signal handler for the window change signal (SIGWINCH). This just sets a 165 * flag indicating that the window has changed. 166 */ 167 168 static void 169 window_change_handler(int sig) 170 { 171 received_window_change_signal = 1; 172 signal(SIGWINCH, window_change_handler); 173 } 174 175 /* 176 * Signal handler for signals that cause the program to terminate. These 177 * signals must be trapped to restore terminal modes. 178 */ 179 180 static void 181 signal_handler(int sig) 182 { 183 received_signal = sig; 184 quit_pending = 1; 185 } 186 187 /* 188 * Returns current time in seconds from Jan 1, 1970 with the maximum 189 * available resolution. 190 */ 191 192 static double 193 get_current_time(void) 194 { 195 struct timeval tv; 196 gettimeofday(&tv, NULL); 197 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0; 198 } 199 200 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1" 201 void 202 client_x11_get_proto(const char *display, const char *xauth_path, 203 u_int trusted, char **_proto, char **_data) 204 { 205 char cmd[1024]; 206 char line[512]; 207 char xdisplay[512]; 208 static char proto[512], data[512]; 209 FILE *f; 210 int got_data = 0, generated = 0, do_unlink = 0, i; 211 char *xauthdir, *xauthfile; 212 struct stat st; 213 214 xauthdir = xauthfile = NULL; 215 *_proto = proto; 216 *_data = data; 217 proto[0] = data[0] = '\0'; 218 219 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) { 220 debug("No xauth program."); 221 } else { 222 if (display == NULL) { 223 debug("x11_get_proto: DISPLAY not set"); 224 return; 225 } 226 /* 227 * Handle FamilyLocal case where $DISPLAY does 228 * not match an authorization entry. For this we 229 * just try "xauth list unix:displaynum.screennum". 230 * XXX: "localhost" match to determine FamilyLocal 231 * is not perfect. 232 */ 233 if (strncmp(display, "localhost:", 10) == 0) { 234 snprintf(xdisplay, sizeof(xdisplay), "unix:%s", 235 display + 10); 236 display = xdisplay; 237 } 238 if (trusted == 0) { 239 xauthdir = xmalloc(MAXPATHLEN); 240 xauthfile = xmalloc(MAXPATHLEN); 241 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN); 242 if (mkdtemp(xauthdir) != NULL) { 243 do_unlink = 1; 244 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile", 245 xauthdir); 246 snprintf(cmd, sizeof(cmd), 247 "%s -f %s generate %s " SSH_X11_PROTO 248 " untrusted timeout 1200 2>" _PATH_DEVNULL, 249 xauth_path, xauthfile, display); 250 debug2("x11_get_proto: %s", cmd); 251 if (system(cmd) == 0) 252 generated = 1; 253 } 254 } 255 256 /* 257 * When in untrusted mode, we read the cookie only if it was 258 * successfully generated as an untrusted one in the step 259 * above. 260 */ 261 if (trusted || generated) { 262 snprintf(cmd, sizeof(cmd), 263 "%s %s%s list %s 2>" _PATH_DEVNULL, 264 xauth_path, 265 generated ? "-f " : "" , 266 generated ? xauthfile : "", 267 display); 268 debug2("x11_get_proto: %s", cmd); 269 f = popen(cmd, "r"); 270 if (f && fgets(line, sizeof(line), f) && 271 sscanf(line, "%*s %511s %511s", proto, data) == 2) 272 got_data = 1; 273 if (f) 274 pclose(f); 275 } 276 else 277 error("Warning: untrusted X11 forwarding setup failed: " 278 "xauth key data not generated"); 279 } 280 281 if (do_unlink) { 282 unlink(xauthfile); 283 rmdir(xauthdir); 284 } 285 if (xauthdir) 286 xfree(xauthdir); 287 if (xauthfile) 288 xfree(xauthfile); 289 290 /* 291 * If we didn't get authentication data, just make up some 292 * data. The forwarding code will check the validity of the 293 * response anyway, and substitute this data. The X11 294 * server, however, will ignore this fake data and use 295 * whatever authentication mechanisms it was using otherwise 296 * for the local connection. 297 */ 298 if (!got_data) { 299 u_int32_t rnd = 0; 300 301 log("Warning: No xauth data; " 302 "using fake authentication data for X11 forwarding."); 303 strlcpy(proto, SSH_X11_PROTO, sizeof proto); 304 for (i = 0; i < 16; i++) { 305 if (i % 4 == 0) 306 rnd = arc4random(); 307 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", 308 rnd & 0xff); 309 rnd >>= 8; 310 } 311 } 312 } 313 314 /* 315 * This is called when the interactive is entered. This checks if there is 316 * an EOF coming on stdin. We must check this explicitly, as select() does 317 * not appear to wake up when redirecting from /dev/null. 318 */ 319 320 static void 321 client_check_initial_eof_on_stdin(void) 322 { 323 int len; 324 char buf[1]; 325 326 /* 327 * If standard input is to be "redirected from /dev/null", we simply 328 * mark that we have seen an EOF and send an EOF message to the 329 * server. Otherwise, we try to read a single character; it appears 330 * that for some files, such /dev/null, select() never wakes up for 331 * read for this descriptor, which means that we never get EOF. This 332 * way we will get the EOF if stdin comes from /dev/null or similar. 333 */ 334 if (stdin_null_flag) { 335 /* Fake EOF on stdin. */ 336 debug("Sending eof."); 337 stdin_eof = 1; 338 packet_start(SSH_CMSG_EOF); 339 packet_send(); 340 } else { 341 enter_non_blocking(); 342 343 /* Check for immediate EOF on stdin. */ 344 len = read(fileno(stdin), buf, 1); 345 if (len == 0) { 346 /* EOF. Record that we have seen it and send EOF to server. */ 347 debug("Sending eof."); 348 stdin_eof = 1; 349 packet_start(SSH_CMSG_EOF); 350 packet_send(); 351 } else if (len > 0) { 352 /* 353 * Got data. We must store the data in the buffer, 354 * and also process it as an escape character if 355 * appropriate. 356 */ 357 if ((u_char) buf[0] == escape_char) 358 escape_pending = 1; 359 else 360 buffer_append(&stdin_buffer, buf, 1); 361 } 362 leave_non_blocking(); 363 } 364 } 365 366 367 /* 368 * Make packets from buffered stdin data, and buffer them for sending to the 369 * connection. 370 */ 371 372 static void 373 client_make_packets_from_stdin_data(void) 374 { 375 u_int len; 376 377 /* Send buffered stdin data to the server. */ 378 while (buffer_len(&stdin_buffer) > 0 && 379 packet_not_very_much_data_to_write()) { 380 len = buffer_len(&stdin_buffer); 381 /* Keep the packets at reasonable size. */ 382 if (len > packet_get_maxsize()) 383 len = packet_get_maxsize(); 384 packet_start(SSH_CMSG_STDIN_DATA); 385 packet_put_string(buffer_ptr(&stdin_buffer), len); 386 packet_send(); 387 buffer_consume(&stdin_buffer, len); 388 stdin_bytes += len; 389 /* If we have a pending EOF, send it now. */ 390 if (stdin_eof && buffer_len(&stdin_buffer) == 0) { 391 packet_start(SSH_CMSG_EOF); 392 packet_send(); 393 } 394 } 395 } 396 397 /* 398 * Checks if the client window has changed, and sends a packet about it to 399 * the server if so. The actual change is detected elsewhere (by a software 400 * interrupt on Unix); this just checks the flag and sends a message if 401 * appropriate. 402 */ 403 404 static void 405 client_check_window_change(void) 406 { 407 struct winsize ws; 408 Channel *c; 409 410 if (! received_window_change_signal) 411 return; 412 413 /* 414 * We want to send a window-change request only when a session is 415 * already established and alive. 416 * 417 * Note: During session handshake we cannot send window-change request, 418 * because we do not know the remote channel ID yet. We have to store 419 * the information about signals which have arrived and send the 420 * window-change request when the channel and the session are fully 421 * established. 422 */ 423 if (compat20) { 424 if (session_ident == -1 || session_closed) 425 return; 426 c = channel_lookup(session_ident); 427 if (c == NULL || c->type != SSH_CHANNEL_OPEN || 428 c->remote_id == -1) 429 return; 430 } 431 432 received_window_change_signal = 0; 433 434 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) 435 return; 436 437 debug2("client_check_window_change: changed"); 438 439 if (compat20) { 440 channel_request_start(session_ident, "window-change", 0); 441 packet_put_int(ws.ws_col); 442 packet_put_int(ws.ws_row); 443 packet_put_int(ws.ws_xpixel); 444 packet_put_int(ws.ws_ypixel); 445 packet_send(); 446 } else { 447 packet_start(SSH_CMSG_WINDOW_SIZE); 448 packet_put_int(ws.ws_row); 449 packet_put_int(ws.ws_col); 450 packet_put_int(ws.ws_xpixel); 451 packet_put_int(ws.ws_ypixel); 452 packet_send(); 453 } 454 } 455 456 static void 457 client_global_request_reply(int type, u_int32_t seq, void *ctxt) 458 { 459 server_alive_timeouts = 0; 460 client_global_request_reply_fwd(type, seq, ctxt); 461 } 462 463 static void 464 server_alive_check(void) 465 { 466 if (++server_alive_timeouts > options.server_alive_count_max) { 467 log("Timeout, server not responding."); 468 fatal_cleanup(); 469 } 470 packet_start(SSH2_MSG_GLOBAL_REQUEST); 471 packet_put_cstring("keepalive@openssh.com"); 472 packet_put_char(1); /* boolean: want reply */ 473 packet_send(); 474 } 475 476 /* 477 * Waits until the client can do something (some data becomes available on 478 * one of the file descriptors). 479 */ 480 481 static void 482 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, 483 int *maxfdp, int *nallocp, int rekeying) 484 { 485 struct timeval tv, *tvp; 486 int ret; 487 488 /* Add any selections by the channel mechanism. */ 489 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying); 490 491 if (!compat20) { 492 /* Read from the connection, unless our buffers are full. */ 493 if (buffer_len(&stdout_buffer) < buffer_high && 494 buffer_len(&stderr_buffer) < buffer_high && 495 channel_not_very_much_buffered_data()) 496 FD_SET(connection_in, *readsetp); 497 /* 498 * Read from stdin, unless we have seen EOF or have very much 499 * buffered data to send to the server. 500 */ 501 if (!stdin_eof && packet_not_very_much_data_to_write()) 502 FD_SET(fileno(stdin), *readsetp); 503 504 /* Select stdout/stderr if have data in buffer. */ 505 if (buffer_len(&stdout_buffer) > 0) 506 FD_SET(fileno(stdout), *writesetp); 507 if (buffer_len(&stderr_buffer) > 0) 508 FD_SET(fileno(stderr), *writesetp); 509 } else { 510 /* channel_prepare_select could have closed the last channel */ 511 if (session_closed && !channel_still_open() && 512 !packet_have_data_to_write()) { 513 /* clear mask since we did not call select() */ 514 memset(*readsetp, 0, *nallocp); 515 memset(*writesetp, 0, *nallocp); 516 return; 517 } else { 518 FD_SET(connection_in, *readsetp); 519 } 520 } 521 522 /* Select server connection if have data to write to the server. */ 523 if (packet_have_data_to_write()) 524 FD_SET(connection_out, *writesetp); 525 526 /* 527 * Wait for something to happen. This will suspend the process until 528 * some selected descriptor can be read, written, or has some other 529 * event pending. 530 */ 531 532 if (options.server_alive_interval == 0 || !compat20) 533 tvp = NULL; 534 else { 535 tv.tv_sec = options.server_alive_interval; 536 tv.tv_usec = 0; 537 tvp = &tv; 538 } 539 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp); 540 if (ret < 0) { 541 char buf[100]; 542 543 /* 544 * We have to clear the select masks, because we return. 545 * We have to return, because the mainloop checks for the flags 546 * set by the signal handlers. 547 */ 548 memset(*readsetp, 0, *nallocp); 549 memset(*writesetp, 0, *nallocp); 550 551 if (errno == EINTR) 552 return; 553 /* Note: we might still have data in the buffers. */ 554 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno)); 555 buffer_append(&stderr_buffer, buf, strlen(buf)); 556 quit_pending = 1; 557 } else if (ret == 0) 558 server_alive_check(); 559 } 560 561 static void 562 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr) 563 { 564 struct winsize oldws, newws; 565 566 /* Flush stdout and stderr buffers. */ 567 if (buffer_len(bout) > 0) 568 atomicio(write, fileno(stdout), buffer_ptr(bout), buffer_len(bout)); 569 if (buffer_len(berr) > 0) 570 atomicio(write, fileno(stderr), buffer_ptr(berr), buffer_len(berr)); 571 572 leave_raw_mode(); 573 574 /* 575 * Free (and clear) the buffer to reduce the amount of data that gets 576 * written to swap. 577 */ 578 buffer_free(bin); 579 buffer_free(bout); 580 buffer_free(berr); 581 582 /* Save old window size. */ 583 ioctl(fileno(stdin), TIOCGWINSZ, &oldws); 584 585 /* Send the suspend signal to the program itself. */ 586 kill(getpid(), SIGTSTP); 587 588 /* Check if the window size has changed. */ 589 if (ioctl(fileno(stdin), TIOCGWINSZ, &newws) >= 0 && 590 (oldws.ws_row != newws.ws_row || 591 oldws.ws_col != newws.ws_col || 592 oldws.ws_xpixel != newws.ws_xpixel || 593 oldws.ws_ypixel != newws.ws_ypixel)) 594 received_window_change_signal = 1; 595 596 /* OK, we have been continued by the user. Reinitialize buffers. */ 597 buffer_init(bin); 598 buffer_init(bout); 599 buffer_init(berr); 600 601 enter_raw_mode(); 602 } 603 604 static void 605 client_process_net_input(fd_set * readset) 606 { 607 int len; 608 char buf[8192]; 609 610 /* 611 * Read input from the server, and add any such data to the buffer of 612 * the packet subsystem. 613 */ 614 if (FD_ISSET(connection_in, readset)) { 615 /* Read as much as possible. */ 616 len = read(connection_in, buf, sizeof(buf)); 617 if (len == 0) { 618 /* Received EOF. The remote host has closed the connection. */ 619 snprintf(buf, sizeof buf, 620 gettext("Connection to %.300s closed " 621 "by remote host.\n"), 622 host); 623 buffer_append(&stderr_buffer, buf, strlen(buf)); 624 quit_pending = 1; 625 return; 626 } 627 /* 628 * There is a kernel bug on Solaris that causes select to 629 * sometimes wake up even though there is no data available. 630 */ 631 if (len < 0 && (errno == EAGAIN || errno == EINTR)) 632 len = 0; 633 634 if (len < 0) { 635 /* An error has encountered. Perhaps there is a network problem. */ 636 snprintf(buf, sizeof buf, 637 gettext("Read from remote host " 638 "%.300s: %.100s\n"), 639 host, strerror(errno)); 640 buffer_append(&stderr_buffer, buf, strlen(buf)); 641 quit_pending = 1; 642 return; 643 } 644 packet_process_incoming(buf, len); 645 } 646 } 647 648 static void 649 process_cmdline(void) 650 { 651 void (*handler)(int); 652 char *s, *cmd; 653 int delete = 0; 654 int local = 0; 655 Forward fwd; 656 657 memset(&fwd, 0, sizeof(fwd)); 658 659 leave_raw_mode(); 660 handler = signal(SIGINT, SIG_IGN); 661 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO); 662 if (s == NULL) 663 goto out; 664 while (isspace(*s)) 665 s++; 666 if (*s == '-') 667 s++; /* Skip cmdline '-', if any */ 668 if (*s == '\0') 669 goto out; 670 671 if (*s == 'h' || *s == 'H' || *s == '?') { 672 log("Commands:"); 673 log(" -L[bind_address:]port:host:hostport " 674 "Request local forward"); 675 log(" -R[bind_address:]port:host:hostport " 676 "Request remote forward"); 677 log(" -KR[bind_address:]port " 678 "Cancel remote forward"); 679 goto out; 680 } 681 682 if (*s == 'K') { 683 delete = 1; 684 s++; 685 } 686 if (*s != 'L' && *s != 'R') { 687 log("Invalid command."); 688 goto out; 689 } 690 if (*s == 'L') 691 local = 1; 692 if (local && delete) { 693 log("Not supported."); 694 goto out; 695 } 696 if ((!local || delete) && !compat20) { 697 log("Not supported for SSH protocol version 1."); 698 goto out; 699 } 700 701 while (isspace(*++s)) 702 ; 703 704 if (delete) { 705 if (parse_forward(0, &fwd, s) == 0) { 706 log("Bad forwarding close port"); 707 goto out; 708 } 709 channel_request_rforward_cancel(fwd.listen_host, fwd.listen_port); 710 } else { 711 if (parse_forward(1, &fwd, s) == 0) { 712 log("Bad forwarding specification."); 713 goto out; 714 } 715 if (local) { 716 if (channel_setup_local_fwd_listener(fwd.listen_host, 717 fwd.listen_port, fwd.connect_host, 718 fwd.connect_port, options.gateway_ports) < 0) { 719 log("Port forwarding failed."); 720 goto out; 721 } 722 } else { 723 if (channel_request_remote_forwarding(fwd.listen_host, 724 fwd.listen_port, fwd.connect_host, 725 fwd.connect_port) < 0) { 726 log("Port forwarding failed."); 727 goto out; 728 } 729 } 730 731 log("Forwarding port."); 732 } 733 734 out: 735 signal(SIGINT, handler); 736 enter_raw_mode(); 737 if (cmd != NULL) 738 xfree(cmd); 739 if (fwd.listen_host != NULL) 740 xfree(fwd.listen_host); 741 if (fwd.connect_host != NULL) 742 xfree(fwd.connect_host); 743 } 744 745 /* 746 * If we are using the engine we must not fork until we do key reexchange. See 747 * PKCS#11 spec for more information on fork safety and packet.c for information 748 * about forking with the engine. 749 */ 750 void 751 client_daemonize(void) 752 { 753 if (compat20 == 1 && options.use_openssl_engine == 1) { 754 will_daemonize = 1; 755 debug("must rekey before daemonizing"); 756 kex_send_kexinit(xxx_kex); 757 need_rekeying = 0; 758 } 759 else { 760 if (daemon(1, 1) < 0) { 761 fatal("daemon() failed: %.200s", 762 strerror(errno)); 763 } 764 } 765 } 766 767 /* process the characters one by one */ 768 static int 769 process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len) 770 { 771 char string[1536]; 772 int bytes = 0; 773 u_int i; 774 u_char ch; 775 char *s; 776 777 for (i = 0; i < len; i++) { 778 /* Get one character at a time. */ 779 ch = buf[i]; 780 781 if (escape_pending) { 782 /* We have previously seen an escape character. */ 783 /* Clear the flag now. */ 784 escape_pending = 0; 785 786 /* Process the escaped character. */ 787 switch (ch) { 788 case '.': 789 /* Terminate the connection. */ 790 snprintf(string, sizeof string, "%c.\r\n", escape_char); 791 buffer_append(berr, string, strlen(string)); 792 793 quit_pending = 1; 794 return -1; 795 796 case 'Z' - 64: 797 /* Suspend the program. */ 798 /* Print a message to that effect to the user. */ 799 snprintf(string, sizeof string, 800 gettext("%c^Z [suspend ssh]\n"), 801 escape_char); 802 buffer_append(berr, string, strlen(string)); 803 804 /* Restore terminal modes and suspend. */ 805 client_suspend_self(bin, bout, berr); 806 807 /* We have been continued. */ 808 continue; 809 810 case 'B': 811 if (compat20) { 812 snprintf(string, sizeof string, 813 gettext("%cB [sent break]\n"), 814 escape_char); 815 buffer_append(berr, string, 816 strlen(string)); 817 channel_request_start(session_ident, 818 "break", 0); 819 packet_put_int(1000); 820 packet_send(); 821 } 822 continue; 823 824 case 'R': 825 if (compat20) { 826 if (datafellows & SSH_BUG_NOREKEY) 827 log("Server does not support re-keying"); 828 else 829 need_rekeying = 1; 830 } 831 continue; 832 833 case '&': 834 /* 835 * Detach the program (continue to serve connections, 836 * but put in background and no more new connections). 837 */ 838 /* Restore tty modes. */ 839 leave_raw_mode(); 840 841 /* Stop listening for new connections. */ 842 channel_stop_listening(); 843 844 snprintf(string, sizeof string, 845 gettext("%c& [backgrounded]\n"), 846 escape_char); 847 buffer_append(berr, string, strlen(string)); 848 849 client_daemonize(); 850 851 /* The child continues serving connections. */ 852 if (compat20) { 853 buffer_append(bin, "\004", 1); 854 /* fake EOF on stdin */ 855 return -1; 856 } else if (!stdin_eof) { 857 /* 858 * Sending SSH_CMSG_EOF alone does not always appear 859 * to be enough. So we try to send an EOF character 860 * first. 861 */ 862 packet_start(SSH_CMSG_STDIN_DATA); 863 packet_put_string("\004", 1); 864 packet_send(); 865 /* Close stdin. */ 866 stdin_eof = 1; 867 if (buffer_len(bin) == 0) { 868 packet_start(SSH_CMSG_EOF); 869 packet_send(); 870 } 871 } 872 continue; 873 874 case '?': 875 snprintf(string, sizeof string, gettext( 876 "%c?\n\ 877 Supported escape sequences:\n\ 878 %c. - terminate connection\n\ 879 %cB - send break (SSH protocol 2 only)\n\ 880 %cC - open a command line\n\ 881 %cR - Request rekey (SSH protocol 2 only)\n\ 882 %c^Z - suspend ssh\n\ 883 %c# - list forwarded connections\n\ 884 %c& - background ssh (when waiting for connections to terminate)\n\ 885 %c? - this message\n\ 886 %c%c - send the escape character by typing it twice\n\ 887 (Note that escapes are only recognized immediately after newline.)\n"), 888 escape_char, escape_char, escape_char, escape_char, 889 escape_char, escape_char, escape_char, escape_char, 890 escape_char, escape_char); 891 buffer_append(berr, string, strlen(string)); 892 continue; 893 894 case '#': 895 snprintf(string, sizeof string, "%c#\r\n", escape_char); 896 buffer_append(berr, string, strlen(string)); 897 s = channel_open_message(); 898 buffer_append(berr, s, strlen(s)); 899 xfree(s); 900 continue; 901 902 case 'C': 903 process_cmdline(); 904 continue; 905 906 default: 907 if (ch != escape_char) { 908 buffer_put_char(bin, escape_char); 909 bytes++; 910 } 911 /* Escaped characters fall through here */ 912 break; 913 } 914 } else { 915 /* 916 * The previous character was not an escape char. Check if this 917 * is an escape. 918 */ 919 if (last_was_cr && ch == escape_char) { 920 /* It is. Set the flag and continue to next character. */ 921 escape_pending = 1; 922 continue; 923 } 924 } 925 926 /* 927 * Normal character. Record whether it was a newline, 928 * and append it to the buffer. 929 */ 930 last_was_cr = (ch == '\r' || ch == '\n'); 931 buffer_put_char(bin, ch); 932 bytes++; 933 } 934 return bytes; 935 } 936 937 static void 938 client_process_input(fd_set * readset) 939 { 940 int len; 941 char buf[8192]; 942 943 /* Read input from stdin. */ 944 if (FD_ISSET(fileno(stdin), readset)) { 945 /* Read as much as possible. */ 946 len = read(fileno(stdin), buf, sizeof(buf)); 947 if (len < 0 && (errno == EAGAIN || errno == EINTR)) 948 return; /* we'll try again later */ 949 if (len <= 0) { 950 /* 951 * Received EOF or error. They are treated 952 * similarly, except that an error message is printed 953 * if it was an error condition. 954 */ 955 if (len < 0) { 956 snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno)); 957 buffer_append(&stderr_buffer, buf, strlen(buf)); 958 } 959 /* Mark that we have seen EOF. */ 960 stdin_eof = 1; 961 /* 962 * Send an EOF message to the server unless there is 963 * data in the buffer. If there is data in the 964 * buffer, no message will be sent now. Code 965 * elsewhere will send the EOF when the buffer 966 * becomes empty if stdin_eof is set. 967 */ 968 if (buffer_len(&stdin_buffer) == 0) { 969 packet_start(SSH_CMSG_EOF); 970 packet_send(); 971 } 972 } else if (escape_char == SSH_ESCAPECHAR_NONE) { 973 /* 974 * Normal successful read, and no escape character. 975 * Just append the data to buffer. 976 */ 977 buffer_append(&stdin_buffer, buf, len); 978 } else { 979 /* 980 * Normal, successful read. But we have an escape character 981 * and have to process the characters one by one. 982 */ 983 if (process_escapes(&stdin_buffer, &stdout_buffer, 984 &stderr_buffer, buf, len) == -1) 985 return; 986 } 987 } 988 } 989 990 static void 991 client_process_output(fd_set * writeset) 992 { 993 int len; 994 char buf[100]; 995 996 /* Write buffered output to stdout. */ 997 if (FD_ISSET(fileno(stdout), writeset)) { 998 /* Write as much data as possible. */ 999 len = write(fileno(stdout), buffer_ptr(&stdout_buffer), 1000 buffer_len(&stdout_buffer)); 1001 if (len <= 0) { 1002 if (errno == EINTR || errno == EAGAIN) 1003 len = 0; 1004 else { 1005 /* 1006 * An error or EOF was encountered. Put an 1007 * error message to stderr buffer. 1008 */ 1009 snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno)); 1010 buffer_append(&stderr_buffer, buf, strlen(buf)); 1011 quit_pending = 1; 1012 return; 1013 } 1014 } 1015 /* Consume printed data from the buffer. */ 1016 buffer_consume(&stdout_buffer, len); 1017 stdout_bytes += len; 1018 } 1019 /* Write buffered output to stderr. */ 1020 if (FD_ISSET(fileno(stderr), writeset)) { 1021 /* Write as much data as possible. */ 1022 len = write(fileno(stderr), buffer_ptr(&stderr_buffer), 1023 buffer_len(&stderr_buffer)); 1024 if (len <= 0) { 1025 if (errno == EINTR || errno == EAGAIN) 1026 len = 0; 1027 else { 1028 /* EOF or error, but can't even print error message. */ 1029 quit_pending = 1; 1030 return; 1031 } 1032 } 1033 /* Consume printed characters from the buffer. */ 1034 buffer_consume(&stderr_buffer, len); 1035 stderr_bytes += len; 1036 } 1037 } 1038 1039 /* 1040 * Get packets from the connection input buffer, and process them as long as 1041 * there are packets available. 1042 * 1043 * Any unknown packets received during the actual 1044 * session cause the session to terminate. This is 1045 * intended to make debugging easier since no 1046 * confirmations are sent. Any compatible protocol 1047 * extensions must be negotiated during the 1048 * preparatory phase. 1049 */ 1050 1051 static void 1052 client_process_buffered_input_packets(void) 1053 { 1054 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL); 1055 } 1056 1057 /* scan buf[] for '~' before sending data to the peer */ 1058 1059 static int 1060 simple_escape_filter(Channel *c, char *buf, int len) 1061 { 1062 /* XXX we assume c->extended is writeable */ 1063 return process_escapes(&c->input, &c->output, &c->extended, buf, len); 1064 } 1065 1066 static void 1067 client_channel_closed(int id, void *arg) 1068 { 1069 if (id != session_ident) 1070 error("client_channel_closed: id %d != session_ident %d", 1071 id, session_ident); 1072 channel_cancel_cleanup(id); 1073 session_closed = 1; 1074 if (in_raw_mode()) 1075 leave_raw_mode(); 1076 } 1077 1078 /* 1079 * Implements the interactive session with the server. This is called after 1080 * the user has been authenticated, and a command has been started on the 1081 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character 1082 * used as an escape character for terminating or suspending the session. 1083 */ 1084 1085 int 1086 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id) 1087 { 1088 fd_set *readset = NULL, *writeset = NULL; 1089 double start_time, total_time; 1090 int max_fd = 0, max_fd2 = 0, len, rekeying = 0, nalloc = 0; 1091 char buf[100]; 1092 1093 debug("Entering interactive session."); 1094 1095 start_time = get_current_time(); 1096 1097 /* Initialize variables. */ 1098 escape_pending = 0; 1099 last_was_cr = 1; 1100 exit_status = -1; 1101 stdin_eof = 0; 1102 buffer_high = 64 * 1024; 1103 connection_in = packet_get_connection_in(); 1104 connection_out = packet_get_connection_out(); 1105 max_fd = MAX(connection_in, connection_out); 1106 1107 if (!compat20) { 1108 /* enable nonblocking unless tty */ 1109 if (!isatty(fileno(stdin))) 1110 set_nonblock(fileno(stdin)); 1111 if (!isatty(fileno(stdout))) 1112 set_nonblock(fileno(stdout)); 1113 if (!isatty(fileno(stderr))) 1114 set_nonblock(fileno(stderr)); 1115 max_fd = MAX(max_fd, fileno(stdin)); 1116 max_fd = MAX(max_fd, fileno(stdout)); 1117 max_fd = MAX(max_fd, fileno(stderr)); 1118 } 1119 stdin_bytes = 0; 1120 stdout_bytes = 0; 1121 stderr_bytes = 0; 1122 quit_pending = 0; 1123 escape_char = escape_char_arg; 1124 1125 /* Initialize buffers. */ 1126 buffer_init(&stdin_buffer); 1127 buffer_init(&stdout_buffer); 1128 buffer_init(&stderr_buffer); 1129 1130 client_init_dispatch(); 1131 1132 /* 1133 * Set signal handlers to restore non-blocking mode, but 1134 * don't overwrite SIG_IGN - matches behavious from rsh(1). 1135 */ 1136 if (signal(SIGINT, SIG_IGN) != SIG_IGN) 1137 signal(SIGINT, signal_handler); 1138 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) 1139 signal(SIGQUIT, signal_handler); 1140 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) 1141 signal(SIGTERM, signal_handler); 1142 if (have_pty) 1143 signal(SIGWINCH, window_change_handler); 1144 1145 if (have_pty) 1146 enter_raw_mode(); 1147 1148 if (compat20) { 1149 session_ident = ssh2_chan_id; 1150 if (escape_char != SSH_ESCAPECHAR_NONE) 1151 channel_register_filter(session_ident, 1152 simple_escape_filter); 1153 if (session_ident != -1) 1154 channel_register_cleanup(session_ident, 1155 client_channel_closed); 1156 } else { 1157 /* Check if we should immediately send eof on stdin. */ 1158 client_check_initial_eof_on_stdin(); 1159 } 1160 1161 /* Main loop of the client for the interactive session mode. */ 1162 while (!quit_pending) { 1163 1164 /* Process buffered packets sent by the server. */ 1165 client_process_buffered_input_packets(); 1166 1167 if (compat20 && session_closed && !channel_still_open()) 1168 break; 1169 1170 rekeying = (xxx_kex != NULL && !xxx_kex->done); 1171 1172 if (rekeying) { 1173 debug("rekeying in progress"); 1174 } else { 1175 /* 1176 * Make packets of buffered stdin data, and buffer 1177 * them for sending to the server. 1178 */ 1179 if (!compat20) 1180 client_make_packets_from_stdin_data(); 1181 1182 /* 1183 * Make packets from buffered channel data, and 1184 * enqueue them for sending to the server. 1185 */ 1186 if (packet_not_very_much_data_to_write()) 1187 channel_output_poll(); 1188 1189 /* 1190 * Check if the window size has changed, and buffer a 1191 * message about it to the server if so. 1192 */ 1193 client_check_window_change(); 1194 1195 if (quit_pending) 1196 break; 1197 } 1198 /* 1199 * Wait until we have something to do (something becomes 1200 * available on one of the descriptors). 1201 */ 1202 max_fd2 = max_fd; 1203 client_wait_until_can_do_something(&readset, &writeset, 1204 &max_fd2, &nalloc, rekeying); 1205 1206 if (quit_pending) 1207 break; 1208 1209 /* Do channel operations unless rekeying in progress. */ 1210 if (!rekeying) { 1211 channel_after_select(readset, writeset); 1212 if (need_rekeying || packet_need_rekeying()) { 1213 debug("rekey limit reached, need rekeying"); 1214 kex_send_kexinit(xxx_kex); 1215 need_rekeying = 0; 1216 } 1217 } 1218 1219 /* Buffer input from the connection. */ 1220 client_process_net_input(readset); 1221 1222 if (quit_pending) 1223 break; 1224 1225 if (!compat20) { 1226 /* Buffer data from stdin */ 1227 client_process_input(readset); 1228 /* 1229 * Process output to stdout and stderr. Output to 1230 * the connection is processed elsewhere (above). 1231 */ 1232 client_process_output(writeset); 1233 } 1234 1235 /* Send as much buffered packet data as possible to the sender. */ 1236 if (FD_ISSET(connection_out, writeset)) 1237 packet_write_poll(); 1238 } 1239 if (readset) 1240 xfree(readset); 1241 if (writeset) 1242 xfree(writeset); 1243 1244 /* Terminate the session. */ 1245 1246 /* Stop watching for window change. */ 1247 if (have_pty) 1248 signal(SIGWINCH, SIG_DFL); 1249 1250 channel_free_all(); 1251 1252 if (have_pty) 1253 leave_raw_mode(); 1254 1255 /* restore blocking io */ 1256 if (!isatty(fileno(stdin))) 1257 unset_nonblock(fileno(stdin)); 1258 if (!isatty(fileno(stdout))) 1259 unset_nonblock(fileno(stdout)); 1260 if (!isatty(fileno(stderr))) 1261 unset_nonblock(fileno(stderr)); 1262 1263 if (received_signal) { 1264 if (in_non_blocking_mode) /* XXX */ 1265 leave_non_blocking(); 1266 fatal("Killed by signal %d.", (int) received_signal); 1267 } 1268 1269 /* 1270 * In interactive mode (with pseudo tty) display a message indicating 1271 * that the connection has been closed. 1272 */ 1273 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) { 1274 snprintf(buf, sizeof buf, 1275 gettext("Connection to %.64s closed.\n"), 1276 host); 1277 buffer_append(&stderr_buffer, buf, strlen(buf)); 1278 } 1279 1280 /* Output any buffered data for stdout. */ 1281 while (buffer_len(&stdout_buffer) > 0) { 1282 len = write(fileno(stdout), buffer_ptr(&stdout_buffer), 1283 buffer_len(&stdout_buffer)); 1284 if (len <= 0) { 1285 error("Write failed flushing stdout buffer."); 1286 break; 1287 } 1288 buffer_consume(&stdout_buffer, len); 1289 stdout_bytes += len; 1290 } 1291 1292 /* Output any buffered data for stderr. */ 1293 while (buffer_len(&stderr_buffer) > 0) { 1294 len = write(fileno(stderr), buffer_ptr(&stderr_buffer), 1295 buffer_len(&stderr_buffer)); 1296 if (len <= 0) { 1297 error("Write failed flushing stderr buffer."); 1298 break; 1299 } 1300 buffer_consume(&stderr_buffer, len); 1301 stderr_bytes += len; 1302 } 1303 1304 /* Clear and free any buffers. */ 1305 memset(buf, 0, sizeof(buf)); 1306 buffer_free(&stdin_buffer); 1307 buffer_free(&stdout_buffer); 1308 buffer_free(&stderr_buffer); 1309 1310 /* Report bytes transferred, and transfer rates. */ 1311 total_time = get_current_time() - start_time; 1312 debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds", 1313 stdin_bytes, stdout_bytes, stderr_bytes, total_time); 1314 if (total_time > 0) 1315 debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f", 1316 stdin_bytes / total_time, stdout_bytes / total_time, 1317 stderr_bytes / total_time); 1318 1319 /* Return the exit status of the program. */ 1320 debug("Exit status %d", exit_status); 1321 return exit_status; 1322 } 1323 1324 /*********/ 1325 1326 static void 1327 client_input_stdout_data(int type, u_int32_t seq, void *ctxt) 1328 { 1329 u_int data_len; 1330 char *data = packet_get_string(&data_len); 1331 packet_check_eom(); 1332 buffer_append(&stdout_buffer, data, data_len); 1333 memset(data, 0, data_len); 1334 xfree(data); 1335 } 1336 static void 1337 client_input_stderr_data(int type, u_int32_t seq, void *ctxt) 1338 { 1339 u_int data_len; 1340 char *data = packet_get_string(&data_len); 1341 packet_check_eom(); 1342 buffer_append(&stderr_buffer, data, data_len); 1343 memset(data, 0, data_len); 1344 xfree(data); 1345 } 1346 static void 1347 client_input_exit_status(int type, u_int32_t seq, void *ctxt) 1348 { 1349 exit_status = packet_get_int(); 1350 packet_check_eom(); 1351 /* Acknowledge the exit. */ 1352 packet_start(SSH_CMSG_EXIT_CONFIRMATION); 1353 packet_send(); 1354 /* 1355 * Must wait for packet to be sent since we are 1356 * exiting the loop. 1357 */ 1358 packet_write_wait(); 1359 /* Flag that we want to exit. */ 1360 quit_pending = 1; 1361 } 1362 1363 static Channel * 1364 client_request_forwarded_tcpip(const char *request_type, int rchan) 1365 { 1366 Channel *c = NULL; 1367 char *listen_address, *originator_address; 1368 int listen_port, originator_port; 1369 int sock; 1370 1371 /* Get rest of the packet */ 1372 listen_address = packet_get_string(NULL); 1373 listen_port = packet_get_int(); 1374 originator_address = packet_get_string(NULL); 1375 originator_port = packet_get_int(); 1376 packet_check_eom(); 1377 1378 debug("client_request_forwarded_tcpip: listen %s port %d, originator %s port %d", 1379 listen_address, listen_port, originator_address, originator_port); 1380 1381 sock = channel_connect_by_listen_address(listen_port); 1382 if (sock < 0) { 1383 xfree(originator_address); 1384 xfree(listen_address); 1385 return NULL; 1386 } 1387 c = channel_new("forwarded-tcpip", 1388 SSH_CHANNEL_CONNECTING, sock, sock, -1, 1389 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0, 1390 xstrdup(originator_address), 1); 1391 xfree(originator_address); 1392 xfree(listen_address); 1393 return c; 1394 } 1395 1396 static Channel * 1397 client_request_x11(const char *request_type, int rchan) 1398 { 1399 Channel *c = NULL; 1400 char *originator; 1401 int originator_port; 1402 int sock; 1403 1404 if (!options.forward_x11) { 1405 error("Warning: ssh server tried X11 forwarding."); 1406 error("Warning: this is probably a break in attempt by a malicious server."); 1407 return NULL; 1408 } 1409 originator = packet_get_string(NULL); 1410 if (datafellows & SSH_BUG_X11FWD) { 1411 debug2("buggy server: x11 request w/o originator_port"); 1412 originator_port = 0; 1413 } else { 1414 originator_port = packet_get_int(); 1415 } 1416 packet_check_eom(); 1417 /* XXX check permission */ 1418 debug("client_request_x11: request from %s %d", originator, 1419 originator_port); 1420 xfree(originator); 1421 sock = x11_connect_display(); 1422 if (sock < 0) 1423 return NULL; 1424 c = channel_new("x11", 1425 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 1426 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, 1427 xstrdup("x11"), 1); 1428 c->force_drain = 1; 1429 return c; 1430 } 1431 1432 static Channel * 1433 client_request_agent(const char *request_type, int rchan) 1434 { 1435 Channel *c = NULL; 1436 int sock; 1437 1438 if (!options.forward_agent) { 1439 error("Warning: ssh server tried agent forwarding."); 1440 error("Warning: this is probably a break in attempt by a malicious server."); 1441 return NULL; 1442 } 1443 sock = ssh_get_authentication_socket(); 1444 if (sock < 0) 1445 return NULL; 1446 c = channel_new("authentication agent connection", 1447 SSH_CHANNEL_OPEN, sock, sock, -1, 1448 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0, 1449 xstrdup("authentication agent connection"), 1); 1450 c->force_drain = 1; 1451 return c; 1452 } 1453 1454 /* XXXX move to generic input handler */ 1455 static void 1456 client_input_channel_open(int type, u_int32_t seq, void *ctxt) 1457 { 1458 Channel *c = NULL; 1459 char *ctype; 1460 int rchan; 1461 u_int rmaxpack, rwindow, len; 1462 1463 ctype = packet_get_string(&len); 1464 rchan = packet_get_int(); 1465 rwindow = packet_get_int(); 1466 rmaxpack = packet_get_int(); 1467 1468 debug("client_input_channel_open: ctype %s rchan %d win %d max %d", 1469 ctype, rchan, rwindow, rmaxpack); 1470 1471 if (strcmp(ctype, "forwarded-tcpip") == 0) { 1472 c = client_request_forwarded_tcpip(ctype, rchan); 1473 } else if (strcmp(ctype, "x11") == 0) { 1474 c = client_request_x11(ctype, rchan); 1475 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) { 1476 c = client_request_agent(ctype, rchan); 1477 } 1478 /* XXX duplicate : */ 1479 if (c != NULL) { 1480 debug("confirm %s", ctype); 1481 c->remote_id = rchan; 1482 c->remote_window = rwindow; 1483 c->remote_maxpacket = rmaxpack; 1484 if (c->type != SSH_CHANNEL_CONNECTING) { 1485 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION); 1486 packet_put_int(c->remote_id); 1487 packet_put_int(c->self); 1488 packet_put_int(c->local_window); 1489 packet_put_int(c->local_maxpacket); 1490 packet_send(); 1491 } 1492 } else { 1493 debug("failure %s", ctype); 1494 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE); 1495 packet_put_int(rchan); 1496 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED); 1497 if (!(datafellows & SSH_BUG_OPENFAILURE)) { 1498 packet_put_utf8_cstring("open failed"); 1499 packet_put_cstring(""); 1500 } 1501 packet_send(); 1502 } 1503 xfree(ctype); 1504 } 1505 1506 static void 1507 client_input_channel_req(int type, u_int32_t seq, void *ctxt) 1508 { 1509 Channel *c = NULL; 1510 int id, reply, success = 0; 1511 char *rtype; 1512 1513 id = packet_get_int(); 1514 rtype = packet_get_string(NULL); 1515 reply = packet_get_char(); 1516 1517 debug("client_input_channel_req: channel %d rtype %s reply %d", 1518 id, rtype, reply); 1519 1520 if (session_ident == -1) { 1521 error("client_input_channel_req: no channel %d", session_ident); 1522 } else if (id != session_ident) { 1523 error("client_input_channel_req: channel %d: wrong channel: %d", 1524 session_ident, id); 1525 } 1526 c = channel_lookup(id); 1527 if (c == NULL) { 1528 error("client_input_channel_req: channel %d: unknown channel", id); 1529 } else if (strcmp(rtype, "eow@openssh.com") == 0) { 1530 packet_check_eom(); 1531 chan_rcvd_eow(c); 1532 } else if (strcmp(rtype, "exit-status") == 0) { 1533 success = 1; 1534 exit_status = packet_get_int(); 1535 packet_check_eom(); 1536 } 1537 if (reply) { 1538 packet_start(success ? 1539 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE); 1540 packet_put_int(c->remote_id); 1541 packet_send(); 1542 } 1543 xfree(rtype); 1544 } 1545 1546 static void 1547 client_input_global_request(int type, u_int32_t seq, void *ctxt) 1548 { 1549 char *rtype; 1550 int want_reply; 1551 int success = 0; 1552 1553 rtype = packet_get_string(NULL); 1554 want_reply = packet_get_char(); 1555 debug("client_input_global_request: rtype %s want_reply %d", rtype, want_reply); 1556 if (want_reply) { 1557 packet_start(success ? 1558 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE); 1559 packet_send(); 1560 packet_write_wait(); 1561 } 1562 xfree(rtype); 1563 } 1564 1565 static void 1566 client_init_dispatch_20(void) 1567 { 1568 dispatch_init(&dispatch_protocol_error); 1569 1570 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 1571 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data); 1572 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof); 1573 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data); 1574 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open); 1575 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 1576 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 1577 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req); 1578 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust); 1579 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request); 1580 1581 /* rekeying */ 1582 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit); 1583 1584 /* global request reply messages */ 1585 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply); 1586 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply); 1587 } 1588 1589 static void 1590 client_init_dispatch_13(void) 1591 { 1592 dispatch_init(NULL); 1593 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close); 1594 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation); 1595 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data); 1596 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation); 1597 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure); 1598 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open); 1599 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status); 1600 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data); 1601 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data); 1602 1603 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ? 1604 &auth_input_open_request : &deny_input_open); 1605 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ? 1606 &x11_input_open : &deny_input_open); 1607 } 1608 1609 static void 1610 client_init_dispatch_15(void) 1611 { 1612 client_init_dispatch_13(); 1613 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof); 1614 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose); 1615 } 1616 1617 static void 1618 client_init_dispatch(void) 1619 { 1620 if (compat20) 1621 client_init_dispatch_20(); 1622 else if (compat13) 1623 client_init_dispatch_13(); 1624 else 1625 client_init_dispatch_15(); 1626 }