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