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