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