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