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