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