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