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