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