1 /* $NetBSD: ssh.c,v 1.9 2011/09/07 17:49:19 christos Exp $ */ 2 /* $OpenBSD: ssh.c,v 1.364 2011/08/02 23:15:03 djm Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * Ssh client program. This program can be used to log into a remote machine. 8 * The software supports strong authentication, encryption, and forwarding 9 * of X11, TCP/IP, and authentication connections. 10 * 11 * As far as I am concerned, the code I have written for this software 12 * can be used freely for any purpose. Any derived versions of this 13 * software must be clearly marked as such, and if the derived work is 14 * incompatible with the protocol description in the RFC file, it must be 15 * called by a name other than "ssh" or "Secure Shell". 16 * 17 * Copyright (c) 1999 Niels Provos. All rights reserved. 18 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved. 19 * 20 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu> 21 * in Canada (German citizen). 22 * 23 * Redistribution and use in source and binary forms, with or without 24 * modification, are permitted provided that the following conditions 25 * are met: 26 * 1. Redistributions of source code must retain the above copyright 27 * notice, this list of conditions and the following disclaimer. 28 * 2. Redistributions in binary form must reproduce the above copyright 29 * notice, this list of conditions and the following disclaimer in the 30 * documentation and/or other materials provided with the distribution. 31 * 32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 42 */ 43 44 #include "includes.h" 45 __RCSID("$NetBSD: ssh.c,v 1.9 2011/09/07 17:49:19 christos Exp $"); 46 #include <sys/types.h> 47 #include <sys/param.h> 48 #include <sys/ioctl.h> 49 #include <sys/param.h> 50 #include <sys/queue.h> 51 #include <sys/resource.h> 52 #include <sys/socket.h> 53 #include <sys/stat.h> 54 #include <sys/time.h> 55 #include <sys/wait.h> 56 57 #include <ctype.h> 58 #include <errno.h> 59 #include <fcntl.h> 60 #include <netdb.h> 61 #include <paths.h> 62 #include <pwd.h> 63 #include <signal.h> 64 #include <stddef.h> 65 #include <stdio.h> 66 #include <stdlib.h> 67 #include <string.h> 68 #include <unistd.h> 69 70 #include <openssl/evp.h> 71 #include <openssl/err.h> 72 73 #include "xmalloc.h" 74 #include "ssh.h" 75 #include "ssh1.h" 76 #include "ssh2.h" 77 #include "canohost.h" 78 #include "compat.h" 79 #include "cipher.h" 80 #include "packet.h" 81 #include "buffer.h" 82 #include "channels.h" 83 #include "key.h" 84 #include "authfd.h" 85 #include "authfile.h" 86 #include "pathnames.h" 87 #include "dispatch.h" 88 #include "clientloop.h" 89 #include "log.h" 90 #include "readconf.h" 91 #include "sshconnect.h" 92 #include "misc.h" 93 #include "kex.h" 94 #include "mac.h" 95 #include "sshpty.h" 96 #include "match.h" 97 #include "msg.h" 98 #include "uidswap.h" 99 #include "roaming.h" 100 #include "version.h" 101 102 #ifdef ENABLE_PKCS11 103 #include "ssh-pkcs11.h" 104 #endif 105 106 extern char *__progname; 107 108 /* Flag indicating whether debug mode is on. May be set on the command line. */ 109 int debug_flag = 0; 110 111 /* Flag indicating whether a tty should be requested */ 112 int tty_flag = 0; 113 114 /* don't exec a shell */ 115 int no_shell_flag = 0; 116 117 /* 118 * Flag indicating that nothing should be read from stdin. This can be set 119 * on the command line. 120 */ 121 int stdin_null_flag = 0; 122 123 /* 124 * Flag indicating that the current process should be backgrounded and 125 * a new slave launched in the foreground for ControlPersist. 126 */ 127 int need_controlpersist_detach = 0; 128 129 /* Copies of flags for ControlPersist foreground slave */ 130 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty; 131 132 /* 133 * Flag indicating that ssh should fork after authentication. This is useful 134 * so that the passphrase can be entered manually, and then ssh goes to the 135 * background. 136 */ 137 int fork_after_authentication_flag = 0; 138 139 /* forward stdio to remote host and port */ 140 char *stdio_forward_host = NULL; 141 int stdio_forward_port = 0; 142 143 /* 144 * General data structure for command line options and options configurable 145 * in configuration files. See readconf.h. 146 */ 147 Options options; 148 149 /* optional user configfile */ 150 char *config = NULL; 151 152 /* 153 * Name of the host we are connecting to. This is the name given on the 154 * command line, or the HostName specified for the user-supplied name in a 155 * configuration file. 156 */ 157 char *host; 158 159 /* socket address the host resolves to */ 160 struct sockaddr_storage hostaddr; 161 162 /* Private host keys. */ 163 Sensitive sensitive_data; 164 165 /* Original real UID. */ 166 uid_t original_real_uid; 167 uid_t original_effective_uid; 168 169 /* command to be executed */ 170 Buffer command; 171 172 /* Should we execute a command or invoke a subsystem? */ 173 int subsystem_flag = 0; 174 175 /* # of replies received for global requests */ 176 static int remote_forward_confirms_received = 0; 177 178 /* mux.c */ 179 extern int muxserver_sock; 180 extern u_int muxclient_command; 181 182 183 /* Prints a help message to the user. This function never returns. */ 184 185 __dead static void 186 usage(void) 187 { 188 fprintf(stderr, 189 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n" 190 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n" 191 " [-I pkcs11] [-i identity_file]\n" 192 " [-L [bind_address:]port:host:hostport]\n" 193 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n" 194 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n" 195 " [-W host:port] [-w local_tun[:remote_tun]]\n" 196 " [user@]hostname [command]\n" 197 ); 198 exit(255); 199 } 200 201 static int ssh_session(void); 202 static int ssh_session2(void); 203 static void load_public_identity_files(void); 204 static void main_sigchld_handler(int); 205 206 /* from muxclient.c */ 207 void muxclient(const char *); 208 void muxserver_listen(void); 209 210 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */ 211 static void 212 tilde_expand_paths(char **paths, u_int num_paths) 213 { 214 u_int i; 215 char *cp; 216 217 for (i = 0; i < num_paths; i++) { 218 cp = tilde_expand_filename(paths[i], original_real_uid); 219 xfree(paths[i]); 220 paths[i] = cp; 221 } 222 } 223 224 /* 225 * Main program for the ssh client. 226 */ 227 int 228 main(int ac, char **av) 229 { 230 int i, r, opt, exit_status, use_syslog; 231 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg; 232 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV]; 233 struct stat st; 234 struct passwd *pw; 235 int dummy, timeout_ms; 236 extern int optind, optreset; 237 extern char *optarg; 238 struct servent *sp; 239 Forward fwd; 240 241 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 242 sanitise_stdfd(); 243 244 /* 245 * Discard other fds that are hanging around. These can cause problem 246 * with backgrounded ssh processes started by ControlPersist. 247 */ 248 closefrom(STDERR_FILENO + 1); 249 250 /* 251 * Save the original real uid. It will be needed later (uid-swapping 252 * may clobber the real uid). 253 */ 254 original_real_uid = getuid(); 255 original_effective_uid = geteuid(); 256 257 /* 258 * Use uid-swapping to give up root privileges for the duration of 259 * option processing. We will re-instantiate the rights when we are 260 * ready to create the privileged port, and will permanently drop 261 * them when the port has been created (actually, when the connection 262 * has been made, as we may need to create the port several times). 263 */ 264 PRIV_END; 265 266 /* If we are installed setuid root be careful to not drop core. */ 267 if (original_real_uid != original_effective_uid) { 268 struct rlimit rlim; 269 rlim.rlim_cur = rlim.rlim_max = 0; 270 if (setrlimit(RLIMIT_CORE, &rlim) < 0) 271 fatal("setrlimit failed: %.100s", strerror(errno)); 272 } 273 /* Get user data. */ 274 pw = getpwuid(original_real_uid); 275 if (!pw) { 276 logit("You don't exist, go away!"); 277 exit(255); 278 } 279 /* Take a copy of the returned structure. */ 280 pw = pwcopy(pw); 281 282 /* 283 * Set our umask to something reasonable, as some files are created 284 * with the default umask. This will make them world-readable but 285 * writable only by the owner, which is ok for all files for which we 286 * don't set the modes explicitly. 287 */ 288 umask(022); 289 290 /* 291 * Initialize option structure to indicate that no values have been 292 * set. 293 */ 294 initialize_options(&options); 295 296 /* Parse command-line arguments. */ 297 host = NULL; 298 use_syslog = 0; 299 argv0 = av[0]; 300 301 again: 302 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx" 303 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) { 304 switch (opt) { 305 case '1': 306 options.protocol = SSH_PROTO_1; 307 break; 308 case '2': 309 options.protocol = SSH_PROTO_2; 310 break; 311 case '4': 312 options.address_family = AF_INET; 313 break; 314 case '6': 315 options.address_family = AF_INET6; 316 break; 317 case 'n': 318 stdin_null_flag = 1; 319 break; 320 case 'f': 321 fork_after_authentication_flag = 1; 322 stdin_null_flag = 1; 323 break; 324 case 'x': 325 options.forward_x11 = 0; 326 break; 327 case 'X': 328 options.forward_x11 = 1; 329 break; 330 case 'y': 331 use_syslog = 1; 332 break; 333 case 'Y': 334 options.forward_x11 = 1; 335 options.forward_x11_trusted = 1; 336 break; 337 case 'g': 338 options.gateway_ports = 1; 339 break; 340 case 'O': 341 if (stdio_forward_host != NULL) 342 fatal("Cannot specify multiplexing " 343 "command with -W"); 344 else if (muxclient_command != 0) 345 fatal("Multiplexing command already specified"); 346 if (strcmp(optarg, "check") == 0) 347 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK; 348 else if (strcmp(optarg, "forward") == 0) 349 muxclient_command = SSHMUX_COMMAND_FORWARD; 350 else if (strcmp(optarg, "exit") == 0) 351 muxclient_command = SSHMUX_COMMAND_TERMINATE; 352 else if (strcmp(optarg, "stop") == 0) 353 muxclient_command = SSHMUX_COMMAND_STOP; 354 else 355 fatal("Invalid multiplex command."); 356 break; 357 case 'P': /* deprecated */ 358 options.use_privileged_port = 0; 359 break; 360 case 'a': 361 options.forward_agent = 0; 362 break; 363 case 'A': 364 options.forward_agent = 1; 365 break; 366 case 'k': 367 options.gss_deleg_creds = 0; 368 break; 369 case 'K': 370 options.gss_authentication = 1; 371 options.gss_deleg_creds = 1; 372 break; 373 case 'i': 374 if (stat(optarg, &st) < 0) { 375 fprintf(stderr, "Warning: Identity file %s " 376 "not accessible: %s.\n", optarg, 377 strerror(errno)); 378 break; 379 } 380 if (options.num_identity_files >= 381 SSH_MAX_IDENTITY_FILES) 382 fatal("Too many identity files specified " 383 "(max %d)", SSH_MAX_IDENTITY_FILES); 384 options.identity_files[options.num_identity_files++] = 385 xstrdup(optarg); 386 break; 387 case 'I': 388 #ifdef ENABLE_PKCS11 389 options.pkcs11_provider = xstrdup(optarg); 390 #else 391 fprintf(stderr, "no support for PKCS#11.\n"); 392 #endif 393 break; 394 case 't': 395 if (options.request_tty == REQUEST_TTY_YES) 396 options.request_tty = REQUEST_TTY_FORCE; 397 else 398 options.request_tty = REQUEST_TTY_YES; 399 break; 400 case 'v': 401 if (debug_flag == 0) { 402 debug_flag = 1; 403 options.log_level = SYSLOG_LEVEL_DEBUG1; 404 } else { 405 if (options.log_level < SYSLOG_LEVEL_DEBUG3) 406 options.log_level++; 407 break; 408 } 409 /* FALLTHROUGH */ 410 case 'V': 411 fprintf(stderr, "%s, %s\n", 412 SSH_VERSION, SSLeay_version(SSLEAY_VERSION)); 413 if (opt == 'V') 414 exit(0); 415 break; 416 case 'w': 417 if (options.tun_open == -1) 418 options.tun_open = SSH_TUNMODE_DEFAULT; 419 options.tun_local = a2tun(optarg, &options.tun_remote); 420 if (options.tun_local == SSH_TUNID_ERR) { 421 fprintf(stderr, 422 "Bad tun device '%s'\n", optarg); 423 exit(255); 424 } 425 break; 426 case 'W': 427 if (stdio_forward_host != NULL) 428 fatal("stdio forward already specified"); 429 if (muxclient_command != 0) 430 fatal("Cannot specify stdio forward with -O"); 431 if (parse_forward(&fwd, optarg, 1, 0)) { 432 stdio_forward_host = fwd.listen_host; 433 stdio_forward_port = fwd.listen_port; 434 xfree(fwd.connect_host); 435 } else { 436 fprintf(stderr, 437 "Bad stdio forwarding specification '%s'\n", 438 optarg); 439 exit(255); 440 } 441 options.request_tty = REQUEST_TTY_NO; 442 no_shell_flag = 1; 443 options.clear_forwardings = 1; 444 options.exit_on_forward_failure = 1; 445 break; 446 case 'q': 447 options.log_level = SYSLOG_LEVEL_QUIET; 448 break; 449 case 'e': 450 if (optarg[0] == '^' && optarg[2] == 0 && 451 (u_char) optarg[1] >= 64 && 452 (u_char) optarg[1] < 128) 453 options.escape_char = (u_char) optarg[1] & 31; 454 else if (strlen(optarg) == 1) 455 options.escape_char = (u_char) optarg[0]; 456 else if (strcmp(optarg, "none") == 0) 457 options.escape_char = SSH_ESCAPECHAR_NONE; 458 else { 459 fprintf(stderr, "Bad escape character '%s'.\n", 460 optarg); 461 exit(255); 462 } 463 break; 464 case 'c': 465 if (ciphers_valid(optarg)) { 466 /* SSH2 only */ 467 options.ciphers = xstrdup(optarg); 468 options.cipher = SSH_CIPHER_INVALID; 469 } else { 470 /* SSH1 only */ 471 options.cipher = cipher_number(optarg); 472 if (options.cipher == -1) { 473 fprintf(stderr, 474 "Unknown cipher type '%s'\n", 475 optarg); 476 exit(255); 477 } 478 if (options.cipher == SSH_CIPHER_3DES) 479 options.ciphers = __UNCONST("3des-cbc"); 480 else if (options.cipher == SSH_CIPHER_BLOWFISH) 481 options.ciphers = 482 __UNCONST("blowfish-cbc"); 483 else 484 options.ciphers = (char *)-1; 485 } 486 break; 487 case 'm': 488 if (mac_valid(optarg)) 489 options.macs = xstrdup(optarg); 490 else { 491 fprintf(stderr, "Unknown mac type '%s'\n", 492 optarg); 493 exit(255); 494 } 495 break; 496 case 'M': 497 if (options.control_master == SSHCTL_MASTER_YES) 498 options.control_master = SSHCTL_MASTER_ASK; 499 else 500 options.control_master = SSHCTL_MASTER_YES; 501 break; 502 case 'p': 503 options.port = a2port(optarg); 504 if (options.port <= 0) { 505 fprintf(stderr, "Bad port '%s'\n", optarg); 506 exit(255); 507 } 508 break; 509 case 'l': 510 options.user = optarg; 511 break; 512 513 case 'L': 514 if (parse_forward(&fwd, optarg, 0, 0)) 515 add_local_forward(&options, &fwd); 516 else { 517 fprintf(stderr, 518 "Bad local forwarding specification '%s'\n", 519 optarg); 520 exit(255); 521 } 522 break; 523 524 case 'R': 525 if (parse_forward(&fwd, optarg, 0, 1)) { 526 add_remote_forward(&options, &fwd); 527 } else { 528 fprintf(stderr, 529 "Bad remote forwarding specification " 530 "'%s'\n", optarg); 531 exit(255); 532 } 533 break; 534 535 case 'D': 536 if (parse_forward(&fwd, optarg, 1, 0)) { 537 add_local_forward(&options, &fwd); 538 } else { 539 fprintf(stderr, 540 "Bad dynamic forwarding specification " 541 "'%s'\n", optarg); 542 exit(255); 543 } 544 break; 545 546 case 'C': 547 options.compression = 1; 548 break; 549 case 'N': 550 no_shell_flag = 1; 551 options.request_tty = REQUEST_TTY_NO; 552 break; 553 case 'T': 554 options.request_tty = REQUEST_TTY_NO; 555 /* ensure that the user doesn't try to backdoor a */ 556 /* null cipher switch on an interactive session */ 557 /* so explicitly disable it no matter what */ 558 options.none_switch = 0; 559 break; 560 case 'o': 561 dummy = 1; 562 line = xstrdup(optarg); 563 if (process_config_line(&options, host ? host : "", 564 line, "command-line", 0, &dummy) != 0) 565 exit(255); 566 xfree(line); 567 break; 568 case 's': 569 subsystem_flag = 1; 570 break; 571 case 'S': 572 if (options.control_path != NULL) 573 free(options.control_path); 574 options.control_path = xstrdup(optarg); 575 break; 576 case 'b': 577 options.bind_address = optarg; 578 break; 579 case 'F': 580 config = optarg; 581 break; 582 default: 583 usage(); 584 } 585 } 586 587 ac -= optind; 588 av += optind; 589 590 if (ac > 0 && !host) { 591 if (strrchr(*av, '@')) { 592 p = xstrdup(*av); 593 cp = strrchr(p, '@'); 594 if (cp == NULL || cp == p) 595 usage(); 596 options.user = p; 597 *cp = '\0'; 598 host = ++cp; 599 } else 600 host = *av; 601 if (ac > 1) { 602 optind = optreset = 1; 603 goto again; 604 } 605 ac--, av++; 606 } 607 608 /* Check that we got a host name. */ 609 if (!host) 610 usage(); 611 612 OpenSSL_add_all_algorithms(); 613 ERR_load_crypto_strings(); 614 615 /* Initialize the command to execute on remote host. */ 616 buffer_init(&command); 617 618 if (options.request_tty == REQUEST_TTY_YES || 619 options.request_tty == REQUEST_TTY_FORCE) 620 tty_flag = 1; 621 622 /* 623 * Save the command to execute on the remote host in a buffer. There 624 * is no limit on the length of the command, except by the maximum 625 * packet size. Also sets the tty flag if there is no command. 626 */ 627 if (!ac) { 628 /* No command specified - execute shell on a tty. */ 629 tty_flag = options.request_tty != REQUEST_TTY_NO; 630 if (subsystem_flag) { 631 fprintf(stderr, 632 "You must specify a subsystem to invoke.\n"); 633 usage(); 634 } 635 } else { 636 /* A command has been specified. Store it into the buffer. */ 637 for (i = 0; i < ac; i++) { 638 if (i) 639 buffer_append(&command, " ", 1); 640 buffer_append(&command, av[i], strlen(av[i])); 641 } 642 } 643 644 /* Cannot fork to background if no command. */ 645 if (fork_after_authentication_flag && buffer_len(&command) == 0 && 646 !no_shell_flag) 647 fatal("Cannot fork into background without a command " 648 "to execute."); 649 650 /* Allocate a tty by default if no command specified. */ 651 if (buffer_len(&command) == 0) 652 tty_flag = options.request_tty != REQUEST_TTY_NO; 653 654 /* Force no tty */ 655 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0) 656 tty_flag = 0; 657 /* Do not allocate a tty if stdin is not a tty. */ 658 if ((!isatty(fileno(stdin)) || stdin_null_flag) && 659 options.request_tty != REQUEST_TTY_FORCE) { 660 if (tty_flag) 661 logit("Pseudo-terminal will not be allocated because " 662 "stdin is not a terminal."); 663 tty_flag = 0; 664 } 665 666 /* 667 * Initialize "log" output. Since we are the client all output 668 * actually goes to stderr. 669 */ 670 log_init(argv0, 671 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level, 672 SYSLOG_FACILITY_USER, !use_syslog); 673 674 /* 675 * Read per-user configuration file. Ignore the system wide config 676 * file if the user specifies a config file on the command line. 677 */ 678 if (config != NULL) { 679 if (!read_config_file(config, host, &options, 0)) 680 fatal("Can't open user config file %.100s: " 681 "%.100s", config, strerror(errno)); 682 } else { 683 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir, 684 _PATH_SSH_USER_CONFFILE); 685 if (r > 0 && (size_t)r < sizeof(buf)) 686 (void)read_config_file(buf, host, &options, 1); 687 688 /* Read systemwide configuration file after user config. */ 689 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host, 690 &options, 0); 691 } 692 693 /* Fill configuration defaults. */ 694 fill_default_options(&options); 695 696 channel_set_af(options.address_family); 697 698 /* reinit */ 699 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog); 700 701 if (options.user == NULL) 702 options.user = xstrdup(pw->pw_name); 703 704 /* Get default port if port has not been set. */ 705 if (options.port == 0) { 706 sp = getservbyname(SSH_SERVICE_NAME, "tcp"); 707 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT; 708 } 709 710 /* preserve host name given on command line for %n expansion */ 711 host_arg = host; 712 if (options.hostname != NULL) { 713 host = percent_expand(options.hostname, 714 "h", host, (char *)NULL); 715 } 716 717 if (gethostname(thishost, sizeof(thishost)) == -1) 718 fatal("gethostname: %s", strerror(errno)); 719 strlcpy(shorthost, thishost, sizeof(shorthost)); 720 shorthost[strcspn(thishost, ".")] = '\0'; 721 snprintf(portstr, sizeof(portstr), "%d", options.port); 722 723 if (options.local_command != NULL) { 724 debug3("expanding LocalCommand: %s", options.local_command); 725 cp = options.local_command; 726 options.local_command = percent_expand(cp, "d", pw->pw_dir, 727 "h", host, "l", thishost, "n", host_arg, "r", options.user, 728 "p", portstr, "u", pw->pw_name, "L", shorthost, 729 (char *)NULL); 730 debug3("expanded LocalCommand: %s", options.local_command); 731 xfree(cp); 732 } 733 734 /* force lowercase for hostkey matching */ 735 if (options.host_key_alias != NULL) { 736 for (p = options.host_key_alias; *p; p++) 737 if (isupper((unsigned char)*p)) 738 *p = (char)tolower((unsigned char)*p); 739 } 740 741 if (options.proxy_command != NULL && 742 strcmp(options.proxy_command, "none") == 0) { 743 xfree(options.proxy_command); 744 options.proxy_command = NULL; 745 } 746 if (options.control_path != NULL && 747 strcmp(options.control_path, "none") == 0) { 748 xfree(options.control_path); 749 options.control_path = NULL; 750 } 751 752 if (options.control_path != NULL) { 753 cp = tilde_expand_filename(options.control_path, 754 original_real_uid); 755 xfree(options.control_path); 756 options.control_path = percent_expand(cp, "h", host, 757 "l", thishost, "n", host_arg, "r", options.user, 758 "p", portstr, "u", pw->pw_name, "L", shorthost, 759 (char *)NULL); 760 xfree(cp); 761 } 762 if (muxclient_command != 0 && options.control_path == NULL) 763 fatal("No ControlPath specified for \"-O\" command"); 764 if (options.control_path != NULL) 765 muxclient(options.control_path); 766 767 timeout_ms = options.connection_timeout * 1000; 768 769 /* Open a connection to the remote host. */ 770 if (ssh_connect(host, &hostaddr, options.port, 771 options.address_family, options.connection_attempts, &timeout_ms, 772 options.tcp_keep_alive, 773 original_effective_uid == 0 && options.use_privileged_port, 774 options.proxy_command) != 0) 775 exit(255); 776 777 if (timeout_ms > 0) 778 debug3("timeout: %d ms remain after connect", timeout_ms); 779 780 /* 781 * If we successfully made the connection, load the host private key 782 * in case we will need it later for combined rsa-rhosts 783 * authentication. This must be done before releasing extra 784 * privileges, because the file is only readable by root. 785 * If we cannot access the private keys, load the public keys 786 * instead and try to execute the ssh-keysign helper instead. 787 */ 788 sensitive_data.nkeys = 0; 789 sensitive_data.keys = NULL; 790 sensitive_data.external_keysign = 0; 791 if (options.rhosts_rsa_authentication || 792 options.hostbased_authentication) { 793 sensitive_data.nkeys = 7; 794 sensitive_data.keys = xcalloc(sensitive_data.nkeys, 795 sizeof(Key)); 796 797 PRIV_START; 798 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1, 799 _PATH_HOST_KEY_FILE, "", NULL, NULL); 800 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA, 801 _PATH_HOST_DSA_KEY_FILE, "", NULL); 802 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA, 803 _PATH_HOST_ECDSA_KEY_FILE, "", NULL); 804 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA, 805 _PATH_HOST_RSA_KEY_FILE, "", NULL); 806 sensitive_data.keys[4] = key_load_private_type(KEY_DSA, 807 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL); 808 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA, 809 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL); 810 sensitive_data.keys[6] = key_load_private_type(KEY_RSA, 811 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL); 812 PRIV_END; 813 814 if (options.hostbased_authentication == 1 && 815 sensitive_data.keys[0] == NULL && 816 sensitive_data.keys[4] == NULL && 817 sensitive_data.keys[5] == NULL && 818 sensitive_data.keys[6] == NULL) { 819 sensitive_data.keys[1] = key_load_cert( 820 _PATH_HOST_DSA_KEY_FILE); 821 sensitive_data.keys[2] = key_load_cert( 822 _PATH_HOST_ECDSA_KEY_FILE); 823 sensitive_data.keys[3] = key_load_cert( 824 _PATH_HOST_RSA_KEY_FILE); 825 sensitive_data.keys[4] = key_load_public( 826 _PATH_HOST_DSA_KEY_FILE, NULL); 827 sensitive_data.keys[5] = key_load_public( 828 _PATH_HOST_ECDSA_KEY_FILE, NULL); 829 sensitive_data.keys[6] = key_load_public( 830 _PATH_HOST_RSA_KEY_FILE, NULL); 831 sensitive_data.external_keysign = 1; 832 } 833 } 834 /* 835 * Get rid of any extra privileges that we may have. We will no 836 * longer need them. Also, extra privileges could make it very hard 837 * to read identity files and other non-world-readable files from the 838 * user's home directory if it happens to be on a NFS volume where 839 * root is mapped to nobody. 840 */ 841 if (original_effective_uid == 0) { 842 PRIV_START; 843 permanently_set_uid(pw); 844 } 845 846 /* 847 * Now that we are back to our own permissions, create ~/.ssh 848 * directory if it doesn't already exist. 849 */ 850 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir, 851 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR); 852 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) 853 if (mkdir(buf, 0700) < 0) 854 error("Could not create directory '%.200s'.", buf); 855 856 /* load options.identity_files */ 857 load_public_identity_files(); 858 859 /* Expand ~ in known host file names. */ 860 tilde_expand_paths(options.system_hostfiles, 861 options.num_system_hostfiles); 862 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles); 863 864 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */ 865 signal(SIGCHLD, main_sigchld_handler); 866 867 /* Log into the remote system. Never returns if the login fails. */ 868 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, 869 options.port, pw, timeout_ms); 870 871 if (packet_connection_is_on_socket()) { 872 verbose("Authenticated to %s ([%s]:%d).", host, 873 get_remote_ipaddr(), get_remote_port()); 874 } else { 875 verbose("Authenticated to %s (via proxy).", host); 876 } 877 878 /* We no longer need the private host keys. Clear them now. */ 879 if (sensitive_data.nkeys != 0) { 880 for (i = 0; i < sensitive_data.nkeys; i++) { 881 if (sensitive_data.keys[i] != NULL) { 882 /* Destroys contents safely */ 883 debug3("clear hostkey %d", i); 884 key_free(sensitive_data.keys[i]); 885 sensitive_data.keys[i] = NULL; 886 } 887 } 888 xfree(sensitive_data.keys); 889 } 890 for (i = 0; i < options.num_identity_files; i++) { 891 if (options.identity_files[i]) { 892 xfree(options.identity_files[i]); 893 options.identity_files[i] = NULL; 894 } 895 if (options.identity_keys[i]) { 896 key_free(options.identity_keys[i]); 897 options.identity_keys[i] = NULL; 898 } 899 } 900 901 exit_status = compat20 ? ssh_session2() : ssh_session(); 902 packet_close(); 903 904 if (options.control_path != NULL && muxserver_sock != -1) 905 unlink(options.control_path); 906 907 /* Kill ProxyCommand if it is running. */ 908 ssh_kill_proxy_command(); 909 910 return exit_status; 911 } 912 913 static void 914 control_persist_detach(void) 915 { 916 pid_t pid; 917 int devnull; 918 919 debug("%s: backgrounding master process", __func__); 920 921 /* 922 * master (current process) into the background, and make the 923 * foreground process a client of the backgrounded master. 924 */ 925 switch ((pid = fork())) { 926 case -1: 927 fatal("%s: fork: %s", __func__, strerror(errno)); 928 case 0: 929 /* Child: master process continues mainloop */ 930 break; 931 default: 932 /* Parent: set up mux slave to connect to backgrounded master */ 933 debug2("%s: background process is %ld", __func__, (long)pid); 934 stdin_null_flag = ostdin_null_flag; 935 options.request_tty = orequest_tty; 936 tty_flag = otty_flag; 937 close(muxserver_sock); 938 muxserver_sock = -1; 939 options.control_master = SSHCTL_MASTER_NO; 940 muxclient(options.control_path); 941 /* muxclient() doesn't return on success. */ 942 fatal("Failed to connect to new control master"); 943 } 944 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 945 error("%s: open(\"/dev/null\"): %s", __func__, 946 strerror(errno)); 947 } else { 948 if (dup2(devnull, STDIN_FILENO) == -1 || 949 dup2(devnull, STDOUT_FILENO) == -1) 950 error("%s: dup2: %s", __func__, strerror(errno)); 951 if (devnull > STDERR_FILENO) 952 close(devnull); 953 } 954 setproctitle("%s [mux]", options.control_path); 955 } 956 957 /* Do fork() after authentication. Used by "ssh -f" */ 958 static void 959 fork_postauth(void) 960 { 961 if (need_controlpersist_detach) 962 control_persist_detach(); 963 debug("forking to background"); 964 fork_after_authentication_flag = 0; 965 if (daemon(1, 1) < 0) 966 fatal("daemon() failed: %.200s", strerror(errno)); 967 } 968 969 /* Callback for remote forward global requests */ 970 static void 971 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt) 972 { 973 Forward *rfwd = (Forward *)ctxt; 974 975 /* XXX verbose() on failure? */ 976 debug("remote forward %s for: listen %d, connect %s:%d", 977 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure", 978 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port); 979 if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) { 980 rfwd->allocated_port = packet_get_int(); 981 logit("Allocated port %u for remote forward to %s:%d", 982 rfwd->allocated_port, 983 rfwd->connect_host, rfwd->connect_port); 984 } 985 986 if (type == SSH2_MSG_REQUEST_FAILURE) { 987 if (options.exit_on_forward_failure) 988 fatal("Error: remote port forwarding failed for " 989 "listen port %d", rfwd->listen_port); 990 else 991 logit("Warning: remote port forwarding failed for " 992 "listen port %d", rfwd->listen_port); 993 } 994 if (++remote_forward_confirms_received == options.num_remote_forwards) { 995 debug("All remote forwarding requests processed"); 996 if (fork_after_authentication_flag) 997 fork_postauth(); 998 } 999 } 1000 1001 __dead static void 1002 client_cleanup_stdio_fwd(int id, void *arg) 1003 { 1004 debug("stdio forwarding: done"); 1005 cleanup_exit(0); 1006 } 1007 1008 static int 1009 client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect) 1010 { 1011 Channel *c; 1012 int in, out; 1013 1014 debug3("client_setup_stdio_fwd %s:%d", host_to_connect, 1015 port_to_connect); 1016 1017 in = dup(STDIN_FILENO); 1018 out = dup(STDOUT_FILENO); 1019 if (in < 0 || out < 0) 1020 fatal("channel_connect_stdio_fwd: dup() in/out failed"); 1021 1022 if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect, 1023 in, out)) == NULL) 1024 return 0; 1025 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0); 1026 return 1; 1027 } 1028 1029 static void 1030 ssh_init_forwarding(void) 1031 { 1032 int success = 0; 1033 int i; 1034 1035 if (stdio_forward_host != NULL) { 1036 if (!compat20) { 1037 fatal("stdio forwarding require Protocol 2"); 1038 } 1039 if (!client_setup_stdio_fwd(stdio_forward_host, 1040 stdio_forward_port)) 1041 fatal("Failed to connect in stdio forward mode."); 1042 } 1043 1044 /* Initiate local TCP/IP port forwardings. */ 1045 for (i = 0; i < options.num_local_forwards; i++) { 1046 debug("Local connections to %.200s:%d forwarded to remote " 1047 "address %.200s:%d", 1048 (options.local_forwards[i].listen_host == NULL) ? 1049 (options.gateway_ports ? "*" : "LOCALHOST") : 1050 options.local_forwards[i].listen_host, 1051 options.local_forwards[i].listen_port, 1052 options.local_forwards[i].connect_host, 1053 options.local_forwards[i].connect_port); 1054 success += channel_setup_local_fwd_listener( 1055 options.local_forwards[i].listen_host, 1056 options.local_forwards[i].listen_port, 1057 options.local_forwards[i].connect_host, 1058 options.local_forwards[i].connect_port, 1059 options.gateway_ports); 1060 } 1061 if (i > 0 && success != i && options.exit_on_forward_failure) 1062 fatal("Could not request local forwarding."); 1063 if (i > 0 && success == 0) 1064 error("Could not request local forwarding."); 1065 1066 /* Initiate remote TCP/IP port forwardings. */ 1067 for (i = 0; i < options.num_remote_forwards; i++) { 1068 debug("Remote connections from %.200s:%d forwarded to " 1069 "local address %.200s:%d", 1070 (options.remote_forwards[i].listen_host == NULL) ? 1071 "LOCALHOST" : options.remote_forwards[i].listen_host, 1072 options.remote_forwards[i].listen_port, 1073 options.remote_forwards[i].connect_host, 1074 options.remote_forwards[i].connect_port); 1075 if (channel_request_remote_forwarding( 1076 options.remote_forwards[i].listen_host, 1077 options.remote_forwards[i].listen_port, 1078 options.remote_forwards[i].connect_host, 1079 options.remote_forwards[i].connect_port) < 0) { 1080 if (options.exit_on_forward_failure) 1081 fatal("Could not request remote forwarding."); 1082 else 1083 logit("Warning: Could not request remote " 1084 "forwarding."); 1085 } 1086 client_register_global_confirm(ssh_confirm_remote_forward, 1087 &options.remote_forwards[i]); 1088 } 1089 1090 /* Initiate tunnel forwarding. */ 1091 if (options.tun_open != SSH_TUNMODE_NO) { 1092 if (client_request_tun_fwd(options.tun_open, 1093 options.tun_local, options.tun_remote) == -1) { 1094 if (options.exit_on_forward_failure) 1095 fatal("Could not request tunnel forwarding."); 1096 else 1097 error("Could not request tunnel forwarding."); 1098 } 1099 } 1100 } 1101 1102 static void 1103 check_agent_present(void) 1104 { 1105 if (options.forward_agent) { 1106 /* Clear agent forwarding if we don't have an agent. */ 1107 if (!ssh_agent_present()) 1108 options.forward_agent = 0; 1109 } 1110 } 1111 1112 static int 1113 ssh_session(void) 1114 { 1115 int type; 1116 int interactive = 0; 1117 int have_tty = 0; 1118 struct winsize ws; 1119 const char *display; 1120 1121 /* Enable compression if requested. */ 1122 if (options.compression) { 1123 debug("Requesting compression at level %d.", 1124 options.compression_level); 1125 1126 if (options.compression_level < 1 || 1127 options.compression_level > 9) 1128 fatal("Compression level must be from 1 (fast) to " 1129 "9 (slow, best)."); 1130 1131 /* Send the request. */ 1132 packet_start(SSH_CMSG_REQUEST_COMPRESSION); 1133 packet_put_int(options.compression_level); 1134 packet_send(); 1135 packet_write_wait(); 1136 type = packet_read(); 1137 if (type == SSH_SMSG_SUCCESS) 1138 packet_start_compression(options.compression_level); 1139 else if (type == SSH_SMSG_FAILURE) 1140 logit("Warning: Remote host refused compression."); 1141 else 1142 packet_disconnect("Protocol error waiting for " 1143 "compression response."); 1144 } 1145 /* Allocate a pseudo tty if appropriate. */ 1146 if (tty_flag) { 1147 const char *dp; 1148 debug("Requesting pty."); 1149 1150 /* Start the packet. */ 1151 packet_start(SSH_CMSG_REQUEST_PTY); 1152 1153 /* Store TERM in the packet. There is no limit on the 1154 length of the string. */ 1155 dp = getenv("TERM"); 1156 if (!dp) 1157 dp = ""; 1158 packet_put_cstring(dp); 1159 1160 /* Store window size in the packet. */ 1161 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) 1162 memset(&ws, 0, sizeof(ws)); 1163 packet_put_int((u_int)ws.ws_row); 1164 packet_put_int((u_int)ws.ws_col); 1165 packet_put_int((u_int)ws.ws_xpixel); 1166 packet_put_int((u_int)ws.ws_ypixel); 1167 1168 /* Store tty modes in the packet. */ 1169 tty_make_modes(fileno(stdin), NULL); 1170 1171 /* Send the packet, and wait for it to leave. */ 1172 packet_send(); 1173 packet_write_wait(); 1174 1175 /* Read response from the server. */ 1176 type = packet_read(); 1177 if (type == SSH_SMSG_SUCCESS) { 1178 interactive = 1; 1179 have_tty = 1; 1180 } else if (type == SSH_SMSG_FAILURE) 1181 logit("Warning: Remote host failed or refused to " 1182 "allocate a pseudo tty."); 1183 else 1184 packet_disconnect("Protocol error waiting for pty " 1185 "request response."); 1186 } 1187 /* Request X11 forwarding if enabled and DISPLAY is set. */ 1188 display = getenv("DISPLAY"); 1189 if (options.forward_x11 && display != NULL) { 1190 char *proto, *data; 1191 /* Get reasonable local authentication information. */ 1192 client_x11_get_proto(display, options.xauth_location, 1193 options.forward_x11_trusted, 1194 options.forward_x11_timeout, 1195 &proto, &data); 1196 /* Request forwarding with authentication spoofing. */ 1197 debug("Requesting X11 forwarding with authentication " 1198 "spoofing."); 1199 x11_request_forwarding_with_spoofing(0, display, proto, 1200 data, 0); 1201 /* Read response from the server. */ 1202 type = packet_read(); 1203 if (type == SSH_SMSG_SUCCESS) { 1204 interactive = 1; 1205 } else if (type == SSH_SMSG_FAILURE) { 1206 logit("Warning: Remote host denied X11 forwarding."); 1207 } else { 1208 packet_disconnect("Protocol error waiting for X11 " 1209 "forwarding"); 1210 } 1211 } 1212 /* Tell the packet module whether this is an interactive session. */ 1213 packet_set_interactive(interactive, 1214 options.ip_qos_interactive, options.ip_qos_bulk); 1215 1216 /* Request authentication agent forwarding if appropriate. */ 1217 check_agent_present(); 1218 1219 if (options.forward_agent) { 1220 debug("Requesting authentication agent forwarding."); 1221 auth_request_forwarding(); 1222 1223 /* Read response from the server. */ 1224 type = packet_read(); 1225 packet_check_eom(); 1226 if (type != SSH_SMSG_SUCCESS) 1227 logit("Warning: Remote host denied authentication agent forwarding."); 1228 } 1229 1230 /* Initiate port forwardings. */ 1231 ssh_init_forwarding(); 1232 1233 /* Execute a local command */ 1234 if (options.local_command != NULL && 1235 options.permit_local_command) 1236 ssh_local_cmd(options.local_command); 1237 1238 /* 1239 * If requested and we are not interested in replies to remote 1240 * forwarding requests, then let ssh continue in the background. 1241 */ 1242 if (fork_after_authentication_flag) { 1243 if (options.exit_on_forward_failure && 1244 options.num_remote_forwards > 0) { 1245 debug("deferring postauth fork until remote forward " 1246 "confirmation received"); 1247 } else 1248 fork_postauth(); 1249 } 1250 1251 /* 1252 * If a command was specified on the command line, execute the 1253 * command now. Otherwise request the server to start a shell. 1254 */ 1255 if (buffer_len(&command) > 0) { 1256 int len = buffer_len(&command); 1257 if (len > 900) 1258 len = 900; 1259 debug("Sending command: %.*s", len, 1260 (u_char *)buffer_ptr(&command)); 1261 packet_start(SSH_CMSG_EXEC_CMD); 1262 packet_put_string(buffer_ptr(&command), buffer_len(&command)); 1263 packet_send(); 1264 packet_write_wait(); 1265 } else { 1266 debug("Requesting shell."); 1267 packet_start(SSH_CMSG_EXEC_SHELL); 1268 packet_send(); 1269 packet_write_wait(); 1270 } 1271 1272 /* Enter the interactive session. */ 1273 return client_loop(have_tty, tty_flag ? 1274 options.escape_char : SSH_ESCAPECHAR_NONE, 0); 1275 } 1276 1277 /* request pty/x11/agent/tcpfwd/shell for channel */ 1278 static void 1279 ssh_session2_setup(int id, int success, void *arg) 1280 { 1281 extern char **environ; 1282 const char *display; 1283 int interactive = tty_flag; 1284 1285 if (!success) 1286 return; /* No need for error message, channels code sens one */ 1287 1288 display = getenv("DISPLAY"); 1289 if (options.forward_x11 && display != NULL) { 1290 char *proto, *data; 1291 /* Get reasonable local authentication information. */ 1292 client_x11_get_proto(display, options.xauth_location, 1293 options.forward_x11_trusted, 1294 options.forward_x11_timeout, &proto, &data); 1295 /* Request forwarding with authentication spoofing. */ 1296 debug("Requesting X11 forwarding with authentication " 1297 "spoofing."); 1298 x11_request_forwarding_with_spoofing(id, display, proto, 1299 data, 1); 1300 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN); 1301 /* XXX exit_on_forward_failure */ 1302 interactive = 1; 1303 } 1304 1305 check_agent_present(); 1306 if (options.forward_agent) { 1307 debug("Requesting authentication agent forwarding."); 1308 channel_request_start(id, "auth-agent-req@openssh.com", 0); 1309 packet_send(); 1310 } 1311 1312 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"), 1313 NULL, fileno(stdin), &command, environ); 1314 } 1315 1316 /* open new channel for a session */ 1317 static int 1318 ssh_session2_open(void) 1319 { 1320 Channel *c; 1321 int window, packetmax, in, out, err; 1322 int sock; 1323 int socksize; 1324 socklen_t socksizelen = sizeof(int); 1325 1326 if (stdin_null_flag) { 1327 in = open(_PATH_DEVNULL, O_RDONLY); 1328 } else { 1329 in = dup(STDIN_FILENO); 1330 } 1331 out = dup(STDOUT_FILENO); 1332 err = dup(STDERR_FILENO); 1333 1334 if (in < 0 || out < 0 || err < 0) 1335 fatal("dup() in/out/err failed"); 1336 1337 /* enable nonblocking unless tty */ 1338 if (!isatty(in)) 1339 set_nonblock(in); 1340 if (!isatty(out)) 1341 set_nonblock(out); 1342 if (!isatty(err)) 1343 set_nonblock(err); 1344 1345 /* we need to check to see if what they want to do about buffer */ 1346 /* sizes here. In a hpn to nonhpn connection we want to limit */ 1347 /* the window size to something reasonable in case the far side */ 1348 /* has the large window bug. In hpn to hpn connection we want to */ 1349 /* use the max window size but allow the user to override it */ 1350 /* lastly if they disabled hpn then use the ssh std window size */ 1351 1352 /* so why don't we just do a getsockopt() here and set the */ 1353 /* ssh window to that? In the case of a autotuning receive */ 1354 /* window the window would get stuck at the initial buffer */ 1355 /* size generally less than 96k. Therefore we need to set the */ 1356 /* maximum ssh window size to the maximum hpn buffer size */ 1357 /* unless the user has specifically set the tcprcvbufpoll */ 1358 /* to no. In which case we *can* just set the window to the */ 1359 /* minimum of the hpn buffer size and tcp receive buffer size */ 1360 1361 if (tty_flag) 1362 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT; 1363 else 1364 options.hpn_buffer_size = 2*1024*1024; 1365 1366 if (datafellows & SSH_BUG_LARGEWINDOW) 1367 { 1368 debug("HPN to Non-HPN Connection"); 1369 } 1370 else 1371 { 1372 if (options.tcp_rcv_buf_poll <= 0) 1373 { 1374 sock = socket(AF_INET, SOCK_STREAM, 0); 1375 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, 1376 &socksize, &socksizelen); 1377 close(sock); 1378 debug("socksize %d", socksize); 1379 options.hpn_buffer_size = socksize; 1380 debug ("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size); 1381 } 1382 else 1383 { 1384 if (options.tcp_rcv_buf > 0) 1385 { 1386 /*create a socket but don't connect it */ 1387 /* we use that the get the rcv socket size */ 1388 sock = socket(AF_INET, SOCK_STREAM, 0); 1389 /* if they are using the tcp_rcv_buf option */ 1390 /* attempt to set the buffer size to that */ 1391 if (options.tcp_rcv_buf) 1392 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf, 1393 sizeof(options.tcp_rcv_buf)); 1394 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, 1395 &socksize, &socksizelen); 1396 close(sock); 1397 debug("socksize %d", socksize); 1398 options.hpn_buffer_size = socksize; 1399 debug ("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size); 1400 } 1401 } 1402 1403 } 1404 1405 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size); 1406 1407 window = options.hpn_buffer_size; 1408 1409 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size); 1410 1411 packetmax = CHAN_SES_PACKET_DEFAULT; 1412 if (tty_flag) { 1413 window = 4*CHAN_SES_PACKET_DEFAULT; 1414 window >>= 1; 1415 packetmax >>= 1; 1416 } 1417 c = channel_new( 1418 "session", SSH_CHANNEL_OPENING, in, out, err, 1419 window, packetmax, CHAN_EXTENDED_WRITE, 1420 "client-session", /*nonblock*/0); 1421 1422 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) { 1423 c->dynamic_window = 1; 1424 debug ("Enabled Dynamic Window Scaling\n"); 1425 } 1426 debug3("ssh_session2_open: channel_new: %d", c->self); 1427 1428 channel_send_open(c->self); 1429 if (!no_shell_flag) 1430 channel_register_open_confirm(c->self, 1431 ssh_session2_setup, NULL); 1432 1433 return c->self; 1434 } 1435 1436 static int 1437 ssh_session2(void) 1438 { 1439 int id = -1; 1440 1441 /* XXX should be pre-session */ 1442 ssh_init_forwarding(); 1443 1444 /* Start listening for multiplex clients */ 1445 muxserver_listen(); 1446 1447 /* 1448 * If we are in control persist mode, then prepare to background 1449 * ourselves and have a foreground client attach as a control 1450 * slave. NB. we must save copies of the flags that we override for 1451 * the backgrounding, since we defer attachment of the slave until 1452 * after the connection is fully established (in particular, 1453 * async rfwd replies have been received for ExitOnForwardFailure). 1454 */ 1455 if (options.control_persist && muxserver_sock != -1) { 1456 ostdin_null_flag = stdin_null_flag; 1457 ono_shell_flag = no_shell_flag; 1458 orequest_tty = options.request_tty; 1459 otty_flag = tty_flag; 1460 stdin_null_flag = 1; 1461 no_shell_flag = 1; 1462 tty_flag = 0; 1463 if (!fork_after_authentication_flag) 1464 need_controlpersist_detach = 1; 1465 fork_after_authentication_flag = 1; 1466 } 1467 1468 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN)) 1469 id = ssh_session2_open(); 1470 1471 /* If we don't expect to open a new session, then disallow it */ 1472 if (options.control_master == SSHCTL_MASTER_NO && 1473 (datafellows & SSH_NEW_OPENSSH)) { 1474 debug("Requesting no-more-sessions@openssh.com"); 1475 packet_start(SSH2_MSG_GLOBAL_REQUEST); 1476 packet_put_cstring("no-more-sessions@openssh.com"); 1477 packet_put_char(0); 1478 packet_send(); 1479 } 1480 1481 /* Execute a local command */ 1482 if (options.local_command != NULL && 1483 options.permit_local_command) 1484 ssh_local_cmd(options.local_command); 1485 1486 /* 1487 * If requested and we are not interested in replies to remote 1488 * forwarding requests, then let ssh continue in the background. 1489 */ 1490 if (fork_after_authentication_flag) { 1491 if (options.exit_on_forward_failure && 1492 options.num_remote_forwards > 0) { 1493 debug("deferring postauth fork until remote forward " 1494 "confirmation received"); 1495 } else 1496 fork_postauth(); 1497 } 1498 1499 if (options.use_roaming) 1500 request_roaming(); 1501 1502 return client_loop(tty_flag, tty_flag ? 1503 options.escape_char : SSH_ESCAPECHAR_NONE, id); 1504 } 1505 1506 static void 1507 load_public_identity_files(void) 1508 { 1509 char *filename, *cp, thishost[NI_MAXHOST]; 1510 char *pwdir = NULL, *pwname = NULL; 1511 int i = 0; 1512 Key *public; 1513 struct passwd *pw; 1514 u_int n_ids; 1515 char *identity_files[SSH_MAX_IDENTITY_FILES]; 1516 Key *identity_keys[SSH_MAX_IDENTITY_FILES]; 1517 #ifdef ENABLE_PKCS11 1518 Key **keys; 1519 int nkeys; 1520 #endif /* PKCS11 */ 1521 1522 n_ids = 0; 1523 bzero(identity_files, sizeof(identity_files)); 1524 bzero(identity_keys, sizeof(identity_keys)); 1525 1526 #ifdef ENABLE_PKCS11 1527 if (options.pkcs11_provider != NULL && 1528 options.num_identity_files < SSH_MAX_IDENTITY_FILES && 1529 (pkcs11_init(!options.batch_mode) == 0) && 1530 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL, 1531 &keys)) > 0) { 1532 for (i = 0; i < nkeys; i++) { 1533 if (n_ids >= SSH_MAX_IDENTITY_FILES) { 1534 key_free(keys[i]); 1535 continue; 1536 } 1537 identity_keys[n_ids] = keys[i]; 1538 identity_files[n_ids] = 1539 xstrdup(options.pkcs11_provider); /* XXX */ 1540 n_ids++; 1541 } 1542 xfree(keys); 1543 } 1544 #endif /* ENABLE_PKCS11 */ 1545 if ((pw = getpwuid(original_real_uid)) == NULL) 1546 fatal("load_public_identity_files: getpwuid failed"); 1547 pwname = xstrdup(pw->pw_name); 1548 pwdir = xstrdup(pw->pw_dir); 1549 if (gethostname(thishost, sizeof(thishost)) == -1) 1550 fatal("load_public_identity_files: gethostname: %s", 1551 strerror(errno)); 1552 for (i = 0; i < options.num_identity_files; i++) { 1553 if (n_ids >= SSH_MAX_IDENTITY_FILES) { 1554 xfree(options.identity_files[i]); 1555 continue; 1556 } 1557 cp = tilde_expand_filename(options.identity_files[i], 1558 original_real_uid); 1559 filename = percent_expand(cp, "d", pwdir, 1560 "u", pwname, "l", thishost, "h", host, 1561 "r", options.user, (char *)NULL); 1562 xfree(cp); 1563 public = key_load_public(filename, NULL); 1564 debug("identity file %s type %d", filename, 1565 public ? public->type : -1); 1566 xfree(options.identity_files[i]); 1567 identity_files[n_ids] = filename; 1568 identity_keys[n_ids] = public; 1569 1570 if (++n_ids >= SSH_MAX_IDENTITY_FILES) 1571 continue; 1572 1573 /* Try to add the certificate variant too */ 1574 xasprintf(&cp, "%s-cert", filename); 1575 public = key_load_public(cp, NULL); 1576 debug("identity file %s type %d", cp, 1577 public ? public->type : -1); 1578 if (public == NULL) { 1579 xfree(cp); 1580 continue; 1581 } 1582 if (!key_is_cert(public)) { 1583 debug("%s: key %s type %s is not a certificate", 1584 __func__, cp, key_type(public)); 1585 key_free(public); 1586 xfree(cp); 1587 continue; 1588 } 1589 identity_keys[n_ids] = public; 1590 /* point to the original path, most likely the private key */ 1591 identity_files[n_ids] = xstrdup(filename); 1592 n_ids++; 1593 } 1594 options.num_identity_files = n_ids; 1595 memcpy(options.identity_files, identity_files, sizeof(identity_files)); 1596 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys)); 1597 1598 bzero(pwname, strlen(pwname)); 1599 xfree(pwname); 1600 bzero(pwdir, strlen(pwdir)); 1601 xfree(pwdir); 1602 } 1603 1604 static void 1605 main_sigchld_handler(int sig) 1606 { 1607 int save_errno = errno; 1608 pid_t pid; 1609 int status; 1610 1611 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 1612 (pid < 0 && errno == EINTR)) 1613 ; 1614 1615 signal(sig, main_sigchld_handler); 1616 errno = save_errno; 1617 } 1618 1619