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