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