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