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