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