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