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