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