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