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 * 17 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu> 18 * in Canada (German citizen). 19 * 20 * Redistribution and use in source and binary forms, with or without 21 * modification, are permitted provided that the following conditions 22 * are met: 23 * 1. Redistributions of source code must retain the above copyright 24 * notice, this list of conditions and the following disclaimer. 25 * 2. Redistributions in binary form must reproduce the above copyright 26 * notice, this list of conditions and the following disclaimer in the 27 * documentation and/or other materials provided with the distribution. 28 * 29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 39 */ 40 41 #include "includes.h" 42 RCSID("$OpenBSD: ssh.c,v 1.69 2000/10/27 07:32:19 markus Exp $"); 43 RCSID("$FreeBSD$"); 44 45 #include <openssl/evp.h> 46 #include <openssl/dsa.h> 47 #include <openssl/rsa.h> 48 49 #include "xmalloc.h" 50 #include "ssh.h" 51 #include "packet.h" 52 #include "buffer.h" 53 #include "readconf.h" 54 #include "uidswap.h" 55 56 #include "ssh2.h" 57 #include "compat.h" 58 #include "channels.h" 59 #include "key.h" 60 #include "authfd.h" 61 #include "authfile.h" 62 63 extern char *__progname; 64 65 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line. 66 Default value is AF_UNSPEC means both IPv4 and IPv6. */ 67 int IPv4or6 = AF_UNSPEC; 68 69 /* Flag indicating whether debug mode is on. This can be set on the command line. */ 70 int debug_flag = 0; 71 72 /* Flag indicating whether a tty should be allocated */ 73 int tty_flag = 0; 74 75 /* don't exec a shell */ 76 int no_shell_flag = 0; 77 int no_tty_flag = 0; 78 79 /* 80 * Flag indicating that nothing should be read from stdin. This can be set 81 * on the command line. 82 */ 83 int stdin_null_flag = 0; 84 85 /* 86 * Flag indicating that ssh should fork after authentication. This is useful 87 * so that the pasphrase can be entered manually, and then ssh goes to the 88 * background. 89 */ 90 int fork_after_authentication_flag = 0; 91 92 /* 93 * General data structure for command line options and options configurable 94 * in configuration files. See readconf.h. 95 */ 96 Options options; 97 98 /* 99 * Name of the host we are connecting to. This is the name given on the 100 * command line, or the HostName specified for the user-supplied name in a 101 * configuration file. 102 */ 103 char *host; 104 105 /* socket address the host resolves to */ 106 struct sockaddr_storage hostaddr; 107 108 /* 109 * Flag to indicate that we have received a window change signal which has 110 * not yet been processed. This will cause a message indicating the new 111 * window size to be sent to the server a little later. This is volatile 112 * because this is updated in a signal handler. 113 */ 114 volatile int received_window_change_signal = 0; 115 116 /* Value of argv[0] (set in the main program). */ 117 char *av0; 118 119 /* Flag indicating whether we have a valid host private key loaded. */ 120 int host_private_key_loaded = 0; 121 122 /* Host private key. */ 123 RSA *host_private_key = NULL; 124 125 /* Original real UID. */ 126 uid_t original_real_uid; 127 128 /* command to be executed */ 129 Buffer command; 130 131 /* Prints a help message to the user. This function never returns. */ 132 133 void 134 usage() 135 { 136 fprintf(stderr, "Usage: %s [options] host [command]\n", av0); 137 fprintf(stderr, "Options:\n"); 138 fprintf(stderr, " -l user Log in using this user name.\n"); 139 fprintf(stderr, " -n Redirect input from /dev/null.\n"); 140 fprintf(stderr, " -A Enable authentication agent forwarding.\n"); 141 fprintf(stderr, " -a Disable authentication agent forwarding.\n"); 142 #ifdef AFS 143 fprintf(stderr, " -k Disable Kerberos ticket and AFS token forwarding.\n"); 144 #endif /* AFS */ 145 fprintf(stderr, " -X Enable X11 connection forwarding.\n"); 146 fprintf(stderr, " -x Disable X11 connection forwarding.\n"); 147 fprintf(stderr, " -i file Identity for RSA authentication (default: ~/.ssh/identity).\n"); 148 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n"); 149 fprintf(stderr, " -T Do not allocate a tty.\n"); 150 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n"); 151 fprintf(stderr, " Multiple -v increases verbosity.\n"); 152 fprintf(stderr, " -V Display version number only.\n"); 153 fprintf(stderr, " -P Don't allocate a privileged port.\n"); 154 fprintf(stderr, " -q Quiet; don't display any warning messages.\n"); 155 fprintf(stderr, " -f Fork into background after authentication.\n"); 156 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n"); 157 158 fprintf(stderr, " -c cipher Select encryption algorithm: " 159 "``3des'', " 160 "``blowfish''\n"); 161 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n"); 162 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n"); 163 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n"); 164 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", av0); 165 fprintf(stderr, " forward them to the other side by connecting to host:port.\n"); 166 fprintf(stderr, " -C Enable compression.\n"); 167 fprintf(stderr, " -N Do not execute a shell or command.\n"); 168 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n"); 169 fprintf(stderr, " -4 Use IPv4 only.\n"); 170 fprintf(stderr, " -6 Use IPv6 only.\n"); 171 fprintf(stderr, " -2 Force protocol version 2.\n"); 172 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n"); 173 exit(1); 174 } 175 176 /* 177 * Connects to the given host using rsh (or prints an error message and exits 178 * if rsh is not available). This function never returns. 179 */ 180 void 181 rsh_connect(char *host, char *user, Buffer * command) 182 { 183 char *args[10]; 184 int i; 185 186 log("Using rsh. WARNING: Connection will not be encrypted."); 187 /* Build argument list for rsh. */ 188 i = 0; 189 #ifndef _PATH_RSH 190 #define _PATH_RSH "/usr/bin/rsh" 191 #endif 192 args[i++] = _PATH_RSH; 193 /* host may have to come after user on some systems */ 194 args[i++] = host; 195 if (user) { 196 args[i++] = "-l"; 197 args[i++] = user; 198 } 199 if (buffer_len(command) > 0) { 200 buffer_append(command, "\0", 1); 201 args[i++] = buffer_ptr(command); 202 } 203 args[i++] = NULL; 204 if (debug_flag) { 205 for (i = 0; args[i]; i++) { 206 if (i != 0) 207 fprintf(stderr, " "); 208 fprintf(stderr, "%s", args[i]); 209 } 210 fprintf(stderr, "\n"); 211 } 212 execv(_PATH_RSH, args); 213 perror(_PATH_RSH); 214 exit(1); 215 } 216 217 int ssh_session(void); 218 int ssh_session2(void); 219 220 /* 221 * Main program for the ssh client. 222 */ 223 int 224 main(int ac, char **av) 225 { 226 int i, opt, optind, exit_status, ok; 227 u_short fwd_port, fwd_host_port; 228 char *optarg, *cp, buf[256]; 229 struct stat st; 230 struct passwd *pw, pwcopy; 231 int dummy; 232 uid_t original_effective_uid; 233 234 /* 235 * Save the original real uid. It will be needed later (uid-swapping 236 * may clobber the real uid). 237 */ 238 original_real_uid = getuid(); 239 original_effective_uid = geteuid(); 240 241 /* If we are installed setuid root be careful to not drop core. */ 242 if (original_real_uid != original_effective_uid) { 243 struct rlimit rlim; 244 rlim.rlim_cur = rlim.rlim_max = 0; 245 if (setrlimit(RLIMIT_CORE, &rlim) < 0) 246 fatal("setrlimit failed: %.100s", strerror(errno)); 247 } 248 /* 249 * Use uid-swapping to give up root privileges for the duration of 250 * option processing. We will re-instantiate the rights when we are 251 * ready to create the privileged port, and will permanently drop 252 * them when the port has been created (actually, when the connection 253 * has been made, as we may need to create the port several times). 254 */ 255 temporarily_use_uid(original_real_uid); 256 257 /* 258 * Set our umask to something reasonable, as some files are created 259 * with the default umask. This will make them world-readable but 260 * writable only by the owner, which is ok for all files for which we 261 * don't set the modes explicitly. 262 */ 263 umask(022); 264 265 /* Save our own name. */ 266 av0 = av[0]; 267 268 /* Initialize option structure to indicate that no values have been set. */ 269 initialize_options(&options); 270 271 /* Parse command-line arguments. */ 272 host = NULL; 273 274 /* If program name is not one of the standard names, use it as host name. */ 275 if (strchr(av0, '/')) 276 cp = strrchr(av0, '/') + 1; 277 else 278 cp = av0; 279 if (strcmp(cp, "rsh") && strcmp(cp, "ssh") && strcmp(cp, "rlogin") && 280 strcmp(cp, "slogin") && strcmp(cp, "remsh")) 281 host = cp; 282 283 for (optind = 1; optind < ac; optind++) { 284 if (av[optind][0] != '-') { 285 if (host) 286 break; 287 if ((cp = strchr(av[optind], '@'))) { 288 if(cp == av[optind]) 289 usage(); 290 options.user = av[optind]; 291 *cp = '\0'; 292 host = ++cp; 293 } else 294 host = av[optind]; 295 continue; 296 } 297 opt = av[optind][1]; 298 if (!opt) 299 usage(); 300 if (strchr("eilcpLRo", opt)) { /* options with arguments */ 301 optarg = av[optind] + 2; 302 if (strcmp(optarg, "") == 0) { 303 if (optind >= ac - 1) 304 usage(); 305 optarg = av[++optind]; 306 } 307 } else { 308 if (av[optind][2]) 309 usage(); 310 optarg = NULL; 311 } 312 switch (opt) { 313 case '2': 314 options.protocol = SSH_PROTO_2; 315 break; 316 case '4': 317 IPv4or6 = AF_INET; 318 break; 319 case '6': 320 IPv4or6 = AF_INET6; 321 break; 322 case 'n': 323 stdin_null_flag = 1; 324 break; 325 case 'f': 326 fork_after_authentication_flag = 1; 327 stdin_null_flag = 1; 328 break; 329 case 'x': 330 options.forward_x11 = 0; 331 break; 332 case 'X': 333 options.forward_x11 = 1; 334 break; 335 case 'g': 336 options.gateway_ports = 1; 337 break; 338 case 'P': 339 options.use_privileged_port = 0; 340 break; 341 case 'a': 342 options.forward_agent = 0; 343 break; 344 case 'A': 345 options.forward_agent = 1; 346 break; 347 #ifdef AFS 348 case 'k': 349 options.krb4_tgt_passing = 0; 350 options.krb5_tgt_passing = 0; 351 options.afs_token_passing = 0; 352 break; 353 #endif 354 case 'i': 355 if (stat(optarg, &st) < 0) { 356 fprintf(stderr, "Warning: Identity file %s does not exist.\n", 357 optarg); 358 break; 359 } 360 if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES) 361 fatal("Too many identity files specified (max %d)", 362 SSH_MAX_IDENTITY_FILES); 363 options.identity_files[options.num_identity_files++] = 364 xstrdup(optarg); 365 break; 366 case 't': 367 tty_flag = 1; 368 break; 369 case 'v': 370 if (0 == debug_flag) { 371 debug_flag = 1; 372 options.log_level = SYSLOG_LEVEL_DEBUG1; 373 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) { 374 options.log_level++; 375 break; 376 } else { 377 fatal("Too high debugging level.\n"); 378 } 379 /* fallthrough */ 380 case 'V': 381 fprintf(stderr, "SSH Version %s, protocol versions %d.%d/%d.%d.\n", 382 SSH_VERSION, 383 PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1, 384 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2); 385 fprintf(stderr, "Compiled with SSL (0x%8.8lx).\n", SSLeay()); 386 if (opt == 'V') 387 exit(0); 388 break; 389 case 'q': 390 options.log_level = SYSLOG_LEVEL_QUIET; 391 break; 392 case 'e': 393 if (optarg[0] == '^' && optarg[2] == 0 && 394 (unsigned char) optarg[1] >= 64 && (unsigned char) optarg[1] < 128) 395 options.escape_char = (unsigned char) optarg[1] & 31; 396 else if (strlen(optarg) == 1) 397 options.escape_char = (unsigned char) optarg[0]; 398 else if (strcmp(optarg, "none") == 0) 399 options.escape_char = -2; 400 else { 401 fprintf(stderr, "Bad escape character '%s'.\n", optarg); 402 exit(1); 403 } 404 break; 405 case 'c': 406 if (ciphers_valid(optarg)) { 407 /* SSH2 only */ 408 options.ciphers = xstrdup(optarg); 409 options.cipher = SSH_CIPHER_ILLEGAL; 410 } else { 411 /* SSH1 only */ 412 Cipher *c = cipher_by_name(optarg); 413 if (c == NULL || c->number < 0) { 414 fprintf(stderr, "Unknown cipher type '%s'\n", optarg); 415 exit(1); 416 } 417 options.cipher = c->number; 418 } 419 break; 420 case 'p': 421 options.port = atoi(optarg); 422 break; 423 case 'l': 424 options.user = optarg; 425 break; 426 case 'R': 427 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf, 428 &fwd_host_port) != 3 && 429 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf, 430 &fwd_host_port) != 3) { 431 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg); 432 usage(); 433 /* NOTREACHED */ 434 } 435 add_remote_forward(&options, fwd_port, buf, fwd_host_port); 436 break; 437 case 'L': 438 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf, 439 &fwd_host_port) != 3 && 440 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf, 441 &fwd_host_port) != 3) { 442 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg); 443 usage(); 444 /* NOTREACHED */ 445 } 446 add_local_forward(&options, fwd_port, buf, fwd_host_port); 447 break; 448 case 'C': 449 options.compression = 1; 450 break; 451 case 'N': 452 no_shell_flag = 1; 453 no_tty_flag = 1; 454 break; 455 case 'T': 456 no_tty_flag = 1; 457 break; 458 case 'o': 459 dummy = 1; 460 if (process_config_line(&options, host ? host : "", optarg, 461 "command-line", 0, &dummy) != 0) 462 exit(1); 463 break; 464 default: 465 usage(); 466 } 467 } 468 469 /* Check that we got a host name. */ 470 if (!host) 471 usage(); 472 473 SSLeay_add_all_algorithms(); 474 475 /* Initialize the command to execute on remote host. */ 476 buffer_init(&command); 477 478 /* 479 * Save the command to execute on the remote host in a buffer. There 480 * is no limit on the length of the command, except by the maximum 481 * packet size. Also sets the tty flag if there is no command. 482 */ 483 if (optind == ac) { 484 /* No command specified - execute shell on a tty. */ 485 tty_flag = 1; 486 } else { 487 /* A command has been specified. Store it into the 488 buffer. */ 489 for (i = optind; i < ac; i++) { 490 if (i > optind) 491 buffer_append(&command, " ", 1); 492 buffer_append(&command, av[i], strlen(av[i])); 493 } 494 } 495 496 /* Cannot fork to background if no command. */ 497 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag) 498 fatal("Cannot fork into background without a command to execute."); 499 500 /* Allocate a tty by default if no command specified. */ 501 if (buffer_len(&command) == 0) 502 tty_flag = 1; 503 504 /* Do not allocate a tty if stdin is not a tty. */ 505 if (!isatty(fileno(stdin))) { 506 if (tty_flag) 507 fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n"); 508 tty_flag = 0; 509 } 510 /* force */ 511 if (no_tty_flag) 512 tty_flag = 0; 513 514 /* Get user data. */ 515 pw = getpwuid(original_real_uid); 516 if (!pw) { 517 fprintf(stderr, "You don't exist, go away!\n"); 518 exit(1); 519 } 520 /* Take a copy of the returned structure. */ 521 memset(&pwcopy, 0, sizeof(pwcopy)); 522 pwcopy.pw_name = xstrdup(pw->pw_name); 523 pwcopy.pw_passwd = xstrdup(pw->pw_passwd); 524 pwcopy.pw_uid = pw->pw_uid; 525 pwcopy.pw_gid = pw->pw_gid; 526 pwcopy.pw_dir = xstrdup(pw->pw_dir); 527 pwcopy.pw_shell = xstrdup(pw->pw_shell); 528 pwcopy.pw_class = xstrdup(pw->pw_class); 529 pwcopy.pw_expire = pw->pw_expire; 530 pwcopy.pw_change = pw->pw_change; 531 pw = &pwcopy; 532 533 /* Initialize "log" output. Since we are the client all output 534 actually goes to the terminal. */ 535 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0); 536 537 /* Read per-user configuration file. */ 538 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE); 539 read_config_file(buf, host, &options); 540 541 /* Read systemwide configuration file. */ 542 read_config_file(HOST_CONFIG_FILE, host, &options); 543 544 /* Fill configuration defaults. */ 545 fill_default_options(&options); 546 547 /* reinit */ 548 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0); 549 550 /* check if RSA support exists */ 551 if ((options.protocol & SSH_PROTO_1) && 552 rsa_alive() == 0) { 553 log("%s: no RSA support in libssl and libcrypto. See ssl(8).", 554 __progname); 555 log("Disabling protocol version 1"); 556 options.protocol &= ~ (SSH_PROTO_1|SSH_PROTO_1_PREFERRED); 557 } 558 if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) { 559 fprintf(stderr, "%s: No protocol version available.\n", 560 __progname); 561 exit(1); 562 } 563 564 if (options.user == NULL) 565 options.user = xstrdup(pw->pw_name); 566 567 if (options.hostname != NULL) 568 host = options.hostname; 569 570 /* Disable rhosts authentication if not running as root. */ 571 if (original_effective_uid != 0 || !options.use_privileged_port) { 572 options.rhosts_authentication = 0; 573 options.rhosts_rsa_authentication = 0; 574 } 575 /* 576 * If using rsh has been selected, exec it now (without trying 577 * anything else). Note that we must release privileges first. 578 */ 579 if (options.use_rsh) { 580 /* 581 * Restore our superuser privileges. This must be done 582 * before permanently setting the uid. 583 */ 584 restore_uid(); 585 586 /* Switch to the original uid permanently. */ 587 permanently_set_uid(original_real_uid); 588 589 /* Execute rsh. */ 590 rsh_connect(host, options.user, &command); 591 fatal("rsh_connect returned"); 592 } 593 /* Restore our superuser privileges. */ 594 restore_uid(); 595 596 /* 597 * Open a connection to the remote host. This needs root privileges 598 * if rhosts_{rsa_}authentication is enabled. 599 */ 600 601 ok = ssh_connect(&host, &hostaddr, options.port, 602 options.connection_attempts, 603 !options.rhosts_authentication && 604 !options.rhosts_rsa_authentication, 605 original_real_uid, 606 options.proxy_command); 607 608 /* 609 * If we successfully made the connection, load the host private key 610 * in case we will need it later for combined rsa-rhosts 611 * authentication. This must be done before releasing extra 612 * privileges, because the file is only readable by root. 613 */ 614 if (ok && (options.protocol & SSH_PROTO_1)) { 615 Key k; 616 host_private_key = RSA_new(); 617 k.type = KEY_RSA; 618 k.rsa = host_private_key; 619 if (load_private_key(HOST_KEY_FILE, "", &k, NULL)) 620 host_private_key_loaded = 1; 621 } 622 /* 623 * Get rid of any extra privileges that we may have. We will no 624 * longer need them. Also, extra privileges could make it very hard 625 * to read identity files and other non-world-readable files from the 626 * user's home directory if it happens to be on a NFS volume where 627 * root is mapped to nobody. 628 */ 629 630 /* 631 * Note that some legacy systems need to postpone the following call 632 * to permanently_set_uid() until the private hostkey is destroyed 633 * with RSA_free(). Otherwise the calling user could ptrace() the 634 * process, read the private hostkey and impersonate the host. 635 * OpenBSD does not allow ptracing of setuid processes. 636 */ 637 permanently_set_uid(original_real_uid); 638 639 /* 640 * Now that we are back to our own permissions, create ~/.ssh 641 * directory if it doesn\'t already exist. 642 */ 643 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR); 644 if (stat(buf, &st) < 0) 645 if (mkdir(buf, 0700) < 0) 646 error("Could not create directory '%.200s'.", buf); 647 648 /* Check if the connection failed, and try "rsh" if appropriate. */ 649 if (!ok) { 650 if (options.port != 0) 651 log("Secure connection to %.100s on port %hu refused%.100s.", 652 host, options.port, 653 options.fallback_to_rsh ? "; reverting to insecure method" : ""); 654 else 655 log("Secure connection to %.100s refused%.100s.", host, 656 options.fallback_to_rsh ? "; reverting to insecure method" : ""); 657 658 if (options.fallback_to_rsh) { 659 rsh_connect(host, options.user, &command); 660 fatal("rsh_connect returned"); 661 } 662 exit(1); 663 } 664 /* Expand ~ in options.identity_files. */ 665 /* XXX mem-leaks */ 666 for (i = 0; i < options.num_identity_files; i++) 667 options.identity_files[i] = 668 tilde_expand_filename(options.identity_files[i], original_real_uid); 669 for (i = 0; i < options.num_identity_files2; i++) 670 options.identity_files2[i] = 671 tilde_expand_filename(options.identity_files2[i], original_real_uid); 672 /* Expand ~ in known host file names. */ 673 options.system_hostfile = tilde_expand_filename(options.system_hostfile, 674 original_real_uid); 675 options.user_hostfile = tilde_expand_filename(options.user_hostfile, 676 original_real_uid); 677 options.system_hostfile2 = tilde_expand_filename(options.system_hostfile2, 678 original_real_uid); 679 options.user_hostfile2 = tilde_expand_filename(options.user_hostfile2, 680 original_real_uid); 681 682 /* Log into the remote system. This never returns if the login fails. */ 683 ssh_login(host_private_key_loaded, host_private_key, 684 host, (struct sockaddr *)&hostaddr, original_real_uid); 685 686 /* We no longer need the host private key. Clear it now. */ 687 if (host_private_key_loaded) 688 RSA_free(host_private_key); /* Destroys contents safely */ 689 690 exit_status = compat20 ? ssh_session2() : ssh_session(); 691 packet_close(); 692 return exit_status; 693 } 694 695 void 696 x11_get_proto(char *proto, int proto_len, char *data, int data_len) 697 { 698 char line[512]; 699 FILE *f; 700 int got_data = 0, i; 701 702 if (options.xauth_location) { 703 /* Try to get Xauthority information for the display. */ 704 snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null", 705 options.xauth_location, getenv("DISPLAY")); 706 f = popen(line, "r"); 707 if (f && fgets(line, sizeof(line), f) && 708 sscanf(line, "%*s %s %s", proto, data) == 2) 709 got_data = 1; 710 if (f) 711 pclose(f); 712 } 713 /* 714 * If we didn't get authentication data, just make up some 715 * data. The forwarding code will check the validity of the 716 * response anyway, and substitute this data. The X11 717 * server, however, will ignore this fake data and use 718 * whatever authentication mechanisms it was using otherwise 719 * for the local connection. 720 */ 721 if (!got_data) { 722 u_int32_t rand = 0; 723 724 strlcpy(proto, "MIT-MAGIC-COOKIE-1", proto_len); 725 for (i = 0; i < 16; i++) { 726 if (i % 4 == 0) 727 rand = arc4random(); 728 snprintf(data + 2 * i, data_len - 2 * i, "%02x", rand & 0xff); 729 rand >>= 8; 730 } 731 } 732 } 733 734 int 735 ssh_session(void) 736 { 737 int type; 738 int i; 739 int plen; 740 int interactive = 0; 741 int have_tty = 0; 742 struct winsize ws; 743 int authfd; 744 char *cp; 745 746 /* Enable compression if requested. */ 747 if (options.compression) { 748 debug("Requesting compression at level %d.", options.compression_level); 749 750 if (options.compression_level < 1 || options.compression_level > 9) 751 fatal("Compression level must be from 1 (fast) to 9 (slow, best)."); 752 753 /* Send the request. */ 754 packet_start(SSH_CMSG_REQUEST_COMPRESSION); 755 packet_put_int(options.compression_level); 756 packet_send(); 757 packet_write_wait(); 758 type = packet_read(&plen); 759 if (type == SSH_SMSG_SUCCESS) 760 packet_start_compression(options.compression_level); 761 else if (type == SSH_SMSG_FAILURE) 762 log("Warning: Remote host refused compression."); 763 else 764 packet_disconnect("Protocol error waiting for compression response."); 765 } 766 /* Allocate a pseudo tty if appropriate. */ 767 if (tty_flag) { 768 debug("Requesting pty."); 769 770 /* Start the packet. */ 771 packet_start(SSH_CMSG_REQUEST_PTY); 772 773 /* Store TERM in the packet. There is no limit on the 774 length of the string. */ 775 cp = getenv("TERM"); 776 if (!cp) 777 cp = ""; 778 packet_put_string(cp, strlen(cp)); 779 780 /* Store window size in the packet. */ 781 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) 782 memset(&ws, 0, sizeof(ws)); 783 packet_put_int(ws.ws_row); 784 packet_put_int(ws.ws_col); 785 packet_put_int(ws.ws_xpixel); 786 packet_put_int(ws.ws_ypixel); 787 788 /* Store tty modes in the packet. */ 789 tty_make_modes(fileno(stdin)); 790 791 /* Send the packet, and wait for it to leave. */ 792 packet_send(); 793 packet_write_wait(); 794 795 /* Read response from the server. */ 796 type = packet_read(&plen); 797 if (type == SSH_SMSG_SUCCESS) { 798 interactive = 1; 799 have_tty = 1; 800 } else if (type == SSH_SMSG_FAILURE) 801 log("Warning: Remote host failed or refused to allocate a pseudo tty."); 802 else 803 packet_disconnect("Protocol error waiting for pty request response."); 804 } 805 /* Request X11 forwarding if enabled and DISPLAY is set. */ 806 if (options.forward_x11 && getenv("DISPLAY") != NULL) { 807 char proto[512], data[512]; 808 /* Get reasonable local authentication information. */ 809 x11_get_proto(proto, sizeof proto, data, sizeof data); 810 /* Request forwarding with authentication spoofing. */ 811 debug("Requesting X11 forwarding with authentication spoofing."); 812 x11_request_forwarding_with_spoofing(0, proto, data); 813 814 /* Read response from the server. */ 815 type = packet_read(&plen); 816 if (type == SSH_SMSG_SUCCESS) { 817 interactive = 1; 818 } else if (type == SSH_SMSG_FAILURE) { 819 log("Warning: Remote host denied X11 forwarding."); 820 } else { 821 packet_disconnect("Protocol error waiting for X11 forwarding"); 822 } 823 } 824 /* Tell the packet module whether this is an interactive session. */ 825 packet_set_interactive(interactive, options.keepalives); 826 827 /* Clear agent forwarding if we don\'t have an agent. */ 828 authfd = ssh_get_authentication_socket(); 829 if (authfd < 0) 830 options.forward_agent = 0; 831 else 832 ssh_close_authentication_socket(authfd); 833 834 /* Request authentication agent forwarding if appropriate. */ 835 if (options.forward_agent) { 836 debug("Requesting authentication agent forwarding."); 837 auth_request_forwarding(); 838 839 /* Read response from the server. */ 840 type = packet_read(&plen); 841 packet_integrity_check(plen, 0, type); 842 if (type != SSH_SMSG_SUCCESS) 843 log("Warning: Remote host denied authentication agent forwarding."); 844 } 845 /* Initiate local TCP/IP port forwardings. */ 846 for (i = 0; i < options.num_local_forwards; i++) { 847 debug("Connections to local port %d forwarded to remote address %.200s:%d", 848 options.local_forwards[i].port, 849 options.local_forwards[i].host, 850 options.local_forwards[i].host_port); 851 channel_request_local_forwarding(options.local_forwards[i].port, 852 options.local_forwards[i].host, 853 options.local_forwards[i].host_port, 854 options.gateway_ports); 855 } 856 857 /* Initiate remote TCP/IP port forwardings. */ 858 for (i = 0; i < options.num_remote_forwards; i++) { 859 debug("Connections to remote port %d forwarded to local address %.200s:%d", 860 options.remote_forwards[i].port, 861 options.remote_forwards[i].host, 862 options.remote_forwards[i].host_port); 863 channel_request_remote_forwarding(options.remote_forwards[i].port, 864 options.remote_forwards[i].host, 865 options.remote_forwards[i].host_port); 866 } 867 868 /* If requested, let ssh continue in the background. */ 869 if (fork_after_authentication_flag) 870 if (daemon(1, 1) < 0) 871 fatal("daemon() failed: %.200s", strerror(errno)); 872 873 /* 874 * If a command was specified on the command line, execute the 875 * command now. Otherwise request the server to start a shell. 876 */ 877 if (buffer_len(&command) > 0) { 878 int len = buffer_len(&command); 879 if (len > 900) 880 len = 900; 881 debug("Sending command: %.*s", len, buffer_ptr(&command)); 882 packet_start(SSH_CMSG_EXEC_CMD); 883 packet_put_string(buffer_ptr(&command), buffer_len(&command)); 884 packet_send(); 885 packet_write_wait(); 886 } else { 887 debug("Requesting shell."); 888 packet_start(SSH_CMSG_EXEC_SHELL); 889 packet_send(); 890 packet_write_wait(); 891 } 892 893 /* Enter the interactive session. */ 894 return client_loop(have_tty, tty_flag ? options.escape_char : -1, 0); 895 } 896 897 void 898 init_local_fwd(void) 899 { 900 int i; 901 /* Initiate local TCP/IP port forwardings. */ 902 for (i = 0; i < options.num_local_forwards; i++) { 903 debug("Connections to local port %d forwarded to remote address %.200s:%d", 904 options.local_forwards[i].port, 905 options.local_forwards[i].host, 906 options.local_forwards[i].host_port); 907 channel_request_local_forwarding(options.local_forwards[i].port, 908 options.local_forwards[i].host, 909 options.local_forwards[i].host_port, 910 options.gateway_ports); 911 } 912 } 913 914 extern void client_set_session_ident(int id); 915 916 void 917 client_init(int id, void *arg) 918 { 919 int len; 920 debug("client_init id %d arg %d", id, (int)arg); 921 922 if (no_shell_flag) 923 goto done; 924 925 if (tty_flag) { 926 struct winsize ws; 927 char *cp; 928 cp = getenv("TERM"); 929 if (!cp) 930 cp = ""; 931 /* Store window size in the packet. */ 932 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) 933 memset(&ws, 0, sizeof(ws)); 934 935 channel_request_start(id, "pty-req", 0); 936 packet_put_cstring(cp); 937 packet_put_int(ws.ws_col); 938 packet_put_int(ws.ws_row); 939 packet_put_int(ws.ws_xpixel); 940 packet_put_int(ws.ws_ypixel); 941 packet_put_cstring(""); /* XXX: encode terminal modes */ 942 packet_send(); 943 /* XXX wait for reply */ 944 } 945 if (options.forward_x11 && 946 getenv("DISPLAY") != NULL) { 947 char proto[512], data[512]; 948 /* Get reasonable local authentication information. */ 949 x11_get_proto(proto, sizeof proto, data, sizeof data); 950 /* Request forwarding with authentication spoofing. */ 951 debug("Requesting X11 forwarding with authentication spoofing."); 952 x11_request_forwarding_with_spoofing(id, proto, data); 953 /* XXX wait for reply */ 954 } 955 956 len = buffer_len(&command); 957 if (len > 0) { 958 if (len > 900) 959 len = 900; 960 debug("Sending command: %.*s", len, buffer_ptr(&command)); 961 channel_request_start(id, "exec", 0); 962 packet_put_string(buffer_ptr(&command), len); 963 packet_send(); 964 } else { 965 channel_request(id, "shell", 0); 966 } 967 /* channel_callback(id, SSH2_MSG_OPEN_CONFIGMATION, client_init, 0); */ 968 done: 969 /* register different callback, etc. XXX */ 970 client_set_session_ident(id); 971 } 972 973 int 974 ssh_session2(void) 975 { 976 int window, packetmax, id; 977 int in, out, err; 978 979 if (stdin_null_flag) { 980 in = open("/dev/null", O_RDONLY); 981 } else { 982 in = dup(STDIN_FILENO); 983 } 984 out = dup(STDOUT_FILENO); 985 err = dup(STDERR_FILENO); 986 987 if (in < 0 || out < 0 || err < 0) 988 fatal("dup() in/out/err failed"); 989 990 /* enable nonblocking unless tty */ 991 if (!isatty(in)) 992 set_nonblock(in); 993 if (!isatty(out)) 994 set_nonblock(out); 995 if (!isatty(err)) 996 set_nonblock(err); 997 998 /* should be pre-session */ 999 init_local_fwd(); 1000 1001 /* If requested, let ssh continue in the background. */ 1002 if (fork_after_authentication_flag) 1003 if (daemon(1, 1) < 0) 1004 fatal("daemon() failed: %.200s", strerror(errno)); 1005 1006 window = CHAN_SES_WINDOW_DEFAULT; 1007 packetmax = CHAN_SES_PACKET_DEFAULT; 1008 if (!tty_flag) { 1009 window *= 2; 1010 packetmax *=2; 1011 } 1012 id = channel_new( 1013 "session", SSH_CHANNEL_OPENING, in, out, err, 1014 window, packetmax, CHAN_EXTENDED_WRITE, 1015 xstrdup("client-session"), /*nonblock*/0); 1016 1017 channel_open(id); 1018 channel_register_callback(id, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, client_init, (void *)0); 1019 1020 return client_loop(tty_flag, tty_flag ? options.escape_char : -1, id); 1021 } 1022