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