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