1 /* $OpenBSD: ssh.c,v 1.401 2014/02/26 20:18:37 djm Exp $ */ 2 /* $FreeBSD$ */ 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("$FreeBSD$"); 46 47 #include <sys/types.h> 48 #ifdef HAVE_SYS_STAT_H 49 # include <sys/stat.h> 50 #endif 51 #include <sys/resource.h> 52 #include <sys/ioctl.h> 53 #include <sys/param.h> 54 #include <sys/socket.h> 55 #include <sys/wait.h> 56 57 #include <ctype.h> 58 #include <errno.h> 59 #include <fcntl.h> 60 #include <netdb.h> 61 #ifdef HAVE_PATHS_H 62 #include <paths.h> 63 #endif 64 #include <pwd.h> 65 #include <signal.h> 66 #include <stdarg.h> 67 #include <stddef.h> 68 #include <stdio.h> 69 #include <stdlib.h> 70 #include <string.h> 71 #include <unistd.h> 72 73 #include <netinet/in.h> 74 #include <arpa/inet.h> 75 76 #include <openssl/evp.h> 77 #include <openssl/err.h> 78 #include "openbsd-compat/openssl-compat.h" 79 #include "openbsd-compat/sys-queue.h" 80 81 #include "xmalloc.h" 82 #include "ssh.h" 83 #include "ssh1.h" 84 #include "ssh2.h" 85 #include "canohost.h" 86 #include "compat.h" 87 #include "cipher.h" 88 #include "packet.h" 89 #include "buffer.h" 90 #include "channels.h" 91 #include "key.h" 92 #include "authfd.h" 93 #include "authfile.h" 94 #include "pathnames.h" 95 #include "dispatch.h" 96 #include "clientloop.h" 97 #include "log.h" 98 #include "readconf.h" 99 #include "sshconnect.h" 100 #include "misc.h" 101 #include "kex.h" 102 #include "mac.h" 103 #include "sshpty.h" 104 #include "match.h" 105 #include "msg.h" 106 #include "uidswap.h" 107 #include "roaming.h" 108 #include "version.h" 109 110 #ifdef ENABLE_PKCS11 111 #include "ssh-pkcs11.h" 112 #endif 113 114 extern char *__progname; 115 116 /* Saves a copy of argv for setproctitle emulation */ 117 #ifndef HAVE_SETPROCTITLE 118 static char **saved_av; 119 #endif 120 121 /* Flag indicating whether debug mode is on. May be set on the command line. */ 122 int debug_flag = 0; 123 124 /* Flag indicating whether a tty should be requested */ 125 int tty_flag = 0; 126 127 /* don't exec a shell */ 128 int no_shell_flag = 0; 129 130 /* 131 * Flag indicating that nothing should be read from stdin. This can be set 132 * on the command line. 133 */ 134 int stdin_null_flag = 0; 135 136 /* 137 * Flag indicating that the current process should be backgrounded and 138 * a new slave launched in the foreground for ControlPersist. 139 */ 140 int need_controlpersist_detach = 0; 141 142 /* Copies of flags for ControlPersist foreground slave */ 143 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty; 144 145 /* 146 * Flag indicating that ssh should fork after authentication. This is useful 147 * so that the passphrase can be entered manually, and then ssh goes to the 148 * background. 149 */ 150 int fork_after_authentication_flag = 0; 151 152 /* forward stdio to remote host and port */ 153 char *stdio_forward_host = NULL; 154 int stdio_forward_port = 0; 155 156 /* 157 * General data structure for command line options and options configurable 158 * in configuration files. See readconf.h. 159 */ 160 Options options; 161 162 /* optional user configfile */ 163 char *config = NULL; 164 165 /* 166 * Name of the host we are connecting to. This is the name given on the 167 * command line, or the HostName specified for the user-supplied name in a 168 * configuration file. 169 */ 170 char *host; 171 172 /* socket address the host resolves to */ 173 struct sockaddr_storage hostaddr; 174 175 /* Private host keys. */ 176 Sensitive sensitive_data; 177 178 /* Original real UID. */ 179 uid_t original_real_uid; 180 uid_t original_effective_uid; 181 182 /* command to be executed */ 183 Buffer command; 184 185 /* Should we execute a command or invoke a subsystem? */ 186 int subsystem_flag = 0; 187 188 /* # of replies received for global requests */ 189 static int remote_forward_confirms_received = 0; 190 191 /* mux.c */ 192 extern int muxserver_sock; 193 extern u_int muxclient_command; 194 195 /* Prints a help message to the user. This function never returns. */ 196 197 static void 198 usage(void) 199 { 200 fprintf(stderr, 201 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n" 202 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n" 203 " [-F configfile] [-I pkcs11] [-i identity_file]\n" 204 " [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n" 205 " [-O ctl_cmd] [-o option] [-p port]\n" 206 " [-Q cipher | cipher-auth | mac | kex | key]\n" 207 " [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n" 208 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n" 209 ); 210 exit(255); 211 } 212 213 static int ssh_session(void); 214 static int ssh_session2(void); 215 static void load_public_identity_files(void); 216 static void main_sigchld_handler(int); 217 218 /* from muxclient.c */ 219 void muxclient(const char *); 220 void muxserver_listen(void); 221 222 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */ 223 static void 224 tilde_expand_paths(char **paths, u_int num_paths) 225 { 226 u_int i; 227 char *cp; 228 229 for (i = 0; i < num_paths; i++) { 230 cp = tilde_expand_filename(paths[i], original_real_uid); 231 free(paths[i]); 232 paths[i] = cp; 233 } 234 } 235 236 /* 237 * Attempt to resolve a host name / port to a set of addresses and 238 * optionally return any CNAMEs encountered along the way. 239 * Returns NULL on failure. 240 * NB. this function must operate with a options having undefined members. 241 */ 242 static struct addrinfo * 243 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen) 244 { 245 char strport[NI_MAXSERV]; 246 struct addrinfo hints, *res; 247 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1; 248 249 if (port <= 0) 250 port = default_ssh_port(); 251 252 snprintf(strport, sizeof strport, "%u", port); 253 memset(&hints, 0, sizeof(hints)); 254 hints.ai_family = options.address_family == -1 ? 255 AF_UNSPEC : options.address_family; 256 hints.ai_socktype = SOCK_STREAM; 257 if (cname != NULL) 258 hints.ai_flags = AI_CANONNAME; 259 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) { 260 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA)) 261 loglevel = SYSLOG_LEVEL_ERROR; 262 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s", 263 __progname, name, ssh_gai_strerror(gaierr)); 264 return NULL; 265 } 266 if (cname != NULL && res->ai_canonname != NULL) { 267 if (strlcpy(cname, res->ai_canonname, clen) >= clen) { 268 error("%s: host \"%s\" cname \"%s\" too long (max %lu)", 269 __func__, name, res->ai_canonname, (u_long)clen); 270 if (clen > 0) 271 *cname = '\0'; 272 } 273 } 274 return res; 275 } 276 277 /* 278 * Check whether the cname is a permitted replacement for the hostname 279 * and perform the replacement if it is. 280 * NB. this function must operate with a options having undefined members. 281 */ 282 static int 283 check_follow_cname(char **namep, const char *cname) 284 { 285 int i; 286 struct allowed_cname *rule; 287 288 if (*cname == '\0' || options.num_permitted_cnames == 0 || 289 strcmp(*namep, cname) == 0) 290 return 0; 291 if (options.canonicalize_hostname == SSH_CANONICALISE_NO) 292 return 0; 293 /* 294 * Don't attempt to canonicalize names that will be interpreted by 295 * a proxy unless the user specifically requests so. 296 */ 297 if (!option_clear_or_none(options.proxy_command) && 298 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS) 299 return 0; 300 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname); 301 for (i = 0; i < options.num_permitted_cnames; i++) { 302 rule = options.permitted_cnames + i; 303 if (match_pattern_list(*namep, rule->source_list, 304 strlen(rule->source_list), 1) != 1 || 305 match_pattern_list(cname, rule->target_list, 306 strlen(rule->target_list), 1) != 1) 307 continue; 308 verbose("Canonicalized DNS aliased hostname " 309 "\"%s\" => \"%s\"", *namep, cname); 310 free(*namep); 311 *namep = xstrdup(cname); 312 return 1; 313 } 314 return 0; 315 } 316 317 /* 318 * Attempt to resolve the supplied hostname after applying the user's 319 * canonicalization rules. Returns the address list for the host or NULL 320 * if no name was found after canonicalization. 321 * NB. this function must operate with a options having undefined members. 322 */ 323 static struct addrinfo * 324 resolve_canonicalize(char **hostp, int port) 325 { 326 int i, ndots; 327 char *cp, *fullhost, cname_target[NI_MAXHOST]; 328 struct addrinfo *addrs; 329 330 if (options.canonicalize_hostname == SSH_CANONICALISE_NO) 331 return NULL; 332 333 /* 334 * Don't attempt to canonicalize names that will be interpreted by 335 * a proxy unless the user specifically requests so. 336 */ 337 if (!option_clear_or_none(options.proxy_command) && 338 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS) 339 return NULL; 340 341 /* Don't apply canonicalization to sufficiently-qualified hostnames */ 342 ndots = 0; 343 for (cp = *hostp; *cp != '\0'; cp++) { 344 if (*cp == '.') 345 ndots++; 346 } 347 if (ndots > options.canonicalize_max_dots) { 348 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)", 349 __func__, *hostp, options.canonicalize_max_dots); 350 return NULL; 351 } 352 /* Attempt each supplied suffix */ 353 for (i = 0; i < options.num_canonical_domains; i++) { 354 *cname_target = '\0'; 355 xasprintf(&fullhost, "%s.%s.", *hostp, 356 options.canonical_domains[i]); 357 debug3("%s: attempting \"%s\" => \"%s\"", __func__, 358 *hostp, fullhost); 359 if ((addrs = resolve_host(fullhost, port, 0, 360 cname_target, sizeof(cname_target))) == NULL) { 361 free(fullhost); 362 continue; 363 } 364 /* Remove trailing '.' */ 365 fullhost[strlen(fullhost) - 1] = '\0'; 366 /* Follow CNAME if requested */ 367 if (!check_follow_cname(&fullhost, cname_target)) { 368 debug("Canonicalized hostname \"%s\" => \"%s\"", 369 *hostp, fullhost); 370 } 371 free(*hostp); 372 *hostp = fullhost; 373 return addrs; 374 } 375 if (!options.canonicalize_fallback_local) 376 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp); 377 debug2("%s: host %s not found in any suffix", __func__, *hostp); 378 return NULL; 379 } 380 381 /* 382 * Read per-user configuration file. Ignore the system wide config 383 * file if the user specifies a config file on the command line. 384 */ 385 static void 386 process_config_files(struct passwd *pw) 387 { 388 char buf[MAXPATHLEN]; 389 int r; 390 391 if (config != NULL) { 392 if (strcasecmp(config, "none") != 0 && 393 !read_config_file(config, pw, host, &options, 394 SSHCONF_USERCONF)) 395 fatal("Can't open user config file %.100s: " 396 "%.100s", config, strerror(errno)); 397 } else { 398 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir, 399 _PATH_SSH_USER_CONFFILE); 400 if (r > 0 && (size_t)r < sizeof(buf)) 401 (void)read_config_file(buf, pw, host, &options, 402 SSHCONF_CHECKPERM|SSHCONF_USERCONF); 403 404 /* Read systemwide configuration file after user config. */ 405 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host, 406 &options, 0); 407 } 408 } 409 410 /* 411 * Main program for the ssh client. 412 */ 413 int 414 main(int ac, char **av) 415 { 416 int i, r, opt, exit_status, use_syslog; 417 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile; 418 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV]; 419 char cname[NI_MAXHOST]; 420 struct stat st; 421 struct passwd *pw; 422 int timeout_ms; 423 extern int optind, optreset; 424 extern char *optarg; 425 Forward fwd; 426 struct addrinfo *addrs = NULL; 427 428 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 429 sanitise_stdfd(); 430 431 __progname = ssh_get_progname(av[0]); 432 433 #ifndef HAVE_SETPROCTITLE 434 /* Prepare for later setproctitle emulation */ 435 /* Save argv so it isn't clobbered by setproctitle() emulation */ 436 saved_av = xcalloc(ac + 1, sizeof(*saved_av)); 437 for (i = 0; i < ac; i++) 438 saved_av[i] = xstrdup(av[i]); 439 saved_av[i] = NULL; 440 compat_init_setproctitle(ac, av); 441 av = saved_av; 442 #endif 443 444 /* 445 * Discard other fds that are hanging around. These can cause problem 446 * with backgrounded ssh processes started by ControlPersist. 447 */ 448 closefrom(STDERR_FILENO + 1); 449 450 /* 451 * Save the original real uid. It will be needed later (uid-swapping 452 * may clobber the real uid). 453 */ 454 original_real_uid = getuid(); 455 original_effective_uid = geteuid(); 456 457 /* 458 * Use uid-swapping to give up root privileges for the duration of 459 * option processing. We will re-instantiate the rights when we are 460 * ready to create the privileged port, and will permanently drop 461 * them when the port has been created (actually, when the connection 462 * has been made, as we may need to create the port several times). 463 */ 464 PRIV_END; 465 466 #ifdef HAVE_SETRLIMIT 467 /* If we are installed setuid root be careful to not drop core. */ 468 if (original_real_uid != original_effective_uid) { 469 struct rlimit rlim; 470 rlim.rlim_cur = rlim.rlim_max = 0; 471 if (setrlimit(RLIMIT_CORE, &rlim) < 0) 472 fatal("setrlimit failed: %.100s", strerror(errno)); 473 } 474 #endif 475 /* Get user data. */ 476 pw = getpwuid(original_real_uid); 477 if (!pw) { 478 logit("No user exists for uid %lu", (u_long)original_real_uid); 479 exit(255); 480 } 481 /* Take a copy of the returned structure. */ 482 pw = pwcopy(pw); 483 484 /* 485 * Set our umask to something reasonable, as some files are created 486 * with the default umask. This will make them world-readable but 487 * writable only by the owner, which is ok for all files for which we 488 * don't set the modes explicitly. 489 */ 490 umask(022); 491 492 /* 493 * Initialize option structure to indicate that no values have been 494 * set. 495 */ 496 initialize_options(&options); 497 498 /* Parse command-line arguments. */ 499 host = NULL; 500 use_syslog = 0; 501 logfile = NULL; 502 argv0 = av[0]; 503 504 again: 505 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx" 506 "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) { 507 switch (opt) { 508 case '1': 509 options.protocol = SSH_PROTO_1; 510 break; 511 case '2': 512 options.protocol = SSH_PROTO_2; 513 break; 514 case '4': 515 options.address_family = AF_INET; 516 break; 517 case '6': 518 options.address_family = AF_INET6; 519 break; 520 case 'n': 521 stdin_null_flag = 1; 522 break; 523 case 'f': 524 fork_after_authentication_flag = 1; 525 stdin_null_flag = 1; 526 break; 527 case 'x': 528 options.forward_x11 = 0; 529 break; 530 case 'X': 531 options.forward_x11 = 1; 532 break; 533 case 'y': 534 use_syslog = 1; 535 break; 536 case 'E': 537 logfile = xstrdup(optarg); 538 break; 539 case 'Y': 540 options.forward_x11 = 1; 541 options.forward_x11_trusted = 1; 542 break; 543 case 'g': 544 options.gateway_ports = 1; 545 break; 546 case 'O': 547 if (stdio_forward_host != NULL) 548 fatal("Cannot specify multiplexing " 549 "command with -W"); 550 else if (muxclient_command != 0) 551 fatal("Multiplexing command already specified"); 552 if (strcmp(optarg, "check") == 0) 553 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK; 554 else if (strcmp(optarg, "forward") == 0) 555 muxclient_command = SSHMUX_COMMAND_FORWARD; 556 else if (strcmp(optarg, "exit") == 0) 557 muxclient_command = SSHMUX_COMMAND_TERMINATE; 558 else if (strcmp(optarg, "stop") == 0) 559 muxclient_command = SSHMUX_COMMAND_STOP; 560 else if (strcmp(optarg, "cancel") == 0) 561 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD; 562 else 563 fatal("Invalid multiplex command."); 564 break; 565 case 'P': /* deprecated */ 566 options.use_privileged_port = 0; 567 break; 568 case 'Q': 569 cp = NULL; 570 if (strcmp(optarg, "cipher") == 0) 571 cp = cipher_alg_list('\n', 0); 572 else if (strcmp(optarg, "cipher-auth") == 0) 573 cp = cipher_alg_list('\n', 1); 574 else if (strcmp(optarg, "mac") == 0) 575 cp = mac_alg_list('\n'); 576 else if (strcmp(optarg, "kex") == 0) 577 cp = kex_alg_list('\n'); 578 else if (strcmp(optarg, "key") == 0) 579 cp = key_alg_list(0, 0); 580 else if (strcmp(optarg, "key-cert") == 0) 581 cp = key_alg_list(1, 0); 582 else if (strcmp(optarg, "key-plain") == 0) 583 cp = key_alg_list(0, 1); 584 if (cp == NULL) 585 fatal("Unsupported query \"%s\"", optarg); 586 printf("%s\n", cp); 587 free(cp); 588 exit(0); 589 break; 590 case 'a': 591 options.forward_agent = 0; 592 break; 593 case 'A': 594 options.forward_agent = 1; 595 break; 596 case 'k': 597 options.gss_deleg_creds = 0; 598 break; 599 case 'K': 600 options.gss_authentication = 1; 601 options.gss_deleg_creds = 1; 602 break; 603 case 'i': 604 if (stat(optarg, &st) < 0) { 605 fprintf(stderr, "Warning: Identity file %s " 606 "not accessible: %s.\n", optarg, 607 strerror(errno)); 608 break; 609 } 610 add_identity_file(&options, NULL, optarg, 1); 611 break; 612 case 'I': 613 #ifdef ENABLE_PKCS11 614 options.pkcs11_provider = xstrdup(optarg); 615 #else 616 fprintf(stderr, "no support for PKCS#11.\n"); 617 #endif 618 break; 619 case 't': 620 if (options.request_tty == REQUEST_TTY_YES) 621 options.request_tty = REQUEST_TTY_FORCE; 622 else 623 options.request_tty = REQUEST_TTY_YES; 624 break; 625 case 'v': 626 if (debug_flag == 0) { 627 debug_flag = 1; 628 options.log_level = SYSLOG_LEVEL_DEBUG1; 629 } else { 630 if (options.log_level < SYSLOG_LEVEL_DEBUG3) 631 options.log_level++; 632 } 633 break; 634 case 'V': 635 if (options.version_addendum && 636 *options.version_addendum != '\0') 637 fprintf(stderr, "%s%s %s, %s\n", SSH_RELEASE, 638 options.hpn_disabled ? "" : SSH_VERSION_HPN, 639 options.version_addendum, 640 SSLeay_version(SSLEAY_VERSION)); 641 else 642 fprintf(stderr, "%s%s, %s\n", SSH_RELEASE, 643 options.hpn_disabled ? "" : SSH_VERSION_HPN, 644 SSLeay_version(SSLEAY_VERSION)); 645 if (opt == 'V') 646 exit(0); 647 break; 648 case 'w': 649 if (options.tun_open == -1) 650 options.tun_open = SSH_TUNMODE_DEFAULT; 651 options.tun_local = a2tun(optarg, &options.tun_remote); 652 if (options.tun_local == SSH_TUNID_ERR) { 653 fprintf(stderr, 654 "Bad tun device '%s'\n", optarg); 655 exit(255); 656 } 657 break; 658 case 'W': 659 if (stdio_forward_host != NULL) 660 fatal("stdio forward already specified"); 661 if (muxclient_command != 0) 662 fatal("Cannot specify stdio forward with -O"); 663 if (parse_forward(&fwd, optarg, 1, 0)) { 664 stdio_forward_host = fwd.listen_host; 665 stdio_forward_port = fwd.listen_port; 666 free(fwd.connect_host); 667 } else { 668 fprintf(stderr, 669 "Bad stdio forwarding specification '%s'\n", 670 optarg); 671 exit(255); 672 } 673 options.request_tty = REQUEST_TTY_NO; 674 no_shell_flag = 1; 675 options.clear_forwardings = 1; 676 options.exit_on_forward_failure = 1; 677 break; 678 case 'q': 679 options.log_level = SYSLOG_LEVEL_QUIET; 680 break; 681 case 'e': 682 if (optarg[0] == '^' && optarg[2] == 0 && 683 (u_char) optarg[1] >= 64 && 684 (u_char) optarg[1] < 128) 685 options.escape_char = (u_char) optarg[1] & 31; 686 else if (strlen(optarg) == 1) 687 options.escape_char = (u_char) optarg[0]; 688 else if (strcmp(optarg, "none") == 0) 689 options.escape_char = SSH_ESCAPECHAR_NONE; 690 else { 691 fprintf(stderr, "Bad escape character '%s'.\n", 692 optarg); 693 exit(255); 694 } 695 break; 696 case 'c': 697 if (ciphers_valid(optarg)) { 698 /* SSH2 only */ 699 options.ciphers = xstrdup(optarg); 700 options.cipher = SSH_CIPHER_INVALID; 701 } else { 702 /* SSH1 only */ 703 options.cipher = cipher_number(optarg); 704 if (options.cipher == -1) { 705 fprintf(stderr, 706 "Unknown cipher type '%s'\n", 707 optarg); 708 exit(255); 709 } 710 if (options.cipher == SSH_CIPHER_3DES) 711 options.ciphers = "3des-cbc"; 712 else if (options.cipher == SSH_CIPHER_BLOWFISH) 713 options.ciphers = "blowfish-cbc"; 714 else 715 options.ciphers = (char *)-1; 716 } 717 break; 718 case 'm': 719 if (mac_valid(optarg)) 720 options.macs = xstrdup(optarg); 721 else { 722 fprintf(stderr, "Unknown mac type '%s'\n", 723 optarg); 724 exit(255); 725 } 726 break; 727 case 'M': 728 if (options.control_master == SSHCTL_MASTER_YES) 729 options.control_master = SSHCTL_MASTER_ASK; 730 else 731 options.control_master = SSHCTL_MASTER_YES; 732 break; 733 case 'p': 734 options.port = a2port(optarg); 735 if (options.port <= 0) { 736 fprintf(stderr, "Bad port '%s'\n", optarg); 737 exit(255); 738 } 739 break; 740 case 'l': 741 options.user = optarg; 742 break; 743 744 case 'L': 745 if (parse_forward(&fwd, optarg, 0, 0)) 746 add_local_forward(&options, &fwd); 747 else { 748 fprintf(stderr, 749 "Bad local forwarding specification '%s'\n", 750 optarg); 751 exit(255); 752 } 753 break; 754 755 case 'R': 756 if (parse_forward(&fwd, optarg, 0, 1)) { 757 add_remote_forward(&options, &fwd); 758 } else { 759 fprintf(stderr, 760 "Bad remote forwarding specification " 761 "'%s'\n", optarg); 762 exit(255); 763 } 764 break; 765 766 case 'D': 767 if (parse_forward(&fwd, optarg, 1, 0)) { 768 add_local_forward(&options, &fwd); 769 } else { 770 fprintf(stderr, 771 "Bad dynamic forwarding specification " 772 "'%s'\n", optarg); 773 exit(255); 774 } 775 break; 776 777 case 'C': 778 options.compression = 1; 779 break; 780 case 'N': 781 no_shell_flag = 1; 782 options.request_tty = REQUEST_TTY_NO; 783 break; 784 case 'T': 785 options.request_tty = REQUEST_TTY_NO; 786 #ifdef NONE_CIPHER_ENABLED 787 /* 788 * Ensure that the user does not try to backdoor a 789 * NONE cipher switch on an interactive session by 790 * explicitly disabling it if the user asks for a 791 * session without a tty. 792 */ 793 options.none_switch = 0; 794 #endif 795 break; 796 case 'o': 797 line = xstrdup(optarg); 798 if (process_config_line(&options, pw, host ? host : "", 799 line, "command-line", 0, NULL, SSHCONF_USERCONF) 800 != 0) 801 exit(255); 802 free(line); 803 break; 804 case 's': 805 subsystem_flag = 1; 806 break; 807 case 'S': 808 if (options.control_path != NULL) 809 free(options.control_path); 810 options.control_path = xstrdup(optarg); 811 break; 812 case 'b': 813 options.bind_address = optarg; 814 break; 815 case 'F': 816 config = optarg; 817 break; 818 default: 819 usage(); 820 } 821 } 822 823 ac -= optind; 824 av += optind; 825 826 if (ac > 0 && !host) { 827 if (strrchr(*av, '@')) { 828 p = xstrdup(*av); 829 cp = strrchr(p, '@'); 830 if (cp == NULL || cp == p) 831 usage(); 832 options.user = p; 833 *cp = '\0'; 834 host = xstrdup(++cp); 835 } else 836 host = xstrdup(*av); 837 if (ac > 1) { 838 optind = optreset = 1; 839 goto again; 840 } 841 ac--, av++; 842 } 843 844 /* Check that we got a host name. */ 845 if (!host) 846 usage(); 847 848 host_arg = xstrdup(host); 849 850 OpenSSL_add_all_algorithms(); 851 ERR_load_crypto_strings(); 852 853 /* Initialize the command to execute on remote host. */ 854 buffer_init(&command); 855 856 /* 857 * Save the command to execute on the remote host in a buffer. There 858 * is no limit on the length of the command, except by the maximum 859 * packet size. Also sets the tty flag if there is no command. 860 */ 861 if (!ac) { 862 /* No command specified - execute shell on a tty. */ 863 if (subsystem_flag) { 864 fprintf(stderr, 865 "You must specify a subsystem to invoke.\n"); 866 usage(); 867 } 868 } else { 869 /* A command has been specified. Store it into the buffer. */ 870 for (i = 0; i < ac; i++) { 871 if (i) 872 buffer_append(&command, " ", 1); 873 buffer_append(&command, av[i], strlen(av[i])); 874 } 875 } 876 877 /* Cannot fork to background if no command. */ 878 if (fork_after_authentication_flag && buffer_len(&command) == 0 && 879 !no_shell_flag) 880 fatal("Cannot fork into background without a command " 881 "to execute."); 882 883 /* 884 * Initialize "log" output. Since we are the client all output 885 * goes to stderr unless otherwise specified by -y or -E. 886 */ 887 if (use_syslog && logfile != NULL) 888 fatal("Can't specify both -y and -E"); 889 if (logfile != NULL) { 890 log_redirect_stderr_to(logfile); 891 free(logfile); 892 } 893 log_init(argv0, 894 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level, 895 SYSLOG_FACILITY_USER, !use_syslog); 896 897 if (debug_flag) 898 logit("%s, %s", SSH_RELEASE, SSLeay_version(SSLEAY_VERSION)); 899 900 /* Parse the configuration files */ 901 process_config_files(pw); 902 903 /* Hostname canonicalisation needs a few options filled. */ 904 fill_default_options_for_canonicalization(&options); 905 906 /* If the user has replaced the hostname then take it into use now */ 907 if (options.hostname != NULL) { 908 /* NB. Please keep in sync with readconf.c:match_cfg_line() */ 909 cp = percent_expand(options.hostname, 910 "h", host, (char *)NULL); 911 free(host); 912 host = cp; 913 } 914 915 /* If canonicalization requested then try to apply it */ 916 lowercase(host); 917 if (options.canonicalize_hostname != SSH_CANONICALISE_NO) 918 addrs = resolve_canonicalize(&host, options.port); 919 920 /* 921 * If CanonicalizePermittedCNAMEs have been specified but 922 * other canonicalization did not happen (by not being requested 923 * or by failing with fallback) then the hostname may still be changed 924 * as a result of CNAME following. 925 * 926 * Try to resolve the bare hostname name using the system resolver's 927 * usual search rules and then apply the CNAME follow rules. 928 * 929 * Skip the lookup if a ProxyCommand is being used unless the user 930 * has specifically requested canonicalisation for this case via 931 * CanonicalizeHostname=always 932 */ 933 if (addrs == NULL && options.num_permitted_cnames != 0 && 934 (option_clear_or_none(options.proxy_command) || 935 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) { 936 if ((addrs = resolve_host(host, options.port, 1, 937 cname, sizeof(cname))) == NULL) 938 cleanup_exit(255); /* resolve_host logs the error */ 939 check_follow_cname(&host, cname); 940 } 941 942 /* 943 * If the target hostname has changed as a result of canonicalisation 944 * then re-parse the configuration files as new stanzas may match. 945 */ 946 if (strcasecmp(host_arg, host) != 0) { 947 debug("Hostname has changed; re-reading configuration"); 948 process_config_files(pw); 949 } 950 951 /* Fill configuration defaults. */ 952 fill_default_options(&options); 953 954 if (options.port == 0) 955 options.port = default_ssh_port(); 956 channel_set_af(options.address_family); 957 958 /* Tidy and check options */ 959 if (options.host_key_alias != NULL) 960 lowercase(options.host_key_alias); 961 if (options.proxy_command != NULL && 962 strcmp(options.proxy_command, "-") == 0 && 963 options.proxy_use_fdpass) 964 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible"); 965 #ifndef HAVE_CYGWIN 966 if (original_effective_uid != 0) 967 options.use_privileged_port = 0; 968 #endif 969 970 /* reinit */ 971 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog); 972 973 if (options.request_tty == REQUEST_TTY_YES || 974 options.request_tty == REQUEST_TTY_FORCE) 975 tty_flag = 1; 976 977 /* Allocate a tty by default if no command specified. */ 978 if (buffer_len(&command) == 0) 979 tty_flag = options.request_tty != REQUEST_TTY_NO; 980 981 /* Force no tty */ 982 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0) 983 tty_flag = 0; 984 /* Do not allocate a tty if stdin is not a tty. */ 985 if ((!isatty(fileno(stdin)) || stdin_null_flag) && 986 options.request_tty != REQUEST_TTY_FORCE) { 987 if (tty_flag) 988 logit("Pseudo-terminal will not be allocated because " 989 "stdin is not a terminal."); 990 tty_flag = 0; 991 } 992 993 seed_rng(); 994 995 if (options.user == NULL) 996 options.user = xstrdup(pw->pw_name); 997 998 if (gethostname(thishost, sizeof(thishost)) == -1) 999 fatal("gethostname: %s", strerror(errno)); 1000 strlcpy(shorthost, thishost, sizeof(shorthost)); 1001 shorthost[strcspn(thishost, ".")] = '\0'; 1002 snprintf(portstr, sizeof(portstr), "%d", options.port); 1003 1004 /* Find canonic host name. */ 1005 if (strchr(host, '.') == 0) { 1006 struct addrinfo hints; 1007 struct addrinfo *ai = NULL; 1008 int errgai; 1009 memset(&hints, 0, sizeof(hints)); 1010 hints.ai_family = options.address_family; 1011 hints.ai_flags = AI_CANONNAME; 1012 hints.ai_socktype = SOCK_STREAM; 1013 errgai = getaddrinfo(host, NULL, &hints, &ai); 1014 if (errgai == 0) { 1015 if (ai->ai_canonname != NULL) 1016 host = xstrdup(ai->ai_canonname); 1017 freeaddrinfo(ai); 1018 } 1019 } 1020 1021 if (options.local_command != NULL) { 1022 debug3("expanding LocalCommand: %s", options.local_command); 1023 cp = options.local_command; 1024 options.local_command = percent_expand(cp, "d", pw->pw_dir, 1025 "h", host, "l", thishost, "n", host_arg, "r", options.user, 1026 "p", portstr, "u", pw->pw_name, "L", shorthost, 1027 (char *)NULL); 1028 debug3("expanded LocalCommand: %s", options.local_command); 1029 free(cp); 1030 } 1031 1032 if (options.control_path != NULL) { 1033 cp = tilde_expand_filename(options.control_path, 1034 original_real_uid); 1035 free(options.control_path); 1036 options.control_path = percent_expand(cp, "h", host, 1037 "l", thishost, "n", host_arg, "r", options.user, 1038 "p", portstr, "u", pw->pw_name, "L", shorthost, 1039 (char *)NULL); 1040 free(cp); 1041 } 1042 if (muxclient_command != 0 && options.control_path == NULL) 1043 fatal("No ControlPath specified for \"-O\" command"); 1044 if (options.control_path != NULL) 1045 muxclient(options.control_path); 1046 1047 /* 1048 * If hostname canonicalisation was not enabled, then we may not 1049 * have yet resolved the hostname. Do so now. 1050 */ 1051 if (addrs == NULL && options.proxy_command == NULL) { 1052 if ((addrs = resolve_host(host, options.port, 1, 1053 cname, sizeof(cname))) == NULL) 1054 cleanup_exit(255); /* resolve_host logs the error */ 1055 } 1056 1057 timeout_ms = options.connection_timeout * 1000; 1058 1059 /* Open a connection to the remote host. */ 1060 if (ssh_connect(host, addrs, &hostaddr, options.port, 1061 options.address_family, options.connection_attempts, 1062 &timeout_ms, options.tcp_keep_alive, 1063 options.use_privileged_port) != 0) 1064 exit(255); 1065 1066 if (addrs != NULL) 1067 freeaddrinfo(addrs); 1068 1069 packet_set_timeout(options.server_alive_interval, 1070 options.server_alive_count_max); 1071 1072 if (timeout_ms > 0) 1073 debug3("timeout: %d ms remain after connect", timeout_ms); 1074 1075 /* 1076 * If we successfully made the connection, load the host private key 1077 * in case we will need it later for combined rsa-rhosts 1078 * authentication. This must be done before releasing extra 1079 * privileges, because the file is only readable by root. 1080 * If we cannot access the private keys, load the public keys 1081 * instead and try to execute the ssh-keysign helper instead. 1082 */ 1083 sensitive_data.nkeys = 0; 1084 sensitive_data.keys = NULL; 1085 sensitive_data.external_keysign = 0; 1086 if (options.rhosts_rsa_authentication || 1087 options.hostbased_authentication) { 1088 sensitive_data.nkeys = 9; 1089 sensitive_data.keys = xcalloc(sensitive_data.nkeys, 1090 sizeof(Key)); 1091 for (i = 0; i < sensitive_data.nkeys; i++) 1092 sensitive_data.keys[i] = NULL; 1093 1094 PRIV_START; 1095 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1, 1096 _PATH_HOST_KEY_FILE, "", NULL, NULL); 1097 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA, 1098 _PATH_HOST_DSA_KEY_FILE, "", NULL); 1099 #ifdef OPENSSL_HAS_ECC 1100 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA, 1101 _PATH_HOST_ECDSA_KEY_FILE, "", NULL); 1102 #endif 1103 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA, 1104 _PATH_HOST_RSA_KEY_FILE, "", NULL); 1105 sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519, 1106 _PATH_HOST_ED25519_KEY_FILE, "", NULL); 1107 sensitive_data.keys[5] = key_load_private_type(KEY_DSA, 1108 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL); 1109 #ifdef OPENSSL_HAS_ECC 1110 sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA, 1111 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL); 1112 #endif 1113 sensitive_data.keys[7] = key_load_private_type(KEY_RSA, 1114 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL); 1115 sensitive_data.keys[8] = key_load_private_type(KEY_ED25519, 1116 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL); 1117 PRIV_END; 1118 1119 if (options.hostbased_authentication == 1 && 1120 sensitive_data.keys[0] == NULL && 1121 sensitive_data.keys[5] == NULL && 1122 sensitive_data.keys[6] == NULL && 1123 sensitive_data.keys[7] == NULL && 1124 sensitive_data.keys[8] == NULL) { 1125 sensitive_data.keys[1] = key_load_cert( 1126 _PATH_HOST_DSA_KEY_FILE); 1127 #ifdef OPENSSL_HAS_ECC 1128 sensitive_data.keys[2] = key_load_cert( 1129 _PATH_HOST_ECDSA_KEY_FILE); 1130 #endif 1131 sensitive_data.keys[3] = key_load_cert( 1132 _PATH_HOST_RSA_KEY_FILE); 1133 sensitive_data.keys[4] = key_load_cert( 1134 _PATH_HOST_ED25519_KEY_FILE); 1135 sensitive_data.keys[5] = key_load_public( 1136 _PATH_HOST_DSA_KEY_FILE, NULL); 1137 #ifdef OPENSSL_HAS_ECC 1138 sensitive_data.keys[6] = key_load_public( 1139 _PATH_HOST_ECDSA_KEY_FILE, NULL); 1140 #endif 1141 sensitive_data.keys[7] = key_load_public( 1142 _PATH_HOST_RSA_KEY_FILE, NULL); 1143 sensitive_data.keys[8] = key_load_public( 1144 _PATH_HOST_ED25519_KEY_FILE, NULL); 1145 sensitive_data.external_keysign = 1; 1146 } 1147 } 1148 /* 1149 * Get rid of any extra privileges that we may have. We will no 1150 * longer need them. Also, extra privileges could make it very hard 1151 * to read identity files and other non-world-readable files from the 1152 * user's home directory if it happens to be on a NFS volume where 1153 * root is mapped to nobody. 1154 */ 1155 if (original_effective_uid == 0) { 1156 PRIV_START; 1157 permanently_set_uid(pw); 1158 } 1159 1160 /* 1161 * Now that we are back to our own permissions, create ~/.ssh 1162 * directory if it doesn't already exist. 1163 */ 1164 if (config == NULL) { 1165 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir, 1166 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR); 1167 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) { 1168 #ifdef WITH_SELINUX 1169 ssh_selinux_setfscreatecon(buf); 1170 #endif 1171 if (mkdir(buf, 0700) < 0) 1172 error("Could not create directory '%.200s'.", 1173 buf); 1174 #ifdef WITH_SELINUX 1175 ssh_selinux_setfscreatecon(NULL); 1176 #endif 1177 } 1178 } 1179 /* load options.identity_files */ 1180 load_public_identity_files(); 1181 1182 /* Expand ~ in known host file names. */ 1183 tilde_expand_paths(options.system_hostfiles, 1184 options.num_system_hostfiles); 1185 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles); 1186 1187 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */ 1188 signal(SIGCHLD, main_sigchld_handler); 1189 1190 /* Log into the remote system. Never returns if the login fails. */ 1191 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, 1192 options.port, pw, timeout_ms); 1193 1194 if (packet_connection_is_on_socket()) { 1195 verbose("Authenticated to %s ([%s]:%d).", host, 1196 get_remote_ipaddr(), get_remote_port()); 1197 } else { 1198 verbose("Authenticated to %s (via proxy).", host); 1199 } 1200 1201 /* We no longer need the private host keys. Clear them now. */ 1202 if (sensitive_data.nkeys != 0) { 1203 for (i = 0; i < sensitive_data.nkeys; i++) { 1204 if (sensitive_data.keys[i] != NULL) { 1205 /* Destroys contents safely */ 1206 debug3("clear hostkey %d", i); 1207 key_free(sensitive_data.keys[i]); 1208 sensitive_data.keys[i] = NULL; 1209 } 1210 } 1211 free(sensitive_data.keys); 1212 } 1213 for (i = 0; i < options.num_identity_files; i++) { 1214 free(options.identity_files[i]); 1215 options.identity_files[i] = NULL; 1216 if (options.identity_keys[i]) { 1217 key_free(options.identity_keys[i]); 1218 options.identity_keys[i] = NULL; 1219 } 1220 } 1221 1222 exit_status = compat20 ? ssh_session2() : ssh_session(); 1223 packet_close(); 1224 1225 if (options.control_path != NULL && muxserver_sock != -1) 1226 unlink(options.control_path); 1227 1228 /* Kill ProxyCommand if it is running. */ 1229 ssh_kill_proxy_command(); 1230 1231 return exit_status; 1232 } 1233 1234 static void 1235 control_persist_detach(void) 1236 { 1237 pid_t pid; 1238 int devnull; 1239 1240 debug("%s: backgrounding master process", __func__); 1241 1242 /* 1243 * master (current process) into the background, and make the 1244 * foreground process a client of the backgrounded master. 1245 */ 1246 switch ((pid = fork())) { 1247 case -1: 1248 fatal("%s: fork: %s", __func__, strerror(errno)); 1249 case 0: 1250 /* Child: master process continues mainloop */ 1251 break; 1252 default: 1253 /* Parent: set up mux slave to connect to backgrounded master */ 1254 debug2("%s: background process is %ld", __func__, (long)pid); 1255 stdin_null_flag = ostdin_null_flag; 1256 options.request_tty = orequest_tty; 1257 tty_flag = otty_flag; 1258 close(muxserver_sock); 1259 muxserver_sock = -1; 1260 options.control_master = SSHCTL_MASTER_NO; 1261 muxclient(options.control_path); 1262 /* muxclient() doesn't return on success. */ 1263 fatal("Failed to connect to new control master"); 1264 } 1265 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 1266 error("%s: open(\"/dev/null\"): %s", __func__, 1267 strerror(errno)); 1268 } else { 1269 if (dup2(devnull, STDIN_FILENO) == -1 || 1270 dup2(devnull, STDOUT_FILENO) == -1) 1271 error("%s: dup2: %s", __func__, strerror(errno)); 1272 if (devnull > STDERR_FILENO) 1273 close(devnull); 1274 } 1275 daemon(1, 1); 1276 setproctitle("%s [mux]", options.control_path); 1277 } 1278 1279 /* Do fork() after authentication. Used by "ssh -f" */ 1280 static void 1281 fork_postauth(void) 1282 { 1283 if (need_controlpersist_detach) 1284 control_persist_detach(); 1285 debug("forking to background"); 1286 fork_after_authentication_flag = 0; 1287 if (daemon(1, 1) < 0) 1288 fatal("daemon() failed: %.200s", strerror(errno)); 1289 } 1290 1291 /* Callback for remote forward global requests */ 1292 static void 1293 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt) 1294 { 1295 Forward *rfwd = (Forward *)ctxt; 1296 1297 /* XXX verbose() on failure? */ 1298 debug("remote forward %s for: listen %d, connect %s:%d", 1299 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure", 1300 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port); 1301 if (rfwd->listen_port == 0) { 1302 if (type == SSH2_MSG_REQUEST_SUCCESS) { 1303 rfwd->allocated_port = packet_get_int(); 1304 logit("Allocated port %u for remote forward to %s:%d", 1305 rfwd->allocated_port, 1306 rfwd->connect_host, rfwd->connect_port); 1307 channel_update_permitted_opens(rfwd->handle, 1308 rfwd->allocated_port); 1309 } else { 1310 channel_update_permitted_opens(rfwd->handle, -1); 1311 } 1312 } 1313 1314 if (type == SSH2_MSG_REQUEST_FAILURE) { 1315 if (options.exit_on_forward_failure) 1316 fatal("Error: remote port forwarding failed for " 1317 "listen port %d", rfwd->listen_port); 1318 else 1319 logit("Warning: remote port forwarding failed for " 1320 "listen port %d", rfwd->listen_port); 1321 } 1322 if (++remote_forward_confirms_received == options.num_remote_forwards) { 1323 debug("All remote forwarding requests processed"); 1324 if (fork_after_authentication_flag) 1325 fork_postauth(); 1326 } 1327 } 1328 1329 static void 1330 client_cleanup_stdio_fwd(int id, void *arg) 1331 { 1332 debug("stdio forwarding: done"); 1333 cleanup_exit(0); 1334 } 1335 1336 static void 1337 ssh_init_stdio_forwarding(void) 1338 { 1339 Channel *c; 1340 int in, out; 1341 1342 if (stdio_forward_host == NULL) 1343 return; 1344 if (!compat20) 1345 fatal("stdio forwarding require Protocol 2"); 1346 1347 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port); 1348 1349 if ((in = dup(STDIN_FILENO)) < 0 || 1350 (out = dup(STDOUT_FILENO)) < 0) 1351 fatal("channel_connect_stdio_fwd: dup() in/out failed"); 1352 if ((c = channel_connect_stdio_fwd(stdio_forward_host, 1353 stdio_forward_port, in, out)) == NULL) 1354 fatal("%s: channel_connect_stdio_fwd failed", __func__); 1355 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0); 1356 } 1357 1358 static void 1359 ssh_init_forwarding(void) 1360 { 1361 int success = 0; 1362 int i; 1363 1364 /* Initiate local TCP/IP port forwardings. */ 1365 for (i = 0; i < options.num_local_forwards; i++) { 1366 debug("Local connections to %.200s:%d forwarded to remote " 1367 "address %.200s:%d", 1368 (options.local_forwards[i].listen_host == NULL) ? 1369 (options.gateway_ports ? "*" : "LOCALHOST") : 1370 options.local_forwards[i].listen_host, 1371 options.local_forwards[i].listen_port, 1372 options.local_forwards[i].connect_host, 1373 options.local_forwards[i].connect_port); 1374 success += channel_setup_local_fwd_listener( 1375 options.local_forwards[i].listen_host, 1376 options.local_forwards[i].listen_port, 1377 options.local_forwards[i].connect_host, 1378 options.local_forwards[i].connect_port, 1379 options.gateway_ports); 1380 } 1381 if (i > 0 && success != i && options.exit_on_forward_failure) 1382 fatal("Could not request local forwarding."); 1383 if (i > 0 && success == 0) 1384 error("Could not request local forwarding."); 1385 1386 /* Initiate remote TCP/IP port forwardings. */ 1387 for (i = 0; i < options.num_remote_forwards; i++) { 1388 debug("Remote connections from %.200s:%d forwarded to " 1389 "local address %.200s:%d", 1390 (options.remote_forwards[i].listen_host == NULL) ? 1391 "LOCALHOST" : options.remote_forwards[i].listen_host, 1392 options.remote_forwards[i].listen_port, 1393 options.remote_forwards[i].connect_host, 1394 options.remote_forwards[i].connect_port); 1395 options.remote_forwards[i].handle = 1396 channel_request_remote_forwarding( 1397 options.remote_forwards[i].listen_host, 1398 options.remote_forwards[i].listen_port, 1399 options.remote_forwards[i].connect_host, 1400 options.remote_forwards[i].connect_port); 1401 if (options.remote_forwards[i].handle < 0) { 1402 if (options.exit_on_forward_failure) 1403 fatal("Could not request remote forwarding."); 1404 else 1405 logit("Warning: Could not request remote " 1406 "forwarding."); 1407 } else { 1408 client_register_global_confirm(ssh_confirm_remote_forward, 1409 &options.remote_forwards[i]); 1410 } 1411 } 1412 1413 /* Initiate tunnel forwarding. */ 1414 if (options.tun_open != SSH_TUNMODE_NO) { 1415 if (client_request_tun_fwd(options.tun_open, 1416 options.tun_local, options.tun_remote) == -1) { 1417 if (options.exit_on_forward_failure) 1418 fatal("Could not request tunnel forwarding."); 1419 else 1420 error("Could not request tunnel forwarding."); 1421 } 1422 } 1423 } 1424 1425 static void 1426 check_agent_present(void) 1427 { 1428 if (options.forward_agent) { 1429 /* Clear agent forwarding if we don't have an agent. */ 1430 if (!ssh_agent_present()) 1431 options.forward_agent = 0; 1432 } 1433 } 1434 1435 static int 1436 ssh_session(void) 1437 { 1438 int type; 1439 int interactive = 0; 1440 int have_tty = 0; 1441 struct winsize ws; 1442 char *cp; 1443 const char *display; 1444 1445 /* Enable compression if requested. */ 1446 if (options.compression) { 1447 debug("Requesting compression at level %d.", 1448 options.compression_level); 1449 1450 if (options.compression_level < 1 || 1451 options.compression_level > 9) 1452 fatal("Compression level must be from 1 (fast) to " 1453 "9 (slow, best)."); 1454 1455 /* Send the request. */ 1456 packet_start(SSH_CMSG_REQUEST_COMPRESSION); 1457 packet_put_int(options.compression_level); 1458 packet_send(); 1459 packet_write_wait(); 1460 type = packet_read(); 1461 if (type == SSH_SMSG_SUCCESS) 1462 packet_start_compression(options.compression_level); 1463 else if (type == SSH_SMSG_FAILURE) 1464 logit("Warning: Remote host refused compression."); 1465 else 1466 packet_disconnect("Protocol error waiting for " 1467 "compression response."); 1468 } 1469 /* Allocate a pseudo tty if appropriate. */ 1470 if (tty_flag) { 1471 debug("Requesting pty."); 1472 1473 /* Start the packet. */ 1474 packet_start(SSH_CMSG_REQUEST_PTY); 1475 1476 /* Store TERM in the packet. There is no limit on the 1477 length of the string. */ 1478 cp = getenv("TERM"); 1479 if (!cp) 1480 cp = ""; 1481 packet_put_cstring(cp); 1482 1483 /* Store window size in the packet. */ 1484 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0) 1485 memset(&ws, 0, sizeof(ws)); 1486 packet_put_int((u_int)ws.ws_row); 1487 packet_put_int((u_int)ws.ws_col); 1488 packet_put_int((u_int)ws.ws_xpixel); 1489 packet_put_int((u_int)ws.ws_ypixel); 1490 1491 /* Store tty modes in the packet. */ 1492 tty_make_modes(fileno(stdin), NULL); 1493 1494 /* Send the packet, and wait for it to leave. */ 1495 packet_send(); 1496 packet_write_wait(); 1497 1498 /* Read response from the server. */ 1499 type = packet_read(); 1500 if (type == SSH_SMSG_SUCCESS) { 1501 interactive = 1; 1502 have_tty = 1; 1503 } else if (type == SSH_SMSG_FAILURE) 1504 logit("Warning: Remote host failed or refused to " 1505 "allocate a pseudo tty."); 1506 else 1507 packet_disconnect("Protocol error waiting for pty " 1508 "request response."); 1509 } 1510 /* Request X11 forwarding if enabled and DISPLAY is set. */ 1511 display = getenv("DISPLAY"); 1512 if (options.forward_x11 && display != NULL) { 1513 char *proto, *data; 1514 /* Get reasonable local authentication information. */ 1515 client_x11_get_proto(display, options.xauth_location, 1516 options.forward_x11_trusted, 1517 options.forward_x11_timeout, 1518 &proto, &data); 1519 /* Request forwarding with authentication spoofing. */ 1520 debug("Requesting X11 forwarding with authentication " 1521 "spoofing."); 1522 x11_request_forwarding_with_spoofing(0, display, proto, 1523 data, 0); 1524 /* Read response from the server. */ 1525 type = packet_read(); 1526 if (type == SSH_SMSG_SUCCESS) { 1527 interactive = 1; 1528 } else if (type == SSH_SMSG_FAILURE) { 1529 logit("Warning: Remote host denied X11 forwarding."); 1530 } else { 1531 packet_disconnect("Protocol error waiting for X11 " 1532 "forwarding"); 1533 } 1534 } 1535 /* Tell the packet module whether this is an interactive session. */ 1536 packet_set_interactive(interactive, 1537 options.ip_qos_interactive, options.ip_qos_bulk); 1538 1539 /* Request authentication agent forwarding if appropriate. */ 1540 check_agent_present(); 1541 1542 if (options.forward_agent) { 1543 debug("Requesting authentication agent forwarding."); 1544 auth_request_forwarding(); 1545 1546 /* Read response from the server. */ 1547 type = packet_read(); 1548 packet_check_eom(); 1549 if (type != SSH_SMSG_SUCCESS) 1550 logit("Warning: Remote host denied authentication agent forwarding."); 1551 } 1552 1553 /* Initiate port forwardings. */ 1554 ssh_init_stdio_forwarding(); 1555 ssh_init_forwarding(); 1556 1557 /* Execute a local command */ 1558 if (options.local_command != NULL && 1559 options.permit_local_command) 1560 ssh_local_cmd(options.local_command); 1561 1562 /* 1563 * If requested and we are not interested in replies to remote 1564 * forwarding requests, then let ssh continue in the background. 1565 */ 1566 if (fork_after_authentication_flag) { 1567 if (options.exit_on_forward_failure && 1568 options.num_remote_forwards > 0) { 1569 debug("deferring postauth fork until remote forward " 1570 "confirmation received"); 1571 } else 1572 fork_postauth(); 1573 } 1574 1575 /* 1576 * If a command was specified on the command line, execute the 1577 * command now. Otherwise request the server to start a shell. 1578 */ 1579 if (buffer_len(&command) > 0) { 1580 int len = buffer_len(&command); 1581 if (len > 900) 1582 len = 900; 1583 debug("Sending command: %.*s", len, 1584 (u_char *)buffer_ptr(&command)); 1585 packet_start(SSH_CMSG_EXEC_CMD); 1586 packet_put_string(buffer_ptr(&command), buffer_len(&command)); 1587 packet_send(); 1588 packet_write_wait(); 1589 } else { 1590 debug("Requesting shell."); 1591 packet_start(SSH_CMSG_EXEC_SHELL); 1592 packet_send(); 1593 packet_write_wait(); 1594 } 1595 1596 /* Enter the interactive session. */ 1597 return client_loop(have_tty, tty_flag ? 1598 options.escape_char : SSH_ESCAPECHAR_NONE, 0); 1599 } 1600 1601 /* request pty/x11/agent/tcpfwd/shell for channel */ 1602 static void 1603 ssh_session2_setup(int id, int success, void *arg) 1604 { 1605 extern char **environ; 1606 const char *display; 1607 int interactive = tty_flag; 1608 1609 if (!success) 1610 return; /* No need for error message, channels code sens one */ 1611 1612 display = getenv("DISPLAY"); 1613 if (options.forward_x11 && display != NULL) { 1614 char *proto, *data; 1615 /* Get reasonable local authentication information. */ 1616 client_x11_get_proto(display, options.xauth_location, 1617 options.forward_x11_trusted, 1618 options.forward_x11_timeout, &proto, &data); 1619 /* Request forwarding with authentication spoofing. */ 1620 debug("Requesting X11 forwarding with authentication " 1621 "spoofing."); 1622 x11_request_forwarding_with_spoofing(id, display, proto, 1623 data, 1); 1624 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN); 1625 /* XXX exit_on_forward_failure */ 1626 interactive = 1; 1627 } 1628 1629 check_agent_present(); 1630 if (options.forward_agent) { 1631 debug("Requesting authentication agent forwarding."); 1632 channel_request_start(id, "auth-agent-req@openssh.com", 0); 1633 packet_send(); 1634 } 1635 1636 /* Tell the packet module whether this is an interactive session. */ 1637 packet_set_interactive(interactive, 1638 options.ip_qos_interactive, options.ip_qos_bulk); 1639 1640 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"), 1641 NULL, fileno(stdin), &command, environ); 1642 } 1643 1644 /* open new channel for a session */ 1645 static int 1646 ssh_session2_open(void) 1647 { 1648 Channel *c; 1649 int window, packetmax, in, out, err; 1650 1651 if (stdin_null_flag) { 1652 in = open(_PATH_DEVNULL, O_RDONLY); 1653 } else { 1654 in = dup(STDIN_FILENO); 1655 } 1656 out = dup(STDOUT_FILENO); 1657 err = dup(STDERR_FILENO); 1658 1659 if (in < 0 || out < 0 || err < 0) 1660 fatal("dup() in/out/err failed"); 1661 1662 /* enable nonblocking unless tty */ 1663 if (!isatty(in)) 1664 set_nonblock(in); 1665 if (!isatty(out)) 1666 set_nonblock(out); 1667 if (!isatty(err)) 1668 set_nonblock(err); 1669 1670 /* 1671 * We need to check to see what to do about buffer sizes here. 1672 * - In an HPN to non-HPN connection we want to limit the window size to 1673 * something reasonable in case the far side has the large window bug. 1674 * - In an HPN to HPN connection we want to use the max window size but 1675 * allow the user to override it. 1676 * - Lastly if HPN is disabled then use the ssh standard window size. 1677 * 1678 * We cannot just do a getsockopt() here and set the ssh window to that 1679 * as in case of autotuning of socket buffers the window would get stuck 1680 * at the initial buffer size, generally less than 96k. Therefore we 1681 * need to set the maximum ssh window size to the maximum HPN buffer 1682 * size unless the user has set TcpRcvBufPoll to no. In that case we 1683 * can just set the window to the minimum of HPN buffer size and TCP 1684 * receive buffer size. 1685 */ 1686 if (tty_flag) 1687 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT; 1688 else 1689 options.hpn_buffer_size = CHAN_HPN_MIN_WINDOW_DEFAULT; 1690 1691 if (datafellows & SSH_BUG_LARGEWINDOW) { 1692 debug("HPN to Non-HPN Connection"); 1693 } else if (options.tcp_rcv_buf_poll <= 0) { 1694 sock_get_rcvbuf(&options.hpn_buffer_size, 0); 1695 debug("HPNBufferSize set to TCP RWIN: %d", 1696 options.hpn_buffer_size); 1697 } else if (options.tcp_rcv_buf > 0) { 1698 sock_get_rcvbuf(&options.hpn_buffer_size, 1699 options.tcp_rcv_buf); 1700 debug("HPNBufferSize set to user TCPRcvBuf: %d", 1701 options.hpn_buffer_size); 1702 } 1703 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size); 1704 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size); 1705 window = options.hpn_buffer_size; 1706 1707 packetmax = CHAN_SES_PACKET_DEFAULT; 1708 if (tty_flag) { 1709 window = CHAN_SES_WINDOW_DEFAULT; 1710 window >>= 1; 1711 packetmax >>= 1; 1712 } 1713 c = channel_new( 1714 "session", SSH_CHANNEL_OPENING, in, out, err, 1715 window, packetmax, CHAN_EXTENDED_WRITE, 1716 "client-session", /*nonblock*/0); 1717 if (!options.hpn_disabled && options.tcp_rcv_buf_poll > 0) { 1718 c->dynamic_window = 1; 1719 debug("Enabled Dynamic Window Scaling\n"); 1720 } 1721 1722 debug3("ssh_session2_open: channel_new: %d", c->self); 1723 1724 channel_send_open(c->self); 1725 if (!no_shell_flag) 1726 channel_register_open_confirm(c->self, 1727 ssh_session2_setup, NULL); 1728 1729 return c->self; 1730 } 1731 1732 static int 1733 ssh_session2(void) 1734 { 1735 int id = -1; 1736 1737 /* XXX should be pre-session */ 1738 if (!options.control_persist) 1739 ssh_init_stdio_forwarding(); 1740 ssh_init_forwarding(); 1741 1742 /* Start listening for multiplex clients */ 1743 muxserver_listen(); 1744 1745 /* 1746 * If we are in control persist mode and have a working mux listen 1747 * socket, then prepare to background ourselves and have a foreground 1748 * client attach as a control slave. 1749 * NB. we must save copies of the flags that we override for 1750 * the backgrounding, since we defer attachment of the slave until 1751 * after the connection is fully established (in particular, 1752 * async rfwd replies have been received for ExitOnForwardFailure). 1753 */ 1754 if (options.control_persist && muxserver_sock != -1) { 1755 ostdin_null_flag = stdin_null_flag; 1756 ono_shell_flag = no_shell_flag; 1757 orequest_tty = options.request_tty; 1758 otty_flag = tty_flag; 1759 stdin_null_flag = 1; 1760 no_shell_flag = 1; 1761 tty_flag = 0; 1762 if (!fork_after_authentication_flag) 1763 need_controlpersist_detach = 1; 1764 fork_after_authentication_flag = 1; 1765 } 1766 /* 1767 * ControlPersist mux listen socket setup failed, attempt the 1768 * stdio forward setup that we skipped earlier. 1769 */ 1770 if (options.control_persist && muxserver_sock == -1) 1771 ssh_init_stdio_forwarding(); 1772 1773 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN)) 1774 id = ssh_session2_open(); 1775 else { 1776 packet_set_interactive( 1777 options.control_master == SSHCTL_MASTER_NO, 1778 options.ip_qos_interactive, options.ip_qos_bulk); 1779 } 1780 1781 /* If we don't expect to open a new session, then disallow it */ 1782 if (options.control_master == SSHCTL_MASTER_NO && 1783 (datafellows & SSH_NEW_OPENSSH)) { 1784 debug("Requesting no-more-sessions@openssh.com"); 1785 packet_start(SSH2_MSG_GLOBAL_REQUEST); 1786 packet_put_cstring("no-more-sessions@openssh.com"); 1787 packet_put_char(0); 1788 packet_send(); 1789 } 1790 1791 /* Execute a local command */ 1792 if (options.local_command != NULL && 1793 options.permit_local_command) 1794 ssh_local_cmd(options.local_command); 1795 1796 /* 1797 * If requested and we are not interested in replies to remote 1798 * forwarding requests, then let ssh continue in the background. 1799 */ 1800 if (fork_after_authentication_flag) { 1801 if (options.exit_on_forward_failure && 1802 options.num_remote_forwards > 0) { 1803 debug("deferring postauth fork until remote forward " 1804 "confirmation received"); 1805 } else 1806 fork_postauth(); 1807 } 1808 1809 if (options.use_roaming) 1810 request_roaming(); 1811 1812 return client_loop(tty_flag, tty_flag ? 1813 options.escape_char : SSH_ESCAPECHAR_NONE, id); 1814 } 1815 1816 static void 1817 load_public_identity_files(void) 1818 { 1819 char *filename, *cp, thishost[NI_MAXHOST]; 1820 char *pwdir = NULL, *pwname = NULL; 1821 int i = 0; 1822 Key *public; 1823 struct passwd *pw; 1824 u_int n_ids; 1825 char *identity_files[SSH_MAX_IDENTITY_FILES]; 1826 Key *identity_keys[SSH_MAX_IDENTITY_FILES]; 1827 #ifdef ENABLE_PKCS11 1828 Key **keys; 1829 int nkeys; 1830 #endif /* PKCS11 */ 1831 1832 n_ids = 0; 1833 memset(identity_files, 0, sizeof(identity_files)); 1834 memset(identity_keys, 0, sizeof(identity_keys)); 1835 1836 #ifdef ENABLE_PKCS11 1837 if (options.pkcs11_provider != NULL && 1838 options.num_identity_files < SSH_MAX_IDENTITY_FILES && 1839 (pkcs11_init(!options.batch_mode) == 0) && 1840 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL, 1841 &keys)) > 0) { 1842 for (i = 0; i < nkeys; i++) { 1843 if (n_ids >= SSH_MAX_IDENTITY_FILES) { 1844 key_free(keys[i]); 1845 continue; 1846 } 1847 identity_keys[n_ids] = keys[i]; 1848 identity_files[n_ids] = 1849 xstrdup(options.pkcs11_provider); /* XXX */ 1850 n_ids++; 1851 } 1852 free(keys); 1853 } 1854 #endif /* ENABLE_PKCS11 */ 1855 if ((pw = getpwuid(original_real_uid)) == NULL) 1856 fatal("load_public_identity_files: getpwuid failed"); 1857 pwname = xstrdup(pw->pw_name); 1858 pwdir = xstrdup(pw->pw_dir); 1859 if (gethostname(thishost, sizeof(thishost)) == -1) 1860 fatal("load_public_identity_files: gethostname: %s", 1861 strerror(errno)); 1862 for (i = 0; i < options.num_identity_files; i++) { 1863 if (n_ids >= SSH_MAX_IDENTITY_FILES || 1864 strcasecmp(options.identity_files[i], "none") == 0) { 1865 free(options.identity_files[i]); 1866 continue; 1867 } 1868 cp = tilde_expand_filename(options.identity_files[i], 1869 original_real_uid); 1870 filename = percent_expand(cp, "d", pwdir, 1871 "u", pwname, "l", thishost, "h", host, 1872 "r", options.user, (char *)NULL); 1873 free(cp); 1874 public = key_load_public(filename, NULL); 1875 debug("identity file %s type %d", filename, 1876 public ? public->type : -1); 1877 free(options.identity_files[i]); 1878 identity_files[n_ids] = filename; 1879 identity_keys[n_ids] = public; 1880 1881 if (++n_ids >= SSH_MAX_IDENTITY_FILES) 1882 continue; 1883 1884 /* Try to add the certificate variant too */ 1885 xasprintf(&cp, "%s-cert", filename); 1886 public = key_load_public(cp, NULL); 1887 debug("identity file %s type %d", cp, 1888 public ? public->type : -1); 1889 if (public == NULL) { 1890 free(cp); 1891 continue; 1892 } 1893 if (!key_is_cert(public)) { 1894 debug("%s: key %s type %s is not a certificate", 1895 __func__, cp, key_type(public)); 1896 key_free(public); 1897 free(cp); 1898 continue; 1899 } 1900 identity_keys[n_ids] = public; 1901 /* point to the original path, most likely the private key */ 1902 identity_files[n_ids] = xstrdup(filename); 1903 n_ids++; 1904 } 1905 options.num_identity_files = n_ids; 1906 memcpy(options.identity_files, identity_files, sizeof(identity_files)); 1907 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys)); 1908 1909 explicit_bzero(pwname, strlen(pwname)); 1910 free(pwname); 1911 explicit_bzero(pwdir, strlen(pwdir)); 1912 free(pwdir); 1913 } 1914 1915 static void 1916 main_sigchld_handler(int sig) 1917 { 1918 int save_errno = errno; 1919 pid_t pid; 1920 int status; 1921 1922 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 1923 (pid < 0 && errno == EINTR)) 1924 ; 1925 1926 signal(sig, main_sigchld_handler); 1927 errno = save_errno; 1928 } 1929