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