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