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