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