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