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