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