1 /* $NetBSD: ssh.c,v 1.11 2012/12/12 17:42:40 christos Exp $ */ 2 /* $OpenBSD: ssh.c,v 1.370 2012/07/06 01:47:38 djm Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * Ssh client program. This program can be used to log into a remote machine. 8 * The software supports strong authentication, encryption, and forwarding 9 * of X11, TCP/IP, and authentication connections. 10 * 11 * As far as I am concerned, the code I have written for this software 12 * can be used freely for any purpose. Any derived versions of this 13 * software must be clearly marked as such, and if the derived work is 14 * incompatible with the protocol description in the RFC file, it must be 15 * called by a name other than "ssh" or "Secure Shell". 16 * 17 * Copyright (c) 1999 Niels Provos. All rights reserved. 18 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved. 19 * 20 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu> 21 * in Canada (German citizen). 22 * 23 * Redistribution and use in source and binary forms, with or without 24 * modification, are permitted provided that the following conditions 25 * are met: 26 * 1. Redistributions of source code must retain the above copyright 27 * notice, this list of conditions and the following disclaimer. 28 * 2. Redistributions in binary form must reproduce the above copyright 29 * notice, this list of conditions and the following disclaimer in the 30 * documentation and/or other materials provided with the distribution. 31 * 32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 42 */ 43 44 #include "includes.h" 45 __RCSID("$NetBSD: ssh.c,v 1.11 2012/12/12 17:42:40 christos Exp $"); 46 #include <sys/types.h> 47 #include <sys/param.h> 48 #include <sys/ioctl.h> 49 #include <sys/param.h> 50 #include <sys/queue.h> 51 #include <sys/resource.h> 52 #include <sys/socket.h> 53 #include <sys/stat.h> 54 #include <sys/time.h> 55 #include <sys/wait.h> 56 57 #include <ctype.h> 58 #include <errno.h> 59 #include <fcntl.h> 60 #include <netdb.h> 61 #include <paths.h> 62 #include <pwd.h> 63 #include <signal.h> 64 #include <stddef.h> 65 #include <stdio.h> 66 #include <stdlib.h> 67 #include <string.h> 68 #include <unistd.h> 69 70 #include <openssl/evp.h> 71 #include <openssl/err.h> 72 73 #include "xmalloc.h" 74 #include "ssh.h" 75 #include "ssh1.h" 76 #include "ssh2.h" 77 #include "canohost.h" 78 #include "compat.h" 79 #include "cipher.h" 80 #include "packet.h" 81 #include "buffer.h" 82 #include "channels.h" 83 #include "key.h" 84 #include "authfd.h" 85 #include "authfile.h" 86 #include "pathnames.h" 87 #include "dispatch.h" 88 #include "clientloop.h" 89 #include "log.h" 90 #include "readconf.h" 91 #include "sshconnect.h" 92 #include "misc.h" 93 #include "kex.h" 94 #include "mac.h" 95 #include "sshpty.h" 96 #include "match.h" 97 #include "msg.h" 98 #include "uidswap.h" 99 #include "roaming.h" 100 #include "version.h" 101 102 #ifdef ENABLE_PKCS11 103 #include "ssh-pkcs11.h" 104 #endif 105 106 extern char *__progname; 107 108 /* Flag indicating whether debug mode is on. May be set on the command line. */ 109 int debug_flag = 0; 110 111 /* Flag indicating whether a tty should be requested */ 112 int tty_flag = 0; 113 114 /* don't exec a shell */ 115 int no_shell_flag = 0; 116 117 /* 118 * Flag indicating that nothing should be read from stdin. This can be set 119 * on the command line. 120 */ 121 int stdin_null_flag = 0; 122 123 /* 124 * Flag indicating that the current process should be backgrounded and 125 * a new slave launched in the foreground for ControlPersist. 126 */ 127 int need_controlpersist_detach = 0; 128 129 /* Copies of flags for ControlPersist foreground slave */ 130 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty; 131 132 /* 133 * Flag indicating that ssh should fork after authentication. This is useful 134 * so that the passphrase can be entered manually, and then ssh goes to the 135 * background. 136 */ 137 int fork_after_authentication_flag = 0; 138 139 /* forward stdio to remote host and port */ 140 char *stdio_forward_host = NULL; 141 int stdio_forward_port = 0; 142 143 /* 144 * General data structure for command line options and options configurable 145 * in configuration files. See readconf.h. 146 */ 147 Options options; 148 149 /* optional user configfile */ 150 char *config = NULL; 151 152 /* 153 * Name of the host we are connecting to. This is the name given on the 154 * command line, or the HostName specified for the user-supplied name in a 155 * configuration file. 156 */ 157 char *host; 158 159 /* socket address the host resolves to */ 160 struct sockaddr_storage hostaddr; 161 162 /* Private host keys. */ 163 Sensitive sensitive_data; 164 165 /* Original real UID. */ 166 uid_t original_real_uid; 167 uid_t original_effective_uid; 168 169 /* command to be executed */ 170 Buffer command; 171 172 /* Should we execute a command or invoke a subsystem? */ 173 int subsystem_flag = 0; 174 175 /* # of replies received for global requests */ 176 static int remote_forward_confirms_received = 0; 177 178 /* mux.c */ 179 extern int muxserver_sock; 180 extern u_int muxclient_command; 181 182 183 /* Prints a help message to the user. This function never returns. */ 184 185 __dead static void 186 usage(void) 187 { 188 fprintf(stderr, 189 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n" 190 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n" 191 " [-I pkcs11] [-i identity_file]\n" 192 " [-L [bind_address:]port:host:hostport]\n" 193 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n" 194 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n" 195 " [-W host:port] [-w local_tun[:remote_tun]]\n" 196 " [user@]hostname [command]\n" 197 ); 198 exit(255); 199 } 200 201 static int ssh_session(void); 202 static int ssh_session2(void); 203 static void load_public_identity_files(void); 204 static void main_sigchld_handler(int); 205 206 /* from muxclient.c */ 207 void muxclient(const char *); 208 void muxserver_listen(void); 209 210 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */ 211 static void 212 tilde_expand_paths(char **paths, u_int num_paths) 213 { 214 u_int i; 215 char *cp; 216 217 for (i = 0; i < num_paths; i++) { 218 cp = tilde_expand_filename(paths[i], original_real_uid); 219 xfree(paths[i]); 220 paths[i] = cp; 221 } 222 } 223 224 /* 225 * Main program for the ssh client. 226 */ 227 int 228 main(int ac, char **av) 229 { 230 int i, r, opt, exit_status, use_syslog; 231 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg; 232 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV]; 233 struct stat st; 234 struct passwd *pw; 235 int dummy, timeout_ms; 236 extern int optind, optreset; 237 extern char *optarg; 238 struct servent *sp; 239 Forward fwd; 240 241 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 242 sanitise_stdfd(); 243 244 /* 245 * Discard other fds that are hanging around. These can cause problem 246 * with backgrounded ssh processes started by ControlPersist. 247 */ 248 closefrom(STDERR_FILENO + 1); 249 250 /* 251 * Save the original real uid. It will be needed later (uid-swapping 252 * may clobber the real uid). 253 */ 254 original_real_uid = getuid(); 255 original_effective_uid = geteuid(); 256 257 /* 258 * Use uid-swapping to give up root privileges for the duration of 259 * option processing. We will re-instantiate the rights when we are 260 * ready to create the privileged port, and will permanently drop 261 * them when the port has been created (actually, when the connection 262 * has been made, as we may need to create the port several times). 263 */ 264 PRIV_END; 265 266 /* If we are installed setuid root be careful to not drop core. */ 267 if (original_real_uid != original_effective_uid) { 268 struct rlimit rlim; 269 rlim.rlim_cur = rlim.rlim_max = 0; 270 if (setrlimit(RLIMIT_CORE, &rlim) < 0) 271 fatal("setrlimit failed: %.100s", strerror(errno)); 272 } 273 /* Get user data. */ 274 pw = getpwuid(original_real_uid); 275 if (!pw) { 276 logit("You don't exist, go away!"); 277 exit(255); 278 } 279 /* Take a copy of the returned structure. */ 280 pw = pwcopy(pw); 281 282 /* 283 * Set our umask to something reasonable, as some files are created 284 * with the default umask. This will make them world-readable but 285 * writable only by the owner, which is ok for all files for which we 286 * don't set the modes explicitly. 287 */ 288 umask(022); 289 290 /* 291 * Initialize option structure to indicate that no values have been 292 * set. 293 */ 294 initialize_options(&options); 295 296 /* Parse command-line arguments. */ 297 host = NULL; 298 use_syslog = 0; 299 argv0 = av[0]; 300 301 again: 302 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx" 303 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) { 304 switch (opt) { 305 case '1': 306 options.protocol = SSH_PROTO_1; 307 break; 308 case '2': 309 options.protocol = SSH_PROTO_2; 310 break; 311 case '4': 312 options.address_family = AF_INET; 313 break; 314 case '6': 315 options.address_family = AF_INET6; 316 break; 317 case 'n': 318 stdin_null_flag = 1; 319 break; 320 case 'f': 321 fork_after_authentication_flag = 1; 322 stdin_null_flag = 1; 323 break; 324 case 'x': 325 options.forward_x11 = 0; 326 break; 327 case 'X': 328 options.forward_x11 = 1; 329 break; 330 case 'y': 331 use_syslog = 1; 332 break; 333 case 'Y': 334 options.forward_x11 = 1; 335 options.forward_x11_trusted = 1; 336 break; 337 case 'g': 338 options.gateway_ports = 1; 339 break; 340 case 'O': 341 if (stdio_forward_host != NULL) 342 fatal("Cannot specify multiplexing " 343 "command with -W"); 344 else if (muxclient_command != 0) 345 fatal("Multiplexing command already specified"); 346 if (strcmp(optarg, "check") == 0) 347 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK; 348 else if (strcmp(optarg, "forward") == 0) 349 muxclient_command = SSHMUX_COMMAND_FORWARD; 350 else if (strcmp(optarg, "exit") == 0) 351 muxclient_command = SSHMUX_COMMAND_TERMINATE; 352 else if (strcmp(optarg, "stop") == 0) 353 muxclient_command = SSHMUX_COMMAND_STOP; 354 else if (strcmp(optarg, "cancel") == 0) 355 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD; 356 else 357 fatal("Invalid multiplex command."); 358 break; 359 case 'P': /* deprecated */ 360 options.use_privileged_port = 0; 361 break; 362 case 'a': 363 options.forward_agent = 0; 364 break; 365 case 'A': 366 options.forward_agent = 1; 367 break; 368 case 'k': 369 options.gss_deleg_creds = 0; 370 break; 371 case 'K': 372 options.gss_authentication = 1; 373 options.gss_deleg_creds = 1; 374 break; 375 case 'i': 376 if (stat(optarg, &st) < 0) { 377 fprintf(stderr, "Warning: Identity file %s " 378 "not accessible: %s.\n", optarg, 379 strerror(errno)); 380 break; 381 } 382 if (options.num_identity_files >= 383 SSH_MAX_IDENTITY_FILES) 384 fatal("Too many identity files specified " 385 "(max %d)", SSH_MAX_IDENTITY_FILES); 386 options.identity_files[options.num_identity_files++] = 387 xstrdup(optarg); 388 break; 389 case 'I': 390 #ifdef ENABLE_PKCS11 391 options.pkcs11_provider = xstrdup(optarg); 392 #else 393 fprintf(stderr, "no support for PKCS#11.\n"); 394 #endif 395 break; 396 case 't': 397 if (options.request_tty == REQUEST_TTY_YES) 398 options.request_tty = REQUEST_TTY_FORCE; 399 else 400 options.request_tty = REQUEST_TTY_YES; 401 break; 402 case 'v': 403 if (debug_flag == 0) { 404 debug_flag = 1; 405 options.log_level = SYSLOG_LEVEL_DEBUG1; 406 } else { 407 if (options.log_level < SYSLOG_LEVEL_DEBUG3) 408 options.log_level++; 409 break; 410 } 411 /* FALLTHROUGH */ 412 case 'V': 413 fprintf(stderr, "%s, %s\n", 414 SSH_VERSION, SSLeay_version(SSLEAY_VERSION)); 415 if (opt == 'V') 416 exit(0); 417 break; 418 case 'w': 419 if (options.tun_open == -1) 420 options.tun_open = SSH_TUNMODE_DEFAULT; 421 options.tun_local = a2tun(optarg, &options.tun_remote); 422 if (options.tun_local == SSH_TUNID_ERR) { 423 fprintf(stderr, 424 "Bad tun device '%s'\n", optarg); 425 exit(255); 426 } 427 break; 428 case 'W': 429 if (stdio_forward_host != NULL) 430 fatal("stdio forward already specified"); 431 if (muxclient_command != 0) 432 fatal("Cannot specify stdio forward with -O"); 433 if (parse_forward(&fwd, optarg, 1, 0)) { 434 stdio_forward_host = fwd.listen_host; 435 stdio_forward_port = fwd.listen_port; 436 xfree(fwd.connect_host); 437 } else { 438 fprintf(stderr, 439 "Bad stdio forwarding specification '%s'\n", 440 optarg); 441 exit(255); 442 } 443 options.request_tty = REQUEST_TTY_NO; 444 no_shell_flag = 1; 445 options.clear_forwardings = 1; 446 options.exit_on_forward_failure = 1; 447 break; 448 case 'q': 449 options.log_level = SYSLOG_LEVEL_QUIET; 450 break; 451 case 'e': 452 if (optarg[0] == '^' && optarg[2] == 0 && 453 (u_char) optarg[1] >= 64 && 454 (u_char) optarg[1] < 128) 455 options.escape_char = (u_char) optarg[1] & 31; 456 else if (strlen(optarg) == 1) 457 options.escape_char = (u_char) optarg[0]; 458 else if (strcmp(optarg, "none") == 0) 459 options.escape_char = SSH_ESCAPECHAR_NONE; 460 else { 461 fprintf(stderr, "Bad escape character '%s'.\n", 462 optarg); 463 exit(255); 464 } 465 break; 466 case 'c': 467 if (ciphers_valid(optarg)) { 468 /* SSH2 only */ 469 options.ciphers = xstrdup(optarg); 470 options.cipher = SSH_CIPHER_INVALID; 471 } else { 472 /* SSH1 only */ 473 options.cipher = cipher_number(optarg); 474 if (options.cipher == -1) { 475 fprintf(stderr, 476 "Unknown cipher type '%s'\n", 477 optarg); 478 exit(255); 479 } 480 if (options.cipher == SSH_CIPHER_3DES) 481 options.ciphers = __UNCONST("3des-cbc"); 482 else if (options.cipher == SSH_CIPHER_BLOWFISH) 483 options.ciphers = 484 __UNCONST("blowfish-cbc"); 485 else 486 options.ciphers = (char *)-1; 487 } 488 break; 489 case 'm': 490 if (mac_valid(optarg)) 491 options.macs = xstrdup(optarg); 492 else { 493 fprintf(stderr, "Unknown mac type '%s'\n", 494 optarg); 495 exit(255); 496 } 497 break; 498 case 'M': 499 if (options.control_master == SSHCTL_MASTER_YES) 500 options.control_master = SSHCTL_MASTER_ASK; 501 else 502 options.control_master = SSHCTL_MASTER_YES; 503 break; 504 case 'p': 505 options.port = a2port(optarg); 506 if (options.port <= 0) { 507 fprintf(stderr, "Bad port '%s'\n", optarg); 508 exit(255); 509 } 510 break; 511 case 'l': 512 options.user = optarg; 513 break; 514 515 case 'L': 516 if (parse_forward(&fwd, optarg, 0, 0)) 517 add_local_forward(&options, &fwd); 518 else { 519 fprintf(stderr, 520 "Bad local forwarding specification '%s'\n", 521 optarg); 522 exit(255); 523 } 524 break; 525 526 case 'R': 527 if (parse_forward(&fwd, optarg, 0, 1)) { 528 add_remote_forward(&options, &fwd); 529 } else { 530 fprintf(stderr, 531 "Bad remote forwarding specification " 532 "'%s'\n", optarg); 533 exit(255); 534 } 535 break; 536 537 case 'D': 538 if (parse_forward(&fwd, optarg, 1, 0)) { 539 add_local_forward(&options, &fwd); 540 } else { 541 fprintf(stderr, 542 "Bad dynamic forwarding specification " 543 "'%s'\n", optarg); 544 exit(255); 545 } 546 break; 547 548 case 'C': 549 options.compression = 1; 550 break; 551 case 'N': 552 no_shell_flag = 1; 553 options.request_tty = REQUEST_TTY_NO; 554 break; 555 case 'T': 556 options.request_tty = REQUEST_TTY_NO; 557 /* ensure that the user doesn't try to backdoor a */ 558 /* null cipher switch on an interactive session */ 559 /* so explicitly disable it no matter what */ 560 options.none_switch = 0; 561 break; 562 case 'o': 563 dummy = 1; 564 line = xstrdup(optarg); 565 if (process_config_line(&options, host ? host : "", 566 line, "command-line", 0, &dummy) != 0) 567 exit(255); 568 xfree(line); 569 break; 570 case 's': 571 subsystem_flag = 1; 572 break; 573 case 'S': 574 if (options.control_path != NULL) 575 free(options.control_path); 576 options.control_path = xstrdup(optarg); 577 break; 578 case 'b': 579 options.bind_address = optarg; 580 break; 581 case 'F': 582 config = optarg; 583 break; 584 default: 585 usage(); 586 } 587 } 588 589 ac -= optind; 590 av += optind; 591 592 if (ac > 0 && !host) { 593 if (strrchr(*av, '@')) { 594 p = xstrdup(*av); 595 cp = strrchr(p, '@'); 596 if (cp == NULL || cp == p) 597 usage(); 598 options.user = p; 599 *cp = '\0'; 600 host = ++cp; 601 } else 602 host = *av; 603 if (ac > 1) { 604 optind = optreset = 1; 605 goto again; 606 } 607 ac--, av++; 608 } 609 610 /* Check that we got a host name. */ 611 if (!host) 612 usage(); 613 614 OpenSSL_add_all_algorithms(); 615 ERR_load_crypto_strings(); 616 617 /* Initialize the command to execute on remote host. */ 618 buffer_init(&command); 619 620 /* 621 * Save the command to execute on the remote host in a buffer. There 622 * is no limit on the length of the command, except by the maximum 623 * packet size. Also sets the tty flag if there is no command. 624 */ 625 if (!ac) { 626 /* No command specified - execute shell on a tty. */ 627 if (subsystem_flag) { 628 fprintf(stderr, 629 "You must specify a subsystem to invoke.\n"); 630 usage(); 631 } 632 } else { 633 /* A command has been specified. Store it into the buffer. */ 634 for (i = 0; i < ac; i++) { 635 if (i) 636 buffer_append(&command, " ", 1); 637 buffer_append(&command, av[i], strlen(av[i])); 638 } 639 } 640 641 /* Cannot fork to background if no command. */ 642 if (fork_after_authentication_flag && buffer_len(&command) == 0 && 643 !no_shell_flag) 644 fatal("Cannot fork into background without a command " 645 "to execute."); 646 647 /* 648 * Initialize "log" output. Since we are the client all output 649 * actually goes to stderr. 650 */ 651 log_init(argv0, 652 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level, 653 SYSLOG_FACILITY_USER, !use_syslog); 654 655 /* 656 * Read per-user configuration file. Ignore the system wide config 657 * file if the user specifies a config file on the command line. 658 */ 659 if (config != NULL) { 660 if (!read_config_file(config, host, &options, 0)) 661 fatal("Can't open user config file %.100s: " 662 "%.100s", config, strerror(errno)); 663 } else { 664 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir, 665 _PATH_SSH_USER_CONFFILE); 666 if (r > 0 && (size_t)r < sizeof(buf)) 667 (void)read_config_file(buf, host, &options, 1); 668 669 /* Read systemwide configuration file after user config. */ 670 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host, 671 &options, 0); 672 } 673 674 /* Fill configuration defaults. */ 675 fill_default_options(&options); 676 677 channel_set_af(options.address_family); 678 679 /* reinit */ 680 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog); 681 682 if (options.request_tty == REQUEST_TTY_YES || 683 options.request_tty == REQUEST_TTY_FORCE) 684 tty_flag = 1; 685 686 /* Allocate a tty by default if no command specified. */ 687 if (buffer_len(&command) == 0) 688 tty_flag = options.request_tty != REQUEST_TTY_NO; 689 690 /* Force no tty */ 691 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0) 692 tty_flag = 0; 693 /* Do not allocate a tty if stdin is not a tty. */ 694 if ((!isatty(fileno(stdin)) || stdin_null_flag) && 695 options.request_tty != REQUEST_TTY_FORCE) { 696 if (tty_flag) 697 logit("Pseudo-terminal will not be allocated because " 698 "stdin is not a terminal."); 699 tty_flag = 0; 700 } 701 702 if (options.user == NULL) 703 options.user = xstrdup(pw->pw_name); 704 705 /* Get default port if port has not been set. */ 706 if (options.port == 0) { 707 sp = getservbyname(SSH_SERVICE_NAME, "tcp"); 708 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT; 709 } 710 711 /* preserve host name given on command line for %n expansion */ 712 host_arg = host; 713 if (options.hostname != NULL) { 714 host = percent_expand(options.hostname, 715 "h", host, (char *)NULL); 716 } 717 718 if (gethostname(thishost, sizeof(thishost)) == -1) 719 fatal("gethostname: %s", strerror(errno)); 720 strlcpy(shorthost, thishost, sizeof(shorthost)); 721 shorthost[strcspn(thishost, ".")] = '\0'; 722 snprintf(portstr, sizeof(portstr), "%d", options.port); 723 724 if (options.local_command != NULL) { 725 debug3("expanding LocalCommand: %s", options.local_command); 726 cp = options.local_command; 727 options.local_command = percent_expand(cp, "d", pw->pw_dir, 728 "h", host, "l", thishost, "n", host_arg, "r", options.user, 729 "p", portstr, "u", pw->pw_name, "L", shorthost, 730 (char *)NULL); 731 debug3("expanded LocalCommand: %s", options.local_command); 732 xfree(cp); 733 } 734 735 /* force lowercase for hostkey matching */ 736 if (options.host_key_alias != NULL) { 737 for (p = options.host_key_alias; *p; p++) 738 if (isupper((unsigned char)*p)) 739 *p = (char)tolower((unsigned char)*p); 740 } 741 742 if (options.proxy_command != NULL && 743 strcmp(options.proxy_command, "none") == 0) { 744 xfree(options.proxy_command); 745 options.proxy_command = NULL; 746 } 747 if (options.control_path != NULL && 748 strcmp(options.control_path, "none") == 0) { 749 xfree(options.control_path); 750 options.control_path = NULL; 751 } 752 753 if (options.control_path != NULL) { 754 cp = tilde_expand_filename(options.control_path, 755 original_real_uid); 756 xfree(options.control_path); 757 options.control_path = percent_expand(cp, "h", host, 758 "l", thishost, "n", host_arg, "r", options.user, 759 "p", portstr, "u", pw->pw_name, "L", shorthost, 760 (char *)NULL); 761 xfree(cp); 762 } 763 if (muxclient_command != 0 && options.control_path == NULL) 764 fatal("No ControlPath specified for \"-O\" command"); 765 if (options.control_path != NULL) 766 muxclient(options.control_path); 767 768 timeout_ms = options.connection_timeout * 1000; 769 770 /* Open a connection to the remote host. */ 771 if (ssh_connect(host, &hostaddr, options.port, 772 options.address_family, options.connection_attempts, &timeout_ms, 773 options.tcp_keep_alive, 774 original_effective_uid == 0 && options.use_privileged_port, 775 options.proxy_command) != 0) 776 exit(255); 777 778 if (timeout_ms > 0) 779 debug3("timeout: %d ms remain after connect", timeout_ms); 780 781 /* 782 * If we successfully made the connection, load the host private key 783 * in case we will need it later for combined rsa-rhosts 784 * authentication. This must be done before releasing extra 785 * privileges, because the file is only readable by root. 786 * If we cannot access the private keys, load the public keys 787 * instead and try to execute the ssh-keysign helper instead. 788 */ 789 sensitive_data.nkeys = 0; 790 sensitive_data.keys = NULL; 791 sensitive_data.external_keysign = 0; 792 if (options.rhosts_rsa_authentication || 793 options.hostbased_authentication) { 794 sensitive_data.nkeys = 7; 795 sensitive_data.keys = xcalloc(sensitive_data.nkeys, 796 sizeof(Key)); 797 798 PRIV_START; 799 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1, 800 _PATH_HOST_KEY_FILE, "", NULL, NULL); 801 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA, 802 _PATH_HOST_DSA_KEY_FILE, "", NULL); 803 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA, 804 _PATH_HOST_ECDSA_KEY_FILE, "", NULL); 805 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA, 806 _PATH_HOST_RSA_KEY_FILE, "", NULL); 807 sensitive_data.keys[4] = key_load_private_type(KEY_DSA, 808 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL); 809 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA, 810 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL); 811 sensitive_data.keys[6] = key_load_private_type(KEY_RSA, 812 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL); 813 PRIV_END; 814 815 if (options.hostbased_authentication == 1 && 816 sensitive_data.keys[0] == NULL && 817 sensitive_data.keys[4] == NULL && 818 sensitive_data.keys[5] == NULL && 819 sensitive_data.keys[6] == NULL) { 820 sensitive_data.keys[1] = key_load_cert( 821 _PATH_HOST_DSA_KEY_FILE); 822 sensitive_data.keys[2] = key_load_cert( 823 _PATH_HOST_ECDSA_KEY_FILE); 824 sensitive_data.keys[3] = key_load_cert( 825 _PATH_HOST_RSA_KEY_FILE); 826 sensitive_data.keys[4] = key_load_public( 827 _PATH_HOST_DSA_KEY_FILE, NULL); 828 sensitive_data.keys[5] = key_load_public( 829 _PATH_HOST_ECDSA_KEY_FILE, NULL); 830 sensitive_data.keys[6] = key_load_public( 831 _PATH_HOST_RSA_KEY_FILE, NULL); 832 sensitive_data.external_keysign = 1; 833 } 834 } 835 /* 836 * Get rid of any extra privileges that we may have. We will no 837 * longer need them. Also, extra privileges could make it very hard 838 * to read identity files and other non-world-readable files from the 839 * user's home directory if it happens to be on a NFS volume where 840 * root is mapped to nobody. 841 */ 842 if (original_effective_uid == 0) { 843 PRIV_START; 844 permanently_set_uid(pw); 845 } 846 847 /* 848 * Now that we are back to our own permissions, create ~/.ssh 849 * directory if it doesn't already exist. 850 */ 851 if (config == NULL) { 852 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir, 853 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR); 854 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) 855 if (mkdir(buf, 0700) < 0) 856 error("Could not create directory '%.200s'.", 857 buf); 858 } 859 860 /* load options.identity_files */ 861 load_public_identity_files(); 862 863 /* Expand ~ in known host file names. */ 864 tilde_expand_paths(options.system_hostfiles, 865 options.num_system_hostfiles); 866 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles); 867 868 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */ 869 signal(SIGCHLD, main_sigchld_handler); 870 871 /* Log into the remote system. Never returns if the login fails. */ 872 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, 873 options.port, pw, timeout_ms); 874 875 if (packet_connection_is_on_socket()) { 876 verbose("Authenticated to %s ([%s]:%d).", host, 877 get_remote_ipaddr(), get_remote_port()); 878 } else { 879 verbose("Authenticated to %s (via proxy).", host); 880 } 881 882 /* We no longer need the private host keys. Clear them now. */ 883 if (sensitive_data.nkeys != 0) { 884 for (i = 0; i < sensitive_data.nkeys; i++) { 885 if (sensitive_data.keys[i] != NULL) { 886 /* Destroys contents safely */ 887 debug3("clear hostkey %d", i); 888 key_free(sensitive_data.keys[i]); 889 sensitive_data.keys[i] = NULL; 890 } 891 } 892 xfree(sensitive_data.keys); 893 } 894 for (i = 0; i < options.num_identity_files; i++) { 895 if (options.identity_files[i]) { 896 xfree(options.identity_files[i]); 897 options.identity_files[i] = NULL; 898 } 899 if (options.identity_keys[i]) { 900 key_free(options.identity_keys[i]); 901 options.identity_keys[i] = NULL; 902 } 903 } 904 905 exit_status = compat20 ? ssh_session2() : ssh_session(); 906 packet_close(); 907 908 if (options.control_path != NULL && muxserver_sock != -1) 909 unlink(options.control_path); 910 911 /* Kill ProxyCommand if it is running. */ 912 ssh_kill_proxy_command(); 913 914 return exit_status; 915 } 916 917 static void 918 control_persist_detach(void) 919 { 920 pid_t pid; 921 int devnull; 922 923 debug("%s: backgrounding master process", __func__); 924 925 /* 926 * master (current process) into the background, and make the 927 * foreground process a client of the backgrounded master. 928 */ 929 switch ((pid = fork())) { 930 case -1: 931 fatal("%s: fork: %s", __func__, strerror(errno)); 932 case 0: 933 /* Child: master process continues mainloop */ 934 break; 935 default: 936 /* Parent: set up mux slave to connect to backgrounded master */ 937 debug2("%s: background process is %ld", __func__, (long)pid); 938 stdin_null_flag = ostdin_null_flag; 939 options.request_tty = orequest_tty; 940 tty_flag = otty_flag; 941 close(muxserver_sock); 942 muxserver_sock = -1; 943 options.control_master = SSHCTL_MASTER_NO; 944 muxclient(options.control_path); 945 /* muxclient() doesn't return on success. */ 946 fatal("Failed to connect to new control master"); 947 } 948 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 949 error("%s: open(\"/dev/null\"): %s", __func__, 950 strerror(errno)); 951 } else { 952 if (dup2(devnull, STDIN_FILENO) == -1 || 953 dup2(devnull, STDOUT_FILENO) == -1) 954 error("%s: dup2: %s", __func__, strerror(errno)); 955 if (devnull > STDERR_FILENO) 956 close(devnull); 957 } 958 setproctitle("%s [mux]", options.control_path); 959 } 960 961 /* Do fork() after authentication. Used by "ssh -f" */ 962 static void 963 fork_postauth(void) 964 { 965 if (need_controlpersist_detach) 966 control_persist_detach(); 967 debug("forking to background"); 968 fork_after_authentication_flag = 0; 969 if (daemon(1, 1) < 0) 970 fatal("daemon() failed: %.200s", strerror(errno)); 971 } 972 973 /* Callback for remote forward global requests */ 974 static void 975 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt) 976 { 977 Forward *rfwd = (Forward *)ctxt; 978 979 /* XXX verbose() on failure? */ 980 debug("remote forward %s for: listen %d, connect %s:%d", 981 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure", 982 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port); 983 if (rfwd->listen_port == 0) { 984 if (type == SSH2_MSG_REQUEST_SUCCESS) { 985 rfwd->allocated_port = packet_get_int(); 986 logit("Allocated port %u for remote forward to %s:%d", 987 rfwd->allocated_port, 988 rfwd->connect_host, rfwd->connect_port); 989 channel_update_permitted_opens(rfwd->handle, 990 rfwd->allocated_port); 991 } else { 992 channel_update_permitted_opens(rfwd->handle, -1); 993 } 994 } 995 996 if (type == SSH2_MSG_REQUEST_FAILURE) { 997 if (options.exit_on_forward_failure) 998 fatal("Error: remote port forwarding failed for " 999 "listen port %d", rfwd->listen_port); 1000 else 1001 logit("Warning: remote port forwarding failed for " 1002 "listen port %d", rfwd->listen_port); 1003 } 1004 if (++remote_forward_confirms_received == options.num_remote_forwards) { 1005 debug("All remote forwarding requests processed"); 1006 if (fork_after_authentication_flag) 1007 fork_postauth(); 1008 } 1009 } 1010 1011 __dead static void 1012 client_cleanup_stdio_fwd(int id, void *arg) 1013 { 1014 debug("stdio forwarding: done"); 1015 cleanup_exit(0); 1016 } 1017 1018 static void 1019 ssh_init_stdio_forwarding(void) 1020 { 1021 Channel *c; 1022 int in, out; 1023 1024 if (stdio_forward_host == NULL) 1025 return; 1026 if (!compat20) 1027 fatal("stdio forwarding require Protocol 2"); 1028 1029 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port); 1030 1031 if ((in = dup(STDIN_FILENO)) < 0 || 1032 (out = dup(STDOUT_FILENO)) < 0) 1033 fatal("channel_connect_stdio_fwd: dup() in/out failed"); 1034 if ((c = channel_connect_stdio_fwd(stdio_forward_host, 1035 stdio_forward_port, in, out)) == NULL) 1036 fatal("%s: channel_connect_stdio_fwd failed", __func__); 1037 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0); 1038 } 1039 1040 static void 1041 ssh_init_forwarding(void) 1042 { 1043 int success = 0; 1044 int i; 1045 1046 /* Initiate local TCP/IP port forwardings. */ 1047 for (i = 0; i < options.num_local_forwards; i++) { 1048 debug("Local connections to %.200s:%d forwarded to remote " 1049 "address %.200s:%d", 1050 (options.local_forwards[i].listen_host == NULL) ? 1051 (options.gateway_ports ? "*" : "LOCALHOST") : 1052 options.local_forwards[i].listen_host, 1053 options.local_forwards[i].listen_port, 1054 options.local_forwards[i].connect_host, 1055 options.local_forwards[i].connect_port); 1056 success += channel_setup_local_fwd_listener( 1057 options.local_forwards[i].listen_host, 1058 options.local_forwards[i].listen_port, 1059 options.local_forwards[i].connect_host, 1060 options.local_forwards[i].connect_port, 1061 options.gateway_ports); 1062 } 1063 if (i > 0 && success != i && options.exit_on_forward_failure) 1064 fatal("Could not request local forwarding."); 1065 if (i > 0 && success == 0) 1066 error("Could not request local forwarding."); 1067 1068 /* Initiate remote TCP/IP port forwardings. */ 1069 for (i = 0; i < options.num_remote_forwards; i++) { 1070 debug("Remote connections from %.200s:%d forwarded to " 1071 "local address %.200s:%d", 1072 (options.remote_forwards[i].listen_host == NULL) ? 1073 "LOCALHOST" : options.remote_forwards[i].listen_host, 1074 options.remote_forwards[i].listen_port, 1075 options.remote_forwards[i].connect_host, 1076 options.remote_forwards[i].connect_port); 1077 options.remote_forwards[i].handle = 1078 channel_request_remote_forwarding( 1079 options.remote_forwards[i].listen_host, 1080 options.remote_forwards[i].listen_port, 1081 options.remote_forwards[i].connect_host, 1082 options.remote_forwards[i].connect_port); 1083 if (options.remote_forwards[i].handle < 0) { 1084 if (options.exit_on_forward_failure) 1085 fatal("Could not request remote forwarding."); 1086 else 1087 logit("Warning: Could not request remote " 1088 "forwarding."); 1089 } else { 1090 client_register_global_confirm(ssh_confirm_remote_forward, 1091 &options.remote_forwards[i]); 1092 } 1093 } 1094 1095 /* Initiate tunnel forwarding. */ 1096 if (options.tun_open != SSH_TUNMODE_NO) { 1097 if (client_request_tun_fwd(options.tun_open, 1098 options.tun_local, options.tun_remote) == -1) { 1099 if (options.exit_on_forward_failure) 1100 fatal("Could not request tunnel forwarding."); 1101 else 1102 error("Could not request tunnel forwarding."); 1103 } 1104 } 1105 } 1106 1107 static void 1108 check_agent_present(void) 1109 { 1110 if (options.forward_agent) { 1111 /* Clear agent forwarding if we don't have an agent. */ 1112 if (!ssh_agent_present()) 1113 options.forward_agent = 0; 1114 } 1115 } 1116 1117 static int 1118 ssh_session(void) 1119 { 1120 int type; 1121 int interactive = 0; 1122 int have_tty = 0; 1123 struct winsize ws; 1124 const char *display; 1125 1126 /* Enable compression if requested. */ 1127 if (options.compression) { 1128 debug("Requesting compression at level %d.", 1129 options.compression_level); 1130 1131 if (options.compression_level < 1 || 1132 options.compression_level > 9) 1133 fatal("Compression level must be from 1 (fast) to " 1134 "9 (slow, best)."); 1135 1136 /* Send the request. */ 1137 packet_start(SSH_CMSG_REQUEST_COMPRESSION); 1138 packet_put_int(options.compression_level); 1139 packet_send(); 1140 packet_write_wait(); 1141 type = packet_read(); 1142 if (type == SSH_SMSG_SUCCESS) 1143 packet_start_compression(options.compression_level); 1144 else if (type == SSH_SMSG_FAILURE) 1145 logit("Warning: Remote host refused compression."); 1146 else 1147 packet_disconnect("Protocol error waiting for " 1148 "compression response."); 1149 } 1150 /* Allocate a pseudo tty if appropriate. */ 1151 if (tty_flag) { 1152 const char *dp; 1153 debug("Requesting pty."); 1154 1155 /* Start the packet. */ 1156 packet_start(SSH_CMSG_REQUEST_PTY); 1157 1158 /* Store TERM in the packet. There is no limit on the 1159 length of the string. */ 1160 dp = getenv("TERM"); 1161 if (!dp) 1162 dp = ""; 1163 packet_put_cstring(dp); 1164 1165 /* Store window size in the packet. */ 1166 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) 1167 memset(&ws, 0, sizeof(ws)); 1168 packet_put_int((u_int)ws.ws_row); 1169 packet_put_int((u_int)ws.ws_col); 1170 packet_put_int((u_int)ws.ws_xpixel); 1171 packet_put_int((u_int)ws.ws_ypixel); 1172 1173 /* Store tty modes in the packet. */ 1174 tty_make_modes(fileno(stdin), NULL); 1175 1176 /* Send the packet, and wait for it to leave. */ 1177 packet_send(); 1178 packet_write_wait(); 1179 1180 /* Read response from the server. */ 1181 type = packet_read(); 1182 if (type == SSH_SMSG_SUCCESS) { 1183 interactive = 1; 1184 have_tty = 1; 1185 } else if (type == SSH_SMSG_FAILURE) 1186 logit("Warning: Remote host failed or refused to " 1187 "allocate a pseudo tty."); 1188 else 1189 packet_disconnect("Protocol error waiting for pty " 1190 "request response."); 1191 } 1192 /* Request X11 forwarding if enabled and DISPLAY is set. */ 1193 display = getenv("DISPLAY"); 1194 if (options.forward_x11 && display != NULL) { 1195 char *proto, *data; 1196 /* Get reasonable local authentication information. */ 1197 client_x11_get_proto(display, options.xauth_location, 1198 options.forward_x11_trusted, 1199 options.forward_x11_timeout, 1200 &proto, &data); 1201 /* Request forwarding with authentication spoofing. */ 1202 debug("Requesting X11 forwarding with authentication " 1203 "spoofing."); 1204 x11_request_forwarding_with_spoofing(0, display, proto, 1205 data, 0); 1206 /* Read response from the server. */ 1207 type = packet_read(); 1208 if (type == SSH_SMSG_SUCCESS) { 1209 interactive = 1; 1210 } else if (type == SSH_SMSG_FAILURE) { 1211 logit("Warning: Remote host denied X11 forwarding."); 1212 } else { 1213 packet_disconnect("Protocol error waiting for X11 " 1214 "forwarding"); 1215 } 1216 } 1217 /* Tell the packet module whether this is an interactive session. */ 1218 packet_set_interactive(interactive, 1219 options.ip_qos_interactive, options.ip_qos_bulk); 1220 1221 /* Request authentication agent forwarding if appropriate. */ 1222 check_agent_present(); 1223 1224 if (options.forward_agent) { 1225 debug("Requesting authentication agent forwarding."); 1226 auth_request_forwarding(); 1227 1228 /* Read response from the server. */ 1229 type = packet_read(); 1230 packet_check_eom(); 1231 if (type != SSH_SMSG_SUCCESS) 1232 logit("Warning: Remote host denied authentication agent forwarding."); 1233 } 1234 1235 /* Initiate port forwardings. */ 1236 ssh_init_stdio_forwarding(); 1237 ssh_init_forwarding(); 1238 1239 /* Execute a local command */ 1240 if (options.local_command != NULL && 1241 options.permit_local_command) 1242 ssh_local_cmd(options.local_command); 1243 1244 /* 1245 * If requested and we are not interested in replies to remote 1246 * forwarding requests, then let ssh continue in the background. 1247 */ 1248 if (fork_after_authentication_flag) { 1249 if (options.exit_on_forward_failure && 1250 options.num_remote_forwards > 0) { 1251 debug("deferring postauth fork until remote forward " 1252 "confirmation received"); 1253 } else 1254 fork_postauth(); 1255 } 1256 1257 /* 1258 * If a command was specified on the command line, execute the 1259 * command now. Otherwise request the server to start a shell. 1260 */ 1261 if (buffer_len(&command) > 0) { 1262 int len = buffer_len(&command); 1263 if (len > 900) 1264 len = 900; 1265 debug("Sending command: %.*s", len, 1266 (u_char *)buffer_ptr(&command)); 1267 packet_start(SSH_CMSG_EXEC_CMD); 1268 packet_put_string(buffer_ptr(&command), buffer_len(&command)); 1269 packet_send(); 1270 packet_write_wait(); 1271 } else { 1272 debug("Requesting shell."); 1273 packet_start(SSH_CMSG_EXEC_SHELL); 1274 packet_send(); 1275 packet_write_wait(); 1276 } 1277 1278 /* Enter the interactive session. */ 1279 return client_loop(have_tty, tty_flag ? 1280 options.escape_char : SSH_ESCAPECHAR_NONE, 0); 1281 } 1282 1283 /* request pty/x11/agent/tcpfwd/shell for channel */ 1284 static void 1285 ssh_session2_setup(int id, int success, void *arg) 1286 { 1287 extern char **environ; 1288 const char *display; 1289 int interactive = tty_flag; 1290 1291 if (!success) 1292 return; /* No need for error message, channels code sens one */ 1293 1294 display = getenv("DISPLAY"); 1295 if (options.forward_x11 && display != NULL) { 1296 char *proto, *data; 1297 /* Get reasonable local authentication information. */ 1298 client_x11_get_proto(display, options.xauth_location, 1299 options.forward_x11_trusted, 1300 options.forward_x11_timeout, &proto, &data); 1301 /* Request forwarding with authentication spoofing. */ 1302 debug("Requesting X11 forwarding with authentication " 1303 "spoofing."); 1304 x11_request_forwarding_with_spoofing(id, display, proto, 1305 data, 1); 1306 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN); 1307 /* XXX exit_on_forward_failure */ 1308 interactive = 1; 1309 } 1310 1311 check_agent_present(); 1312 if (options.forward_agent) { 1313 debug("Requesting authentication agent forwarding."); 1314 channel_request_start(id, "auth-agent-req@openssh.com", 0); 1315 packet_send(); 1316 } 1317 1318 /* Tell the packet module whether this is an interactive session. */ 1319 packet_set_interactive(interactive, 1320 options.ip_qos_interactive, options.ip_qos_bulk); 1321 1322 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"), 1323 NULL, fileno(stdin), &command, environ); 1324 } 1325 1326 /* open new channel for a session */ 1327 static int 1328 ssh_session2_open(void) 1329 { 1330 Channel *c; 1331 int window, packetmax, in, out, err; 1332 int sock; 1333 int socksize; 1334 socklen_t socksizelen = sizeof(int); 1335 1336 if (stdin_null_flag) { 1337 in = open(_PATH_DEVNULL, O_RDONLY); 1338 } else { 1339 in = dup(STDIN_FILENO); 1340 } 1341 out = dup(STDOUT_FILENO); 1342 err = dup(STDERR_FILENO); 1343 1344 if (in < 0 || out < 0 || err < 0) 1345 fatal("dup() in/out/err failed"); 1346 1347 /* enable nonblocking unless tty */ 1348 if (!isatty(in)) 1349 set_nonblock(in); 1350 if (!isatty(out)) 1351 set_nonblock(out); 1352 if (!isatty(err)) 1353 set_nonblock(err); 1354 1355 /* we need to check to see if what they want to do about buffer */ 1356 /* sizes here. In a hpn to nonhpn connection we want to limit */ 1357 /* the window size to something reasonable in case the far side */ 1358 /* has the large window bug. In hpn to hpn connection we want to */ 1359 /* use the max window size but allow the user to override it */ 1360 /* lastly if they disabled hpn then use the ssh std window size */ 1361 1362 /* so why don't we just do a getsockopt() here and set the */ 1363 /* ssh window to that? In the case of a autotuning receive */ 1364 /* window the window would get stuck at the initial buffer */ 1365 /* size generally less than 96k. Therefore we need to set the */ 1366 /* maximum ssh window size to the maximum hpn buffer size */ 1367 /* unless the user has specifically set the tcprcvbufpoll */ 1368 /* to no. In which case we *can* just set the window to the */ 1369 /* minimum of the hpn buffer size and tcp receive buffer size */ 1370 1371 if (tty_flag) 1372 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT; 1373 else 1374 options.hpn_buffer_size = 2*1024*1024; 1375 1376 if (datafellows & SSH_BUG_LARGEWINDOW) 1377 { 1378 debug("HPN to Non-HPN Connection"); 1379 } 1380 else 1381 { 1382 if (options.tcp_rcv_buf_poll <= 0) 1383 { 1384 sock = socket(AF_INET, SOCK_STREAM, 0); 1385 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, 1386 &socksize, &socksizelen); 1387 close(sock); 1388 debug("socksize %d", socksize); 1389 options.hpn_buffer_size = socksize; 1390 debug ("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size); 1391 } 1392 else 1393 { 1394 if (options.tcp_rcv_buf > 0) 1395 { 1396 /*create a socket but don't connect it */ 1397 /* we use that the get the rcv socket size */ 1398 sock = socket(AF_INET, SOCK_STREAM, 0); 1399 /* if they are using the tcp_rcv_buf option */ 1400 /* attempt to set the buffer size to that */ 1401 if (options.tcp_rcv_buf) 1402 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf, 1403 sizeof(options.tcp_rcv_buf)); 1404 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, 1405 &socksize, &socksizelen); 1406 close(sock); 1407 debug("socksize %d", socksize); 1408 options.hpn_buffer_size = socksize; 1409 debug ("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size); 1410 } 1411 } 1412 1413 } 1414 1415 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size); 1416 1417 window = options.hpn_buffer_size; 1418 1419 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size); 1420 1421 packetmax = CHAN_SES_PACKET_DEFAULT; 1422 if (tty_flag) { 1423 window = 4*CHAN_SES_PACKET_DEFAULT; 1424 window >>= 1; 1425 packetmax >>= 1; 1426 } 1427 c = channel_new( 1428 "session", SSH_CHANNEL_OPENING, in, out, err, 1429 window, packetmax, CHAN_EXTENDED_WRITE, 1430 "client-session", /*nonblock*/0); 1431 1432 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) { 1433 c->dynamic_window = 1; 1434 debug ("Enabled Dynamic Window Scaling\n"); 1435 } 1436 debug3("ssh_session2_open: channel_new: %d", c->self); 1437 1438 channel_send_open(c->self); 1439 if (!no_shell_flag) 1440 channel_register_open_confirm(c->self, 1441 ssh_session2_setup, NULL); 1442 1443 return c->self; 1444 } 1445 1446 static int 1447 ssh_session2(void) 1448 { 1449 int id = -1; 1450 1451 /* XXX should be pre-session */ 1452 if (!options.control_persist) 1453 ssh_init_stdio_forwarding(); 1454 ssh_init_forwarding(); 1455 1456 /* Start listening for multiplex clients */ 1457 muxserver_listen(); 1458 1459 /* 1460 * If we are in control persist mode and have a working mux listen 1461 * socket, then prepare to background ourselves and have a foreground 1462 * client attach as a control slave. 1463 * NB. we must save copies of the flags that we override for 1464 * the backgrounding, since we defer attachment of the slave until 1465 * after the connection is fully established (in particular, 1466 * async rfwd replies have been received for ExitOnForwardFailure). 1467 */ 1468 if (options.control_persist && muxserver_sock != -1) { 1469 ostdin_null_flag = stdin_null_flag; 1470 ono_shell_flag = no_shell_flag; 1471 orequest_tty = options.request_tty; 1472 otty_flag = tty_flag; 1473 stdin_null_flag = 1; 1474 no_shell_flag = 1; 1475 tty_flag = 0; 1476 if (!fork_after_authentication_flag) 1477 need_controlpersist_detach = 1; 1478 fork_after_authentication_flag = 1; 1479 } 1480 /* 1481 * ControlPersist mux listen socket setup failed, attempt the 1482 * stdio forward setup that we skipped earlier. 1483 */ 1484 if (options.control_persist && muxserver_sock == -1) 1485 ssh_init_stdio_forwarding(); 1486 1487 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN)) 1488 id = ssh_session2_open(); 1489 1490 /* If we don't expect to open a new session, then disallow it */ 1491 if (options.control_master == SSHCTL_MASTER_NO && 1492 (datafellows & SSH_NEW_OPENSSH)) { 1493 debug("Requesting no-more-sessions@openssh.com"); 1494 packet_start(SSH2_MSG_GLOBAL_REQUEST); 1495 packet_put_cstring("no-more-sessions@openssh.com"); 1496 packet_put_char(0); 1497 packet_send(); 1498 } 1499 1500 /* Execute a local command */ 1501 if (options.local_command != NULL && 1502 options.permit_local_command) 1503 ssh_local_cmd(options.local_command); 1504 1505 /* 1506 * If requested and we are not interested in replies to remote 1507 * forwarding requests, then let ssh continue in the background. 1508 */ 1509 if (fork_after_authentication_flag) { 1510 if (options.exit_on_forward_failure && 1511 options.num_remote_forwards > 0) { 1512 debug("deferring postauth fork until remote forward " 1513 "confirmation received"); 1514 } else 1515 fork_postauth(); 1516 } 1517 1518 if (options.use_roaming) 1519 request_roaming(); 1520 1521 return client_loop(tty_flag, tty_flag ? 1522 options.escape_char : SSH_ESCAPECHAR_NONE, id); 1523 } 1524 1525 static void 1526 load_public_identity_files(void) 1527 { 1528 char *filename, *cp, thishost[NI_MAXHOST]; 1529 char *pwdir = NULL, *pwname = NULL; 1530 int i = 0; 1531 Key *public; 1532 struct passwd *pw; 1533 u_int n_ids; 1534 char *identity_files[SSH_MAX_IDENTITY_FILES]; 1535 Key *identity_keys[SSH_MAX_IDENTITY_FILES]; 1536 #ifdef ENABLE_PKCS11 1537 Key **keys; 1538 int nkeys; 1539 #endif /* PKCS11 */ 1540 1541 n_ids = 0; 1542 bzero(identity_files, sizeof(identity_files)); 1543 bzero(identity_keys, sizeof(identity_keys)); 1544 1545 #ifdef ENABLE_PKCS11 1546 if (options.pkcs11_provider != NULL && 1547 options.num_identity_files < SSH_MAX_IDENTITY_FILES && 1548 (pkcs11_init(!options.batch_mode) == 0) && 1549 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL, 1550 &keys)) > 0) { 1551 for (i = 0; i < nkeys; i++) { 1552 if (n_ids >= SSH_MAX_IDENTITY_FILES) { 1553 key_free(keys[i]); 1554 continue; 1555 } 1556 identity_keys[n_ids] = keys[i]; 1557 identity_files[n_ids] = 1558 xstrdup(options.pkcs11_provider); /* XXX */ 1559 n_ids++; 1560 } 1561 xfree(keys); 1562 } 1563 #endif /* ENABLE_PKCS11 */ 1564 if ((pw = getpwuid(original_real_uid)) == NULL) 1565 fatal("load_public_identity_files: getpwuid failed"); 1566 pwname = xstrdup(pw->pw_name); 1567 pwdir = xstrdup(pw->pw_dir); 1568 if (gethostname(thishost, sizeof(thishost)) == -1) 1569 fatal("load_public_identity_files: gethostname: %s", 1570 strerror(errno)); 1571 for (i = 0; i < options.num_identity_files; i++) { 1572 if (n_ids >= SSH_MAX_IDENTITY_FILES) { 1573 xfree(options.identity_files[i]); 1574 continue; 1575 } 1576 cp = tilde_expand_filename(options.identity_files[i], 1577 original_real_uid); 1578 filename = percent_expand(cp, "d", pwdir, 1579 "u", pwname, "l", thishost, "h", host, 1580 "r", options.user, (char *)NULL); 1581 xfree(cp); 1582 public = key_load_public(filename, NULL); 1583 debug("identity file %s type %d", filename, 1584 public ? public->type : -1); 1585 xfree(options.identity_files[i]); 1586 identity_files[n_ids] = filename; 1587 identity_keys[n_ids] = public; 1588 1589 if (++n_ids >= SSH_MAX_IDENTITY_FILES) 1590 continue; 1591 1592 /* Try to add the certificate variant too */ 1593 xasprintf(&cp, "%s-cert", filename); 1594 public = key_load_public(cp, NULL); 1595 debug("identity file %s type %d", cp, 1596 public ? public->type : -1); 1597 if (public == NULL) { 1598 xfree(cp); 1599 continue; 1600 } 1601 if (!key_is_cert(public)) { 1602 debug("%s: key %s type %s is not a certificate", 1603 __func__, cp, key_type(public)); 1604 key_free(public); 1605 xfree(cp); 1606 continue; 1607 } 1608 identity_keys[n_ids] = public; 1609 /* point to the original path, most likely the private key */ 1610 identity_files[n_ids] = xstrdup(filename); 1611 n_ids++; 1612 } 1613 options.num_identity_files = n_ids; 1614 memcpy(options.identity_files, identity_files, sizeof(identity_files)); 1615 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys)); 1616 1617 bzero(pwname, strlen(pwname)); 1618 xfree(pwname); 1619 bzero(pwdir, strlen(pwdir)); 1620 xfree(pwdir); 1621 } 1622 1623 static void 1624 main_sigchld_handler(int sig) 1625 { 1626 int save_errno = errno; 1627 pid_t pid; 1628 int status; 1629 1630 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 1631 (pid < 0 && errno == EINTR)) 1632 ; 1633 1634 signal(sig, main_sigchld_handler); 1635 errno = save_errno; 1636 } 1637 1638