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