1 /* $NetBSD: ssh.c,v 1.14 2014/02/20 08:20:05 gson Exp $ */ 2 /* $OpenBSD: ssh.c,v 1.381 2013/07/25 00:29:10 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.14 2014/02/20 08:20:05 gson 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 log_file] [-e escape_char]\n" 191 " [-F configfile] [-I pkcs11] [-i identity_file]\n" 192 " [-L [bind_address:]port:host:hostport] [-Q protocol_feature]\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 free(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, *logfile; 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("No user exists for uid %lu", (u_long)original_real_uid); 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 logfile = NULL; 300 argv0 = av[0]; 301 302 again: 303 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx" 304 "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) { 305 switch (opt) { 306 case '1': 307 options.protocol = SSH_PROTO_1; 308 break; 309 case '2': 310 options.protocol = SSH_PROTO_2; 311 break; 312 case '4': 313 options.address_family = AF_INET; 314 break; 315 case '6': 316 options.address_family = AF_INET6; 317 break; 318 case 'n': 319 stdin_null_flag = 1; 320 break; 321 case 'f': 322 fork_after_authentication_flag = 1; 323 stdin_null_flag = 1; 324 break; 325 case 'x': 326 options.forward_x11 = 0; 327 break; 328 case 'X': 329 options.forward_x11 = 1; 330 break; 331 case 'y': 332 use_syslog = 1; 333 break; 334 case 'E': 335 logfile = xstrdup(optarg); 336 break; 337 case 'Y': 338 options.forward_x11 = 1; 339 options.forward_x11_trusted = 1; 340 break; 341 case 'g': 342 options.gateway_ports = 1; 343 break; 344 case 'O': 345 if (stdio_forward_host != NULL) 346 fatal("Cannot specify multiplexing " 347 "command with -W"); 348 else if (muxclient_command != 0) 349 fatal("Multiplexing command already specified"); 350 if (strcmp(optarg, "check") == 0) 351 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK; 352 else if (strcmp(optarg, "forward") == 0) 353 muxclient_command = SSHMUX_COMMAND_FORWARD; 354 else if (strcmp(optarg, "exit") == 0) 355 muxclient_command = SSHMUX_COMMAND_TERMINATE; 356 else if (strcmp(optarg, "stop") == 0) 357 muxclient_command = SSHMUX_COMMAND_STOP; 358 else if (strcmp(optarg, "cancel") == 0) 359 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD; 360 else 361 fatal("Invalid multiplex command."); 362 break; 363 case 'P': /* deprecated */ 364 options.use_privileged_port = 0; 365 break; 366 case 'Q': /* deprecated */ 367 cp = NULL; 368 if (strcasecmp(optarg, "cipher") == 0) 369 cp = cipher_alg_list(); 370 else if (strcasecmp(optarg, "mac") == 0) 371 cp = mac_alg_list(); 372 else if (strcasecmp(optarg, "kex") == 0) 373 cp = kex_alg_list(); 374 else if (strcasecmp(optarg, "key") == 0) 375 cp = key_alg_list(); 376 if (cp == NULL) 377 fatal("Unsupported query \"%s\"", optarg); 378 printf("%s\n", cp); 379 free(cp); 380 exit(0); 381 break; 382 case 'a': 383 options.forward_agent = 0; 384 break; 385 case 'A': 386 options.forward_agent = 1; 387 break; 388 case 'k': 389 options.gss_deleg_creds = 0; 390 break; 391 case 'K': 392 options.gss_authentication = 1; 393 options.gss_deleg_creds = 1; 394 break; 395 case 'i': 396 if (stat(optarg, &st) < 0) { 397 fprintf(stderr, "Warning: Identity file %s " 398 "not accessible: %s.\n", optarg, 399 strerror(errno)); 400 break; 401 } 402 add_identity_file(&options, NULL, optarg, 1); 403 break; 404 case 'I': 405 #ifdef ENABLE_PKCS11 406 options.pkcs11_provider = xstrdup(optarg); 407 #else 408 fprintf(stderr, "no support for PKCS#11.\n"); 409 #endif 410 break; 411 case 't': 412 if (options.request_tty == REQUEST_TTY_YES) 413 options.request_tty = REQUEST_TTY_FORCE; 414 else 415 options.request_tty = REQUEST_TTY_YES; 416 break; 417 case 'v': 418 if (debug_flag == 0) { 419 debug_flag = 1; 420 options.log_level = SYSLOG_LEVEL_DEBUG1; 421 } else { 422 if (options.log_level < SYSLOG_LEVEL_DEBUG3) 423 options.log_level++; 424 } 425 break; 426 case 'V': 427 fprintf(stderr, "%s, %s\n", 428 SSH_VERSION, SSLeay_version(SSLEAY_VERSION)); 429 if (opt == 'V') 430 exit(0); 431 break; 432 case 'w': 433 if (options.tun_open == -1) 434 options.tun_open = SSH_TUNMODE_DEFAULT; 435 options.tun_local = a2tun(optarg, &options.tun_remote); 436 if (options.tun_local == SSH_TUNID_ERR) { 437 fprintf(stderr, 438 "Bad tun device '%s'\n", optarg); 439 exit(255); 440 } 441 break; 442 case 'W': 443 if (stdio_forward_host != NULL) 444 fatal("stdio forward already specified"); 445 if (muxclient_command != 0) 446 fatal("Cannot specify stdio forward with -O"); 447 if (parse_forward(&fwd, optarg, 1, 0)) { 448 stdio_forward_host = fwd.listen_host; 449 stdio_forward_port = fwd.listen_port; 450 free(fwd.connect_host); 451 } else { 452 fprintf(stderr, 453 "Bad stdio forwarding specification '%s'\n", 454 optarg); 455 exit(255); 456 } 457 options.request_tty = REQUEST_TTY_NO; 458 no_shell_flag = 1; 459 options.clear_forwardings = 1; 460 options.exit_on_forward_failure = 1; 461 break; 462 case 'q': 463 options.log_level = SYSLOG_LEVEL_QUIET; 464 break; 465 case 'e': 466 if (optarg[0] == '^' && optarg[2] == 0 && 467 (u_char) optarg[1] >= 64 && 468 (u_char) optarg[1] < 128) 469 options.escape_char = (u_char) optarg[1] & 31; 470 else if (strlen(optarg) == 1) 471 options.escape_char = (u_char) optarg[0]; 472 else if (strcmp(optarg, "none") == 0) 473 options.escape_char = SSH_ESCAPECHAR_NONE; 474 else { 475 fprintf(stderr, "Bad escape character '%s'.\n", 476 optarg); 477 exit(255); 478 } 479 break; 480 case 'c': 481 if (ciphers_valid(optarg)) { 482 /* SSH2 only */ 483 options.ciphers = xstrdup(optarg); 484 options.cipher = SSH_CIPHER_INVALID; 485 } else { 486 /* SSH1 only */ 487 options.cipher = cipher_number(optarg); 488 if (options.cipher == -1) { 489 fprintf(stderr, 490 "Unknown cipher type '%s'\n", 491 optarg); 492 exit(255); 493 } 494 if (options.cipher == SSH_CIPHER_3DES) 495 options.ciphers = __UNCONST("3des-cbc"); 496 else if (options.cipher == SSH_CIPHER_BLOWFISH) 497 options.ciphers = 498 __UNCONST("blowfish-cbc"); 499 else 500 options.ciphers = (char *)-1; 501 } 502 break; 503 case 'm': 504 if (mac_valid(optarg)) 505 options.macs = xstrdup(optarg); 506 else { 507 fprintf(stderr, "Unknown mac type '%s'\n", 508 optarg); 509 exit(255); 510 } 511 break; 512 case 'M': 513 if (options.control_master == SSHCTL_MASTER_YES) 514 options.control_master = SSHCTL_MASTER_ASK; 515 else 516 options.control_master = SSHCTL_MASTER_YES; 517 break; 518 case 'p': 519 options.port = a2port(optarg); 520 if (options.port <= 0) { 521 fprintf(stderr, "Bad port '%s'\n", optarg); 522 exit(255); 523 } 524 break; 525 case 'l': 526 options.user = optarg; 527 break; 528 529 case 'L': 530 if (parse_forward(&fwd, optarg, 0, 0)) 531 add_local_forward(&options, &fwd); 532 else { 533 fprintf(stderr, 534 "Bad local forwarding specification '%s'\n", 535 optarg); 536 exit(255); 537 } 538 break; 539 540 case 'R': 541 if (parse_forward(&fwd, optarg, 0, 1)) { 542 add_remote_forward(&options, &fwd); 543 } else { 544 fprintf(stderr, 545 "Bad remote forwarding specification " 546 "'%s'\n", optarg); 547 exit(255); 548 } 549 break; 550 551 case 'D': 552 if (parse_forward(&fwd, optarg, 1, 0)) { 553 add_local_forward(&options, &fwd); 554 } else { 555 fprintf(stderr, 556 "Bad dynamic forwarding specification " 557 "'%s'\n", optarg); 558 exit(255); 559 } 560 break; 561 562 case 'C': 563 options.compression = 1; 564 break; 565 case 'N': 566 no_shell_flag = 1; 567 options.request_tty = REQUEST_TTY_NO; 568 break; 569 case 'T': 570 options.request_tty = REQUEST_TTY_NO; 571 /* ensure that the user doesn't try to backdoor a */ 572 /* null cipher switch on an interactive session */ 573 /* so explicitly disable it no matter what */ 574 options.none_switch = 0; 575 break; 576 case 'o': 577 dummy = 1; 578 line = xstrdup(optarg); 579 if (process_config_line(&options, host ? host : "", 580 line, "command-line", 0, &dummy, SSHCONF_USERCONF) 581 != 0) 582 exit(255); 583 free(line); 584 break; 585 case 's': 586 subsystem_flag = 1; 587 break; 588 case 'S': 589 if (options.control_path != NULL) 590 free(options.control_path); 591 options.control_path = xstrdup(optarg); 592 break; 593 case 'b': 594 options.bind_address = optarg; 595 break; 596 case 'F': 597 config = optarg; 598 break; 599 default: 600 usage(); 601 } 602 } 603 604 ac -= optind; 605 av += optind; 606 607 if (ac > 0 && !host) { 608 if (strrchr(*av, '@')) { 609 p = xstrdup(*av); 610 cp = strrchr(p, '@'); 611 if (cp == NULL || cp == p) 612 usage(); 613 options.user = p; 614 *cp = '\0'; 615 host = ++cp; 616 } else 617 host = *av; 618 if (ac > 1) { 619 optind = optreset = 1; 620 goto again; 621 } 622 ac--, av++; 623 } 624 625 /* Check that we got a host name. */ 626 if (!host) 627 usage(); 628 629 OpenSSL_add_all_algorithms(); 630 ERR_load_crypto_strings(); 631 632 /* Initialize the command to execute on remote host. */ 633 buffer_init(&command); 634 635 /* 636 * Save the command to execute on the remote host in a buffer. There 637 * is no limit on the length of the command, except by the maximum 638 * packet size. Also sets the tty flag if there is no command. 639 */ 640 if (!ac) { 641 /* No command specified - execute shell on a tty. */ 642 if (subsystem_flag) { 643 fprintf(stderr, 644 "You must specify a subsystem to invoke.\n"); 645 usage(); 646 } 647 } else { 648 /* A command has been specified. Store it into the buffer. */ 649 for (i = 0; i < ac; i++) { 650 if (i) 651 buffer_append(&command, " ", 1); 652 buffer_append(&command, av[i], strlen(av[i])); 653 } 654 } 655 656 /* Cannot fork to background if no command. */ 657 if (fork_after_authentication_flag && buffer_len(&command) == 0 && 658 !no_shell_flag) 659 fatal("Cannot fork into background without a command " 660 "to execute."); 661 662 /* 663 * Initialize "log" output. Since we are the client all output 664 * goes to stderr unless otherwise specified by -y or -E. 665 */ 666 if (use_syslog && logfile != NULL) 667 fatal("Can't specify both -y and -E"); 668 if (logfile != NULL) { 669 log_redirect_stderr_to(logfile); 670 free(logfile); 671 } 672 log_init(argv0, 673 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level, 674 SYSLOG_FACILITY_USER, !use_syslog); 675 676 if (debug_flag) 677 logit("%s, %s", SSH_VERSION, SSLeay_version(SSLEAY_VERSION)); 678 679 /* 680 * Read per-user configuration file. Ignore the system wide config 681 * file if the user specifies a config file on the command line. 682 */ 683 if (config != NULL) { 684 if (strcasecmp(config, "none") != 0 && 685 !read_config_file(config, host, &options, SSHCONF_USERCONF)) 686 fatal("Can't open user config file %.100s: " 687 "%.100s", config, strerror(errno)); 688 } else { 689 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir, 690 _PATH_SSH_USER_CONFFILE); 691 if (r > 0 && (size_t)r < sizeof(buf)) 692 (void)read_config_file(buf, host, &options, 693 SSHCONF_CHECKPERM|SSHCONF_USERCONF); 694 695 /* Read systemwide configuration file after user config. */ 696 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host, 697 &options, 0); 698 } 699 700 /* Fill configuration defaults. */ 701 fill_default_options(&options); 702 703 channel_set_af(options.address_family); 704 705 /* reinit */ 706 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog); 707 708 if (options.request_tty == REQUEST_TTY_YES || 709 options.request_tty == REQUEST_TTY_FORCE) 710 tty_flag = 1; 711 712 /* Allocate a tty by default if no command specified. */ 713 if (buffer_len(&command) == 0) 714 tty_flag = options.request_tty != REQUEST_TTY_NO; 715 716 /* Force no tty */ 717 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0) 718 tty_flag = 0; 719 /* Do not allocate a tty if stdin is not a tty. */ 720 if ((!isatty(fileno(stdin)) || stdin_null_flag) && 721 options.request_tty != REQUEST_TTY_FORCE) { 722 if (tty_flag) 723 logit("Pseudo-terminal will not be allocated because " 724 "stdin is not a terminal."); 725 tty_flag = 0; 726 } 727 728 if (options.user == NULL) 729 options.user = xstrdup(pw->pw_name); 730 731 /* Get default port if port has not been set. */ 732 if (options.port == 0) { 733 sp = getservbyname(SSH_SERVICE_NAME, "tcp"); 734 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT; 735 } 736 737 /* preserve host name given on command line for %n expansion */ 738 host_arg = host; 739 if (options.hostname != NULL) { 740 host = percent_expand(options.hostname, 741 "h", host, (char *)NULL); 742 } 743 744 if (gethostname(thishost, sizeof(thishost)) == -1) 745 fatal("gethostname: %s", strerror(errno)); 746 strlcpy(shorthost, thishost, sizeof(shorthost)); 747 shorthost[strcspn(thishost, ".")] = '\0'; 748 snprintf(portstr, sizeof(portstr), "%d", options.port); 749 750 if (options.local_command != NULL) { 751 debug3("expanding LocalCommand: %s", options.local_command); 752 cp = options.local_command; 753 options.local_command = percent_expand(cp, "d", pw->pw_dir, 754 "h", host, "l", thishost, "n", host_arg, "r", options.user, 755 "p", portstr, "u", pw->pw_name, "L", shorthost, 756 (char *)NULL); 757 debug3("expanded LocalCommand: %s", options.local_command); 758 free(cp); 759 } 760 761 /* force lowercase for hostkey matching */ 762 if (options.host_key_alias != NULL) { 763 for (p = options.host_key_alias; *p; p++) 764 if (isupper((unsigned char)*p)) 765 *p = (char)tolower((unsigned char)*p); 766 } 767 768 if (options.proxy_command != NULL && 769 strcmp(options.proxy_command, "none") == 0) { 770 free(options.proxy_command); 771 options.proxy_command = NULL; 772 } 773 if (options.control_path != NULL && 774 strcmp(options.control_path, "none") == 0) { 775 free(options.control_path); 776 options.control_path = NULL; 777 } 778 779 if (options.control_path != NULL) { 780 cp = tilde_expand_filename(options.control_path, 781 original_real_uid); 782 free(options.control_path); 783 options.control_path = percent_expand(cp, "h", host, 784 "l", thishost, "n", host_arg, "r", options.user, 785 "p", portstr, "u", pw->pw_name, "L", shorthost, 786 (char *)NULL); 787 free(cp); 788 } 789 if (muxclient_command != 0 && options.control_path == NULL) 790 fatal("No ControlPath specified for \"-O\" command"); 791 if (options.control_path != NULL) 792 muxclient(options.control_path); 793 794 timeout_ms = options.connection_timeout * 1000; 795 796 /* Open a connection to the remote host. */ 797 if (ssh_connect(host, &hostaddr, options.port, 798 options.address_family, options.connection_attempts, &timeout_ms, 799 options.tcp_keep_alive, 800 original_effective_uid == 0 && options.use_privileged_port, 801 options.proxy_command) != 0) 802 exit(255); 803 804 if (timeout_ms > 0) 805 debug3("timeout: %d ms remain after connect", timeout_ms); 806 807 /* 808 * If we successfully made the connection, load the host private key 809 * in case we will need it later for combined rsa-rhosts 810 * authentication. This must be done before releasing extra 811 * privileges, because the file is only readable by root. 812 * If we cannot access the private keys, load the public keys 813 * instead and try to execute the ssh-keysign helper instead. 814 */ 815 sensitive_data.nkeys = 0; 816 sensitive_data.keys = NULL; 817 sensitive_data.external_keysign = 0; 818 if (options.rhosts_rsa_authentication || 819 options.hostbased_authentication) { 820 sensitive_data.nkeys = 7; 821 sensitive_data.keys = xcalloc(sensitive_data.nkeys, 822 sizeof(Key)); 823 824 PRIV_START; 825 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1, 826 _PATH_HOST_KEY_FILE, "", NULL, NULL); 827 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA, 828 _PATH_HOST_DSA_KEY_FILE, "", NULL); 829 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA, 830 _PATH_HOST_ECDSA_KEY_FILE, "", NULL); 831 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA, 832 _PATH_HOST_RSA_KEY_FILE, "", NULL); 833 sensitive_data.keys[4] = key_load_private_type(KEY_DSA, 834 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL); 835 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA, 836 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL); 837 sensitive_data.keys[6] = key_load_private_type(KEY_RSA, 838 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL); 839 PRIV_END; 840 841 if (options.hostbased_authentication == 1 && 842 sensitive_data.keys[0] == NULL && 843 sensitive_data.keys[4] == NULL && 844 sensitive_data.keys[5] == NULL && 845 sensitive_data.keys[6] == NULL) { 846 sensitive_data.keys[1] = key_load_cert( 847 _PATH_HOST_DSA_KEY_FILE); 848 sensitive_data.keys[2] = key_load_cert( 849 _PATH_HOST_ECDSA_KEY_FILE); 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 sensitive_data.keys[5] = key_load_public( 855 _PATH_HOST_ECDSA_KEY_FILE, NULL); 856 sensitive_data.keys[6] = key_load_public( 857 _PATH_HOST_RSA_KEY_FILE, NULL); 858 sensitive_data.external_keysign = 1; 859 } 860 } 861 /* 862 * Get rid of any extra privileges that we may have. We will no 863 * longer need them. Also, extra privileges could make it very hard 864 * to read identity files and other non-world-readable files from the 865 * user's home directory if it happens to be on a NFS volume where 866 * root is mapped to nobody. 867 */ 868 if (original_effective_uid == 0) { 869 PRIV_START; 870 permanently_set_uid(pw); 871 } 872 873 /* 874 * Now that we are back to our own permissions, create ~/.ssh 875 * directory if it doesn't already exist. 876 */ 877 if (config == NULL) { 878 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir, 879 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR); 880 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) 881 if (mkdir(buf, 0700) < 0) 882 error("Could not create directory '%.200s'.", 883 buf); 884 } 885 886 /* load options.identity_files */ 887 load_public_identity_files(); 888 889 /* Expand ~ in known host file names. */ 890 tilde_expand_paths(options.system_hostfiles, 891 options.num_system_hostfiles); 892 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles); 893 894 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */ 895 signal(SIGCHLD, main_sigchld_handler); 896 897 /* Log into the remote system. Never returns if the login fails. */ 898 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, 899 options.port, pw, timeout_ms); 900 901 if (packet_connection_is_on_socket()) { 902 verbose("Authenticated to %s ([%s]:%d).", host, 903 get_remote_ipaddr(), get_remote_port()); 904 } else { 905 verbose("Authenticated to %s (via proxy).", host); 906 } 907 908 /* We no longer need the private host keys. Clear them now. */ 909 if (sensitive_data.nkeys != 0) { 910 for (i = 0; i < sensitive_data.nkeys; i++) { 911 if (sensitive_data.keys[i] != NULL) { 912 /* Destroys contents safely */ 913 debug3("clear hostkey %d", i); 914 key_free(sensitive_data.keys[i]); 915 sensitive_data.keys[i] = NULL; 916 } 917 } 918 free(sensitive_data.keys); 919 } 920 for (i = 0; i < options.num_identity_files; i++) { 921 free(options.identity_files[i]); 922 options.identity_files[i] = NULL; 923 if (options.identity_keys[i]) { 924 key_free(options.identity_keys[i]); 925 options.identity_keys[i] = NULL; 926 } 927 } 928 929 exit_status = compat20 ? ssh_session2() : ssh_session(); 930 packet_close(); 931 932 if (options.control_path != NULL && muxserver_sock != -1) 933 unlink(options.control_path); 934 935 /* Kill ProxyCommand if it is running. */ 936 ssh_kill_proxy_command(); 937 938 return exit_status; 939 } 940 941 static void 942 control_persist_detach(void) 943 { 944 pid_t pid; 945 int devnull; 946 947 debug("%s: backgrounding master process", __func__); 948 949 /* 950 * master (current process) into the background, and make the 951 * foreground process a client of the backgrounded master. 952 */ 953 switch ((pid = fork())) { 954 case -1: 955 fatal("%s: fork: %s", __func__, strerror(errno)); 956 case 0: 957 /* Child: master process continues mainloop */ 958 break; 959 default: 960 /* Parent: set up mux slave to connect to backgrounded master */ 961 debug2("%s: background process is %ld", __func__, (long)pid); 962 stdin_null_flag = ostdin_null_flag; 963 options.request_tty = orequest_tty; 964 tty_flag = otty_flag; 965 close(muxserver_sock); 966 muxserver_sock = -1; 967 options.control_master = SSHCTL_MASTER_NO; 968 muxclient(options.control_path); 969 /* muxclient() doesn't return on success. */ 970 fatal("Failed to connect to new control master"); 971 } 972 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 973 error("%s: open(\"/dev/null\"): %s", __func__, 974 strerror(errno)); 975 } else { 976 if (dup2(devnull, STDIN_FILENO) == -1 || 977 dup2(devnull, STDOUT_FILENO) == -1) 978 error("%s: dup2: %s", __func__, strerror(errno)); 979 if (devnull > STDERR_FILENO) 980 close(devnull); 981 } 982 daemon(1, 1); 983 setproctitle("%s [mux]", options.control_path); 984 } 985 986 /* Do fork() after authentication. Used by "ssh -f" */ 987 static void 988 fork_postauth(void) 989 { 990 if (need_controlpersist_detach) 991 control_persist_detach(); 992 debug("forking to background"); 993 fork_after_authentication_flag = 0; 994 if (daemon(1, 1) < 0) 995 fatal("daemon() failed: %.200s", strerror(errno)); 996 } 997 998 /* Callback for remote forward global requests */ 999 static void 1000 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt) 1001 { 1002 Forward *rfwd = (Forward *)ctxt; 1003 1004 /* XXX verbose() on failure? */ 1005 debug("remote forward %s for: listen %d, connect %s:%d", 1006 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure", 1007 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port); 1008 if (rfwd->listen_port == 0) { 1009 if (type == SSH2_MSG_REQUEST_SUCCESS) { 1010 rfwd->allocated_port = packet_get_int(); 1011 logit("Allocated port %u for remote forward to %s:%d", 1012 rfwd->allocated_port, 1013 rfwd->connect_host, rfwd->connect_port); 1014 channel_update_permitted_opens(rfwd->handle, 1015 rfwd->allocated_port); 1016 } else { 1017 channel_update_permitted_opens(rfwd->handle, -1); 1018 } 1019 } 1020 1021 if (type == SSH2_MSG_REQUEST_FAILURE) { 1022 if (options.exit_on_forward_failure) 1023 fatal("Error: remote port forwarding failed for " 1024 "listen port %d", rfwd->listen_port); 1025 else 1026 logit("Warning: remote port forwarding failed for " 1027 "listen port %d", rfwd->listen_port); 1028 } 1029 if (++remote_forward_confirms_received == options.num_remote_forwards) { 1030 debug("All remote forwarding requests processed"); 1031 if (fork_after_authentication_flag) 1032 fork_postauth(); 1033 } 1034 } 1035 1036 __dead static void 1037 client_cleanup_stdio_fwd(int id, void *arg) 1038 { 1039 debug("stdio forwarding: done"); 1040 cleanup_exit(0); 1041 } 1042 1043 static void 1044 ssh_init_stdio_forwarding(void) 1045 { 1046 Channel *c; 1047 int in, out; 1048 1049 if (stdio_forward_host == NULL) 1050 return; 1051 if (!compat20) 1052 fatal("stdio forwarding require Protocol 2"); 1053 1054 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port); 1055 1056 if ((in = dup(STDIN_FILENO)) < 0 || 1057 (out = dup(STDOUT_FILENO)) < 0) 1058 fatal("channel_connect_stdio_fwd: dup() in/out failed"); 1059 if ((c = channel_connect_stdio_fwd(stdio_forward_host, 1060 stdio_forward_port, in, out)) == NULL) 1061 fatal("%s: channel_connect_stdio_fwd failed", __func__); 1062 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0); 1063 } 1064 1065 static void 1066 ssh_init_forwarding(void) 1067 { 1068 int success = 0; 1069 int i; 1070 1071 /* Initiate local TCP/IP port forwardings. */ 1072 for (i = 0; i < options.num_local_forwards; i++) { 1073 debug("Local connections to %.200s:%d forwarded to remote " 1074 "address %.200s:%d", 1075 (options.local_forwards[i].listen_host == NULL) ? 1076 (options.gateway_ports ? "*" : "LOCALHOST") : 1077 options.local_forwards[i].listen_host, 1078 options.local_forwards[i].listen_port, 1079 options.local_forwards[i].connect_host, 1080 options.local_forwards[i].connect_port); 1081 success += channel_setup_local_fwd_listener( 1082 options.local_forwards[i].listen_host, 1083 options.local_forwards[i].listen_port, 1084 options.local_forwards[i].connect_host, 1085 options.local_forwards[i].connect_port, 1086 options.gateway_ports); 1087 } 1088 if (i > 0 && success != i && options.exit_on_forward_failure) 1089 fatal("Could not request local forwarding."); 1090 if (i > 0 && success == 0) 1091 error("Could not request local forwarding."); 1092 1093 /* Initiate remote TCP/IP port forwardings. */ 1094 for (i = 0; i < options.num_remote_forwards; i++) { 1095 debug("Remote connections from %.200s:%d forwarded to " 1096 "local address %.200s:%d", 1097 (options.remote_forwards[i].listen_host == NULL) ? 1098 "LOCALHOST" : options.remote_forwards[i].listen_host, 1099 options.remote_forwards[i].listen_port, 1100 options.remote_forwards[i].connect_host, 1101 options.remote_forwards[i].connect_port); 1102 options.remote_forwards[i].handle = 1103 channel_request_remote_forwarding( 1104 options.remote_forwards[i].listen_host, 1105 options.remote_forwards[i].listen_port, 1106 options.remote_forwards[i].connect_host, 1107 options.remote_forwards[i].connect_port); 1108 if (options.remote_forwards[i].handle < 0) { 1109 if (options.exit_on_forward_failure) 1110 fatal("Could not request remote forwarding."); 1111 else 1112 logit("Warning: Could not request remote " 1113 "forwarding."); 1114 } else { 1115 client_register_global_confirm(ssh_confirm_remote_forward, 1116 &options.remote_forwards[i]); 1117 } 1118 } 1119 1120 /* Initiate tunnel forwarding. */ 1121 if (options.tun_open != SSH_TUNMODE_NO) { 1122 if (client_request_tun_fwd(options.tun_open, 1123 options.tun_local, options.tun_remote) == -1) { 1124 if (options.exit_on_forward_failure) 1125 fatal("Could not request tunnel forwarding."); 1126 else 1127 error("Could not request tunnel forwarding."); 1128 } 1129 } 1130 } 1131 1132 static void 1133 check_agent_present(void) 1134 { 1135 if (options.forward_agent) { 1136 /* Clear agent forwarding if we don't have an agent. */ 1137 if (!ssh_agent_present()) 1138 options.forward_agent = 0; 1139 } 1140 } 1141 1142 static int 1143 ssh_session(void) 1144 { 1145 int type; 1146 int interactive = 0; 1147 int have_tty = 0; 1148 struct winsize ws; 1149 const char *display; 1150 1151 /* Enable compression if requested. */ 1152 if (options.compression) { 1153 debug("Requesting compression at level %d.", 1154 options.compression_level); 1155 1156 if (options.compression_level < 1 || 1157 options.compression_level > 9) 1158 fatal("Compression level must be from 1 (fast) to " 1159 "9 (slow, best)."); 1160 1161 /* Send the request. */ 1162 packet_start(SSH_CMSG_REQUEST_COMPRESSION); 1163 packet_put_int(options.compression_level); 1164 packet_send(); 1165 packet_write_wait(); 1166 type = packet_read(); 1167 if (type == SSH_SMSG_SUCCESS) 1168 packet_start_compression(options.compression_level); 1169 else if (type == SSH_SMSG_FAILURE) 1170 logit("Warning: Remote host refused compression."); 1171 else 1172 packet_disconnect("Protocol error waiting for " 1173 "compression response."); 1174 } 1175 /* Allocate a pseudo tty if appropriate. */ 1176 if (tty_flag) { 1177 const char *dp; 1178 debug("Requesting pty."); 1179 1180 /* Start the packet. */ 1181 packet_start(SSH_CMSG_REQUEST_PTY); 1182 1183 /* Store TERM in the packet. There is no limit on the 1184 length of the string. */ 1185 dp = getenv("TERM"); 1186 if (!dp) 1187 dp = ""; 1188 packet_put_cstring(dp); 1189 1190 /* Store window size in the packet. */ 1191 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) 1192 memset(&ws, 0, sizeof(ws)); 1193 packet_put_int((u_int)ws.ws_row); 1194 packet_put_int((u_int)ws.ws_col); 1195 packet_put_int((u_int)ws.ws_xpixel); 1196 packet_put_int((u_int)ws.ws_ypixel); 1197 1198 /* Store tty modes in the packet. */ 1199 tty_make_modes(fileno(stdin), NULL); 1200 1201 /* Send the packet, and wait for it to leave. */ 1202 packet_send(); 1203 packet_write_wait(); 1204 1205 /* Read response from the server. */ 1206 type = packet_read(); 1207 if (type == SSH_SMSG_SUCCESS) { 1208 interactive = 1; 1209 have_tty = 1; 1210 } else if (type == SSH_SMSG_FAILURE) 1211 logit("Warning: Remote host failed or refused to " 1212 "allocate a pseudo tty."); 1213 else 1214 packet_disconnect("Protocol error waiting for pty " 1215 "request response."); 1216 } 1217 /* Request X11 forwarding if enabled and DISPLAY is set. */ 1218 display = getenv("DISPLAY"); 1219 if (options.forward_x11 && display != NULL) { 1220 char *proto, *data; 1221 /* Get reasonable local authentication information. */ 1222 client_x11_get_proto(display, options.xauth_location, 1223 options.forward_x11_trusted, 1224 options.forward_x11_timeout, 1225 &proto, &data); 1226 /* Request forwarding with authentication spoofing. */ 1227 debug("Requesting X11 forwarding with authentication " 1228 "spoofing."); 1229 x11_request_forwarding_with_spoofing(0, display, proto, 1230 data, 0); 1231 /* Read response from the server. */ 1232 type = packet_read(); 1233 if (type == SSH_SMSG_SUCCESS) { 1234 interactive = 1; 1235 } else if (type == SSH_SMSG_FAILURE) { 1236 logit("Warning: Remote host denied X11 forwarding."); 1237 } else { 1238 packet_disconnect("Protocol error waiting for X11 " 1239 "forwarding"); 1240 } 1241 } 1242 /* Tell the packet module whether this is an interactive session. */ 1243 packet_set_interactive(interactive, 1244 options.ip_qos_interactive, options.ip_qos_bulk); 1245 1246 /* Request authentication agent forwarding if appropriate. */ 1247 check_agent_present(); 1248 1249 if (options.forward_agent) { 1250 debug("Requesting authentication agent forwarding."); 1251 auth_request_forwarding(); 1252 1253 /* Read response from the server. */ 1254 type = packet_read(); 1255 packet_check_eom(); 1256 if (type != SSH_SMSG_SUCCESS) 1257 logit("Warning: Remote host denied authentication agent forwarding."); 1258 } 1259 1260 /* Initiate port forwardings. */ 1261 ssh_init_stdio_forwarding(); 1262 ssh_init_forwarding(); 1263 1264 /* Execute a local command */ 1265 if (options.local_command != NULL && 1266 options.permit_local_command) 1267 ssh_local_cmd(options.local_command); 1268 1269 /* 1270 * If requested and we are not interested in replies to remote 1271 * forwarding requests, then let ssh continue in the background. 1272 */ 1273 if (fork_after_authentication_flag) { 1274 if (options.exit_on_forward_failure && 1275 options.num_remote_forwards > 0) { 1276 debug("deferring postauth fork until remote forward " 1277 "confirmation received"); 1278 } else 1279 fork_postauth(); 1280 } 1281 1282 /* 1283 * If a command was specified on the command line, execute the 1284 * command now. Otherwise request the server to start a shell. 1285 */ 1286 if (buffer_len(&command) > 0) { 1287 int len = buffer_len(&command); 1288 if (len > 900) 1289 len = 900; 1290 debug("Sending command: %.*s", len, 1291 (u_char *)buffer_ptr(&command)); 1292 packet_start(SSH_CMSG_EXEC_CMD); 1293 packet_put_string(buffer_ptr(&command), buffer_len(&command)); 1294 packet_send(); 1295 packet_write_wait(); 1296 } else { 1297 debug("Requesting shell."); 1298 packet_start(SSH_CMSG_EXEC_SHELL); 1299 packet_send(); 1300 packet_write_wait(); 1301 } 1302 1303 /* Enter the interactive session. */ 1304 return client_loop(have_tty, tty_flag ? 1305 options.escape_char : SSH_ESCAPECHAR_NONE, 0); 1306 } 1307 1308 /* request pty/x11/agent/tcpfwd/shell for channel */ 1309 static void 1310 ssh_session2_setup(int id, int success, void *arg) 1311 { 1312 extern char **environ; 1313 const char *display; 1314 int interactive = tty_flag; 1315 1316 if (!success) 1317 return; /* No need for error message, channels code sens one */ 1318 1319 display = getenv("DISPLAY"); 1320 if (options.forward_x11 && display != NULL) { 1321 char *proto, *data; 1322 /* Get reasonable local authentication information. */ 1323 client_x11_get_proto(display, options.xauth_location, 1324 options.forward_x11_trusted, 1325 options.forward_x11_timeout, &proto, &data); 1326 /* Request forwarding with authentication spoofing. */ 1327 debug("Requesting X11 forwarding with authentication " 1328 "spoofing."); 1329 x11_request_forwarding_with_spoofing(id, display, proto, 1330 data, 1); 1331 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN); 1332 /* XXX exit_on_forward_failure */ 1333 interactive = 1; 1334 } 1335 1336 check_agent_present(); 1337 if (options.forward_agent) { 1338 debug("Requesting authentication agent forwarding."); 1339 channel_request_start(id, "auth-agent-req@openssh.com", 0); 1340 packet_send(); 1341 } 1342 1343 /* Tell the packet module whether this is an interactive session. */ 1344 packet_set_interactive(interactive, 1345 options.ip_qos_interactive, options.ip_qos_bulk); 1346 1347 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"), 1348 NULL, fileno(stdin), &command, environ); 1349 } 1350 1351 /* open new channel for a session */ 1352 static int 1353 ssh_session2_open(void) 1354 { 1355 Channel *c; 1356 int window, packetmax, in, out, err; 1357 int sock; 1358 int socksize; 1359 socklen_t socksizelen = sizeof(int); 1360 1361 if (stdin_null_flag) { 1362 in = open(_PATH_DEVNULL, O_RDONLY); 1363 } else { 1364 in = dup(STDIN_FILENO); 1365 } 1366 out = dup(STDOUT_FILENO); 1367 err = dup(STDERR_FILENO); 1368 1369 if (in < 0 || out < 0 || err < 0) 1370 fatal("dup() in/out/err failed"); 1371 1372 /* enable nonblocking unless tty */ 1373 if (!isatty(in)) 1374 set_nonblock(in); 1375 if (!isatty(out)) 1376 set_nonblock(out); 1377 if (!isatty(err)) 1378 set_nonblock(err); 1379 1380 /* we need to check to see if what they want to do about buffer */ 1381 /* sizes here. In a hpn to nonhpn connection we want to limit */ 1382 /* the window size to something reasonable in case the far side */ 1383 /* has the large window bug. In hpn to hpn connection we want to */ 1384 /* use the max window size but allow the user to override it */ 1385 /* lastly if they disabled hpn then use the ssh std window size */ 1386 1387 /* so why don't we just do a getsockopt() here and set the */ 1388 /* ssh window to that? In the case of a autotuning receive */ 1389 /* window the window would get stuck at the initial buffer */ 1390 /* size generally less than 96k. Therefore we need to set the */ 1391 /* maximum ssh window size to the maximum hpn buffer size */ 1392 /* unless the user has specifically set the tcprcvbufpoll */ 1393 /* to no. In which case we *can* just set the window to the */ 1394 /* minimum of the hpn buffer size and tcp receive buffer size */ 1395 1396 if (tty_flag) 1397 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT; 1398 else 1399 options.hpn_buffer_size = 2*1024*1024; 1400 1401 if (datafellows & SSH_BUG_LARGEWINDOW) 1402 { 1403 debug("HPN to Non-HPN Connection"); 1404 } 1405 else 1406 { 1407 if (options.tcp_rcv_buf_poll <= 0) 1408 { 1409 sock = socket(AF_INET, SOCK_STREAM, 0); 1410 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, 1411 &socksize, &socksizelen); 1412 close(sock); 1413 debug("socksize %d", socksize); 1414 options.hpn_buffer_size = socksize; 1415 debug ("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size); 1416 } 1417 else 1418 { 1419 if (options.tcp_rcv_buf > 0) 1420 { 1421 /*create a socket but don't connect it */ 1422 /* we use that the get the rcv socket size */ 1423 sock = socket(AF_INET, SOCK_STREAM, 0); 1424 /* if they are using the tcp_rcv_buf option */ 1425 /* attempt to set the buffer size to that */ 1426 if (options.tcp_rcv_buf) 1427 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf, 1428 sizeof(options.tcp_rcv_buf)); 1429 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, 1430 &socksize, &socksizelen); 1431 close(sock); 1432 debug("socksize %d", socksize); 1433 options.hpn_buffer_size = socksize; 1434 debug ("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size); 1435 } 1436 } 1437 1438 } 1439 1440 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size); 1441 1442 window = options.hpn_buffer_size; 1443 1444 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size); 1445 1446 packetmax = CHAN_SES_PACKET_DEFAULT; 1447 if (tty_flag) { 1448 window = 4*CHAN_SES_PACKET_DEFAULT; 1449 window >>= 1; 1450 packetmax >>= 1; 1451 } 1452 c = channel_new( 1453 "session", SSH_CHANNEL_OPENING, in, out, err, 1454 window, packetmax, CHAN_EXTENDED_WRITE, 1455 "client-session", /*nonblock*/0); 1456 1457 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) { 1458 c->dynamic_window = 1; 1459 debug ("Enabled Dynamic Window Scaling"); 1460 } 1461 debug3("ssh_session2_open: channel_new: %d", c->self); 1462 1463 channel_send_open(c->self); 1464 if (!no_shell_flag) 1465 channel_register_open_confirm(c->self, 1466 ssh_session2_setup, NULL); 1467 1468 return c->self; 1469 } 1470 1471 static int 1472 ssh_session2(void) 1473 { 1474 int id = -1; 1475 1476 /* XXX should be pre-session */ 1477 if (!options.control_persist) 1478 ssh_init_stdio_forwarding(); 1479 ssh_init_forwarding(); 1480 1481 /* Start listening for multiplex clients */ 1482 muxserver_listen(); 1483 1484 /* 1485 * If we are in control persist mode and have a working mux listen 1486 * socket, then prepare to background ourselves and have a foreground 1487 * client attach as a control slave. 1488 * NB. we must save copies of the flags that we override for 1489 * the backgrounding, since we defer attachment of the slave until 1490 * after the connection is fully established (in particular, 1491 * async rfwd replies have been received for ExitOnForwardFailure). 1492 */ 1493 if (options.control_persist && muxserver_sock != -1) { 1494 ostdin_null_flag = stdin_null_flag; 1495 ono_shell_flag = no_shell_flag; 1496 orequest_tty = options.request_tty; 1497 otty_flag = tty_flag; 1498 stdin_null_flag = 1; 1499 no_shell_flag = 1; 1500 tty_flag = 0; 1501 if (!fork_after_authentication_flag) 1502 need_controlpersist_detach = 1; 1503 fork_after_authentication_flag = 1; 1504 } 1505 /* 1506 * ControlPersist mux listen socket setup failed, attempt the 1507 * stdio forward setup that we skipped earlier. 1508 */ 1509 if (options.control_persist && muxserver_sock == -1) 1510 ssh_init_stdio_forwarding(); 1511 1512 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN)) 1513 id = ssh_session2_open(); 1514 else { 1515 packet_set_interactive( 1516 options.control_master == SSHCTL_MASTER_NO, 1517 options.ip_qos_interactive, options.ip_qos_bulk); 1518 } 1519 1520 /* If we don't expect to open a new session, then disallow it */ 1521 if (options.control_master == SSHCTL_MASTER_NO && 1522 (datafellows & SSH_NEW_OPENSSH)) { 1523 debug("Requesting no-more-sessions@openssh.com"); 1524 packet_start(SSH2_MSG_GLOBAL_REQUEST); 1525 packet_put_cstring("no-more-sessions@openssh.com"); 1526 packet_put_char(0); 1527 packet_send(); 1528 } 1529 1530 /* Execute a local command */ 1531 if (options.local_command != NULL && 1532 options.permit_local_command) 1533 ssh_local_cmd(options.local_command); 1534 1535 /* 1536 * If requested and we are not interested in replies to remote 1537 * forwarding requests, then let ssh continue in the background. 1538 */ 1539 if (fork_after_authentication_flag) { 1540 if (options.exit_on_forward_failure && 1541 options.num_remote_forwards > 0) { 1542 debug("deferring postauth fork until remote forward " 1543 "confirmation received"); 1544 } else 1545 fork_postauth(); 1546 } 1547 1548 if (options.use_roaming) 1549 request_roaming(); 1550 1551 return client_loop(tty_flag, tty_flag ? 1552 options.escape_char : SSH_ESCAPECHAR_NONE, id); 1553 } 1554 1555 static void 1556 load_public_identity_files(void) 1557 { 1558 char *filename, *cp, thishost[NI_MAXHOST]; 1559 char *pwdir = NULL, *pwname = NULL; 1560 int i = 0; 1561 Key *public; 1562 struct passwd *pw; 1563 u_int n_ids; 1564 char *identity_files[SSH_MAX_IDENTITY_FILES]; 1565 Key *identity_keys[SSH_MAX_IDENTITY_FILES]; 1566 #ifdef ENABLE_PKCS11 1567 Key **keys; 1568 int nkeys; 1569 #endif /* PKCS11 */ 1570 1571 n_ids = 0; 1572 bzero(identity_files, sizeof(identity_files)); 1573 bzero(identity_keys, sizeof(identity_keys)); 1574 1575 #ifdef ENABLE_PKCS11 1576 if (options.pkcs11_provider != NULL && 1577 options.num_identity_files < SSH_MAX_IDENTITY_FILES && 1578 (pkcs11_init(!options.batch_mode) == 0) && 1579 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL, 1580 &keys)) > 0) { 1581 for (i = 0; i < nkeys; i++) { 1582 if (n_ids >= SSH_MAX_IDENTITY_FILES) { 1583 key_free(keys[i]); 1584 continue; 1585 } 1586 identity_keys[n_ids] = keys[i]; 1587 identity_files[n_ids] = 1588 xstrdup(options.pkcs11_provider); /* XXX */ 1589 n_ids++; 1590 } 1591 free(keys); 1592 } 1593 #endif /* ENABLE_PKCS11 */ 1594 if ((pw = getpwuid(original_real_uid)) == NULL) 1595 fatal("load_public_identity_files: getpwuid failed"); 1596 pwname = xstrdup(pw->pw_name); 1597 pwdir = xstrdup(pw->pw_dir); 1598 if (gethostname(thishost, sizeof(thishost)) == -1) 1599 fatal("load_public_identity_files: gethostname: %s", 1600 strerror(errno)); 1601 for (i = 0; i < options.num_identity_files; i++) { 1602 if (n_ids >= SSH_MAX_IDENTITY_FILES || 1603 strcasecmp(options.identity_files[i], "none") == 0) { 1604 free(options.identity_files[i]); 1605 continue; 1606 } 1607 cp = tilde_expand_filename(options.identity_files[i], 1608 original_real_uid); 1609 filename = percent_expand(cp, "d", pwdir, 1610 "u", pwname, "l", thishost, "h", host, 1611 "r", options.user, (char *)NULL); 1612 free(cp); 1613 public = key_load_public(filename, NULL); 1614 debug("identity file %s type %d", filename, 1615 public ? public->type : -1); 1616 free(options.identity_files[i]); 1617 identity_files[n_ids] = filename; 1618 identity_keys[n_ids] = public; 1619 1620 if (++n_ids >= SSH_MAX_IDENTITY_FILES) 1621 continue; 1622 1623 /* Try to add the certificate variant too */ 1624 xasprintf(&cp, "%s-cert", filename); 1625 public = key_load_public(cp, NULL); 1626 debug("identity file %s type %d", cp, 1627 public ? public->type : -1); 1628 if (public == NULL) { 1629 free(cp); 1630 continue; 1631 } 1632 if (!key_is_cert(public)) { 1633 debug("%s: key %s type %s is not a certificate", 1634 __func__, cp, key_type(public)); 1635 key_free(public); 1636 free(cp); 1637 continue; 1638 } 1639 identity_keys[n_ids] = public; 1640 /* point to the original path, most likely the private key */ 1641 identity_files[n_ids] = xstrdup(filename); 1642 n_ids++; 1643 } 1644 options.num_identity_files = n_ids; 1645 memcpy(options.identity_files, identity_files, sizeof(identity_files)); 1646 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys)); 1647 1648 bzero(pwname, strlen(pwname)); 1649 free(pwname); 1650 bzero(pwdir, strlen(pwdir)); 1651 free(pwdir); 1652 } 1653 1654 static void 1655 main_sigchld_handler(int sig) 1656 { 1657 int save_errno = errno; 1658 pid_t pid; 1659 int status; 1660 1661 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 1662 (pid < 0 && errno == EINTR)) 1663 ; 1664 1665 signal(sig, main_sigchld_handler); 1666 errno = save_errno; 1667 } 1668 1669