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