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