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