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