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