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