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