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