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