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