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