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