1 /* $OpenBSD: ssh.c,v 1.534 2020/07/31 04:19:37 dtucker 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 1338 if (options.request_tty == REQUEST_TTY_YES || 1339 options.request_tty == REQUEST_TTY_FORCE) 1340 tty_flag = 1; 1341 1342 /* Allocate a tty by default if no command specified. */ 1343 if (sshbuf_len(command) == 0 && options.remote_command == NULL) 1344 tty_flag = options.request_tty != REQUEST_TTY_NO; 1345 1346 /* Force no tty */ 1347 if (options.request_tty == REQUEST_TTY_NO || 1348 (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY)) 1349 tty_flag = 0; 1350 /* Do not allocate a tty if stdin is not a tty. */ 1351 if ((!isatty(fileno(stdin)) || stdin_null_flag) && 1352 options.request_tty != REQUEST_TTY_FORCE) { 1353 if (tty_flag) 1354 logit("Pseudo-terminal will not be allocated because " 1355 "stdin is not a terminal."); 1356 tty_flag = 0; 1357 } 1358 1359 /* Set up strings used to percent_expand() arguments */ 1360 if (gethostname(thishost, sizeof(thishost)) == -1) 1361 fatal("gethostname: %s", strerror(errno)); 1362 strlcpy(shorthost, thishost, sizeof(shorthost)); 1363 shorthost[strcspn(thishost, ".")] = '\0'; 1364 snprintf(portstr, sizeof(portstr), "%d", options.port); 1365 snprintf(uidstr, sizeof(uidstr), "%llu", 1366 (unsigned long long)pw->pw_uid); 1367 keyalias = options.host_key_alias ? options.host_key_alias : host_arg; 1368 1369 conn_hash_hex = ssh_connection_hash(thishost, host, portstr, 1370 options.user); 1371 1372 /* 1373 * Expand tokens in arguments. NB. LocalCommand is expanded later, 1374 * after port-forwarding is set up, so it may pick up any local 1375 * tunnel interface name allocated. 1376 */ 1377 if (options.remote_command != NULL) { 1378 debug3("expanding RemoteCommand: %s", options.remote_command); 1379 cp = options.remote_command; 1380 options.remote_command = default_client_percent_expand(cp, 1381 pw->pw_dir, host, options.user, pw->pw_name); 1382 debug3("expanded RemoteCommand: %s", options.remote_command); 1383 free(cp); 1384 if ((r = sshbuf_put(command, options.remote_command, 1385 strlen(options.remote_command))) != 0) 1386 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 1387 } 1388 1389 if (options.control_path != NULL) { 1390 cp = tilde_expand_filename(options.control_path, getuid()); 1391 free(options.control_path); 1392 options.control_path = default_client_percent_dollar_expand(cp, 1393 pw->pw_dir, host, options.user, pw->pw_name); 1394 free(cp); 1395 } 1396 1397 if (options.identity_agent != NULL) { 1398 p = tilde_expand_filename(options.identity_agent, getuid()); 1399 cp = default_client_percent_dollar_expand(p, 1400 pw->pw_dir, host, options.user, pw->pw_name); 1401 free(p); 1402 free(options.identity_agent); 1403 options.identity_agent = cp; 1404 } 1405 1406 if (options.forward_agent_sock_path != NULL) { 1407 p = tilde_expand_filename(options.forward_agent_sock_path, 1408 getuid()); 1409 cp = default_client_percent_dollar_expand(p, 1410 pw->pw_dir, host, options.user, pw->pw_name); 1411 free(p); 1412 free(options.forward_agent_sock_path); 1413 options.forward_agent_sock_path = cp; 1414 } 1415 1416 for (j = 0; j < options.num_user_hostfiles; j++) { 1417 if (options.user_hostfiles[j] != NULL) { 1418 cp = tilde_expand_filename(options.user_hostfiles[j], 1419 getuid()); 1420 p = default_client_percent_dollar_expand(cp, 1421 pw->pw_dir, host, options.user, pw->pw_name); 1422 if (strcmp(options.user_hostfiles[j], p) != 0) 1423 debug3("expanded UserKnownHostsFile '%s' -> " 1424 "'%s'", options.user_hostfiles[j], p); 1425 free(options.user_hostfiles[j]); 1426 free(cp); 1427 options.user_hostfiles[j] = p; 1428 } 1429 } 1430 1431 for (i = 0; i < options.num_local_forwards; i++) { 1432 if (options.local_forwards[i].listen_path != NULL) { 1433 cp = options.local_forwards[i].listen_path; 1434 p = options.local_forwards[i].listen_path = 1435 default_client_percent_expand(cp, 1436 pw->pw_dir, host, options.user, pw->pw_name); 1437 if (strcmp(cp, p) != 0) 1438 debug3("expanded LocalForward listen path " 1439 "'%s' -> '%s'", cp, p); 1440 free(cp); 1441 } 1442 if (options.local_forwards[i].connect_path != NULL) { 1443 cp = options.local_forwards[i].connect_path; 1444 p = options.local_forwards[i].connect_path = 1445 default_client_percent_expand(cp, 1446 pw->pw_dir, host, options.user, pw->pw_name); 1447 if (strcmp(cp, p) != 0) 1448 debug3("expanded LocalForward connect path " 1449 "'%s' -> '%s'", cp, p); 1450 free(cp); 1451 } 1452 } 1453 1454 for (i = 0; i < options.num_remote_forwards; i++) { 1455 if (options.remote_forwards[i].listen_path != NULL) { 1456 cp = options.remote_forwards[i].listen_path; 1457 p = options.remote_forwards[i].listen_path = 1458 default_client_percent_expand(cp, 1459 pw->pw_dir, host, options.user, pw->pw_name); 1460 if (strcmp(cp, p) != 0) 1461 debug3("expanded RemoteForward listen path " 1462 "'%s' -> '%s'", cp, p); 1463 free(cp); 1464 } 1465 if (options.remote_forwards[i].connect_path != NULL) { 1466 cp = options.remote_forwards[i].connect_path; 1467 p = options.remote_forwards[i].connect_path = 1468 default_client_percent_expand(cp, 1469 pw->pw_dir, host, options.user, pw->pw_name); 1470 if (strcmp(cp, p) != 0) 1471 debug3("expanded RemoteForward connect path " 1472 "'%s' -> '%s'", cp, p); 1473 free(cp); 1474 } 1475 } 1476 1477 if (config_test) { 1478 dump_client_config(&options, host); 1479 exit(0); 1480 } 1481 1482 /* Expand SecurityKeyProvider if it refers to an environment variable */ 1483 if (options.sk_provider != NULL && *options.sk_provider == '$' && 1484 strlen(options.sk_provider) > 1) { 1485 if ((cp = getenv(options.sk_provider + 1)) == NULL) { 1486 debug("Authenticator provider %s did not resolve; " 1487 "disabling", options.sk_provider); 1488 free(options.sk_provider); 1489 options.sk_provider = NULL; 1490 } else { 1491 debug2("resolved SecurityKeyProvider %s => %s", 1492 options.sk_provider, cp); 1493 free(options.sk_provider); 1494 options.sk_provider = xstrdup(cp); 1495 } 1496 } 1497 1498 if (muxclient_command != 0 && options.control_path == NULL) 1499 fatal("No ControlPath specified for \"-O\" command"); 1500 if (options.control_path != NULL) { 1501 int sock; 1502 if ((sock = muxclient(options.control_path)) >= 0) { 1503 ssh_packet_set_connection(ssh, sock, sock); 1504 ssh_packet_set_mux(ssh); 1505 goto skip_connect; 1506 } 1507 } 1508 1509 /* 1510 * If hostname canonicalisation was not enabled, then we may not 1511 * have yet resolved the hostname. Do so now. 1512 */ 1513 if (addrs == NULL && options.proxy_command == NULL) { 1514 debug2("resolving \"%s\" port %d", host, options.port); 1515 if ((addrs = resolve_host(host, options.port, 1, 1516 cname, sizeof(cname))) == NULL) 1517 cleanup_exit(255); /* resolve_host logs the error */ 1518 } 1519 1520 timeout_ms = options.connection_timeout * 1000; 1521 1522 /* Open a connection to the remote host. */ 1523 if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port, 1524 options.address_family, options.connection_attempts, 1525 &timeout_ms, options.tcp_keep_alive) != 0) 1526 exit(255); 1527 1528 if (addrs != NULL) 1529 freeaddrinfo(addrs); 1530 1531 ssh_packet_set_timeout(ssh, options.server_alive_interval, 1532 options.server_alive_count_max); 1533 1534 if (timeout_ms > 0) 1535 debug3("timeout: %d ms remain after connect", timeout_ms); 1536 1537 /* 1538 * If we successfully made the connection and we have hostbased auth 1539 * enabled, load the public keys so we can later use the ssh-keysign 1540 * helper to sign challenges. 1541 */ 1542 sensitive_data.nkeys = 0; 1543 sensitive_data.keys = NULL; 1544 if (options.hostbased_authentication) { 1545 sensitive_data.nkeys = 10; 1546 sensitive_data.keys = xcalloc(sensitive_data.nkeys, 1547 sizeof(struct sshkey)); 1548 1549 /* XXX check errors? */ 1550 #define L_PUBKEY(p,o) do { \ 1551 if ((o) >= sensitive_data.nkeys) \ 1552 fatal("%s pubkey out of array bounds", __func__); \ 1553 check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \ 1554 p, "pubkey"); \ 1555 } while (0) 1556 #define L_CERT(p,o) do { \ 1557 if ((o) >= sensitive_data.nkeys) \ 1558 fatal("%s cert out of array bounds", __func__); \ 1559 check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \ 1560 } while (0) 1561 1562 if (options.hostbased_authentication == 1) { 1563 L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0); 1564 L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1); 1565 L_CERT(_PATH_HOST_RSA_KEY_FILE, 2); 1566 L_CERT(_PATH_HOST_DSA_KEY_FILE, 3); 1567 L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4); 1568 L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5); 1569 L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6); 1570 L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7); 1571 L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8); 1572 L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9); 1573 } 1574 } 1575 1576 /* load options.identity_files */ 1577 load_public_identity_files(pw); 1578 1579 /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */ 1580 if (options.identity_agent && 1581 strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) { 1582 if (strcmp(options.identity_agent, "none") == 0) { 1583 unsetenv(SSH_AUTHSOCKET_ENV_NAME); 1584 } else { 1585 cp = options.identity_agent; 1586 /* legacy (limited) format */ 1587 if (cp[0] == '$' && cp[1] != '{') { 1588 if (!valid_env_name(cp + 1)) { 1589 fatal("Invalid IdentityAgent " 1590 "environment variable name %s", cp); 1591 } 1592 if ((p = getenv(cp + 1)) == NULL) 1593 unsetenv(SSH_AUTHSOCKET_ENV_NAME); 1594 else 1595 setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1); 1596 } else { 1597 /* identity_agent specifies a path directly */ 1598 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1); 1599 } 1600 } 1601 } 1602 1603 if (options.forward_agent && options.forward_agent_sock_path != NULL) { 1604 cp = options.forward_agent_sock_path; 1605 if (cp[0] == '$') { 1606 if (!valid_env_name(cp + 1)) { 1607 fatal("Invalid ForwardAgent environment variable name %s", cp); 1608 } 1609 if ((p = getenv(cp + 1)) != NULL) 1610 forward_agent_sock_path = p; 1611 else 1612 options.forward_agent = 0; 1613 free(cp); 1614 } else { 1615 forward_agent_sock_path = cp; 1616 } 1617 } 1618 1619 /* Expand ~ in known host file names. */ 1620 tilde_expand_paths(options.system_hostfiles, 1621 options.num_system_hostfiles); 1622 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles); 1623 1624 ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */ 1625 ssh_signal(SIGCHLD, main_sigchld_handler); 1626 1627 /* Log into the remote system. Never returns if the login fails. */ 1628 ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr, 1629 options.port, pw, timeout_ms); 1630 1631 if (ssh_packet_connection_is_on_socket(ssh)) { 1632 verbose("Authenticated to %s ([%s]:%d).", host, 1633 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 1634 } else { 1635 verbose("Authenticated to %s (via proxy).", host); 1636 } 1637 1638 /* We no longer need the private host keys. Clear them now. */ 1639 if (sensitive_data.nkeys != 0) { 1640 for (i = 0; i < sensitive_data.nkeys; i++) { 1641 if (sensitive_data.keys[i] != NULL) { 1642 /* Destroys contents safely */ 1643 debug3("clear hostkey %d", i); 1644 sshkey_free(sensitive_data.keys[i]); 1645 sensitive_data.keys[i] = NULL; 1646 } 1647 } 1648 free(sensitive_data.keys); 1649 } 1650 for (i = 0; i < options.num_identity_files; i++) { 1651 free(options.identity_files[i]); 1652 options.identity_files[i] = NULL; 1653 if (options.identity_keys[i]) { 1654 sshkey_free(options.identity_keys[i]); 1655 options.identity_keys[i] = NULL; 1656 } 1657 } 1658 for (i = 0; i < options.num_certificate_files; i++) { 1659 free(options.certificate_files[i]); 1660 options.certificate_files[i] = NULL; 1661 } 1662 1663 skip_connect: 1664 exit_status = ssh_session2(ssh, pw); 1665 ssh_packet_close(ssh); 1666 1667 if (options.control_path != NULL && muxserver_sock != -1) 1668 unlink(options.control_path); 1669 1670 /* Kill ProxyCommand if it is running. */ 1671 ssh_kill_proxy_command(); 1672 1673 return exit_status; 1674 } 1675 1676 static void 1677 control_persist_detach(void) 1678 { 1679 pid_t pid; 1680 int devnull, keep_stderr; 1681 1682 debug("%s: backgrounding master process", __func__); 1683 1684 /* 1685 * master (current process) into the background, and make the 1686 * foreground process a client of the backgrounded master. 1687 */ 1688 switch ((pid = fork())) { 1689 case -1: 1690 fatal("%s: fork: %s", __func__, strerror(errno)); 1691 case 0: 1692 /* Child: master process continues mainloop */ 1693 break; 1694 default: 1695 /* Parent: set up mux client to connect to backgrounded master */ 1696 debug2("%s: background process is %ld", __func__, (long)pid); 1697 stdin_null_flag = ostdin_null_flag; 1698 options.request_tty = orequest_tty; 1699 tty_flag = otty_flag; 1700 close(muxserver_sock); 1701 muxserver_sock = -1; 1702 options.control_master = SSHCTL_MASTER_NO; 1703 muxclient(options.control_path); 1704 /* muxclient() doesn't return on success. */ 1705 fatal("Failed to connect to new control master"); 1706 } 1707 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 1708 error("%s: open(\"/dev/null\"): %s", __func__, 1709 strerror(errno)); 1710 } else { 1711 keep_stderr = log_is_on_stderr() && debug_flag; 1712 if (dup2(devnull, STDIN_FILENO) == -1 || 1713 dup2(devnull, STDOUT_FILENO) == -1 || 1714 (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1)) 1715 error("%s: dup2: %s", __func__, strerror(errno)); 1716 if (devnull > STDERR_FILENO) 1717 close(devnull); 1718 } 1719 daemon(1, 1); 1720 setproctitle("%s [mux]", options.control_path); 1721 } 1722 1723 /* Do fork() after authentication. Used by "ssh -f" */ 1724 static void 1725 fork_postauth(void) 1726 { 1727 if (need_controlpersist_detach) 1728 control_persist_detach(); 1729 debug("forking to background"); 1730 fork_after_authentication_flag = 0; 1731 if (daemon(1, 1) == -1) 1732 fatal("daemon() failed: %.200s", strerror(errno)); 1733 } 1734 1735 static void 1736 forwarding_success(void) 1737 { 1738 if (forward_confirms_pending == -1) 1739 return; 1740 if (--forward_confirms_pending == 0) { 1741 debug("%s: all expected forwarding replies received", __func__); 1742 if (fork_after_authentication_flag) 1743 fork_postauth(); 1744 } else { 1745 debug2("%s: %d expected forwarding replies remaining", 1746 __func__, forward_confirms_pending); 1747 } 1748 } 1749 1750 /* Callback for remote forward global requests */ 1751 static void 1752 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt) 1753 { 1754 struct Forward *rfwd = (struct Forward *)ctxt; 1755 u_int port; 1756 int r; 1757 1758 /* XXX verbose() on failure? */ 1759 debug("remote forward %s for: listen %s%s%d, connect %s:%d", 1760 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure", 1761 rfwd->listen_path ? rfwd->listen_path : 1762 rfwd->listen_host ? rfwd->listen_host : "", 1763 (rfwd->listen_path || rfwd->listen_host) ? ":" : "", 1764 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path : 1765 rfwd->connect_host, rfwd->connect_port); 1766 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) { 1767 if (type == SSH2_MSG_REQUEST_SUCCESS) { 1768 if ((r = sshpkt_get_u32(ssh, &port)) != 0) 1769 fatal("%s: %s", __func__, ssh_err(r)); 1770 if (port > 65535) { 1771 error("Invalid allocated port %u for remote " 1772 "forward to %s:%d", port, 1773 rfwd->connect_host, rfwd->connect_port); 1774 /* Ensure failure processing runs below */ 1775 type = SSH2_MSG_REQUEST_FAILURE; 1776 channel_update_permission(ssh, 1777 rfwd->handle, -1); 1778 } else { 1779 rfwd->allocated_port = (int)port; 1780 logit("Allocated port %u for remote " 1781 "forward to %s:%d", 1782 rfwd->allocated_port, rfwd->connect_host, 1783 rfwd->connect_port); 1784 channel_update_permission(ssh, 1785 rfwd->handle, rfwd->allocated_port); 1786 } 1787 } else { 1788 channel_update_permission(ssh, rfwd->handle, -1); 1789 } 1790 } 1791 1792 if (type == SSH2_MSG_REQUEST_FAILURE) { 1793 if (options.exit_on_forward_failure) { 1794 if (rfwd->listen_path != NULL) 1795 fatal("Error: remote port forwarding failed " 1796 "for listen path %s", rfwd->listen_path); 1797 else 1798 fatal("Error: remote port forwarding failed " 1799 "for listen port %d", rfwd->listen_port); 1800 } else { 1801 if (rfwd->listen_path != NULL) 1802 logit("Warning: remote port forwarding failed " 1803 "for listen path %s", rfwd->listen_path); 1804 else 1805 logit("Warning: remote port forwarding failed " 1806 "for listen port %d", rfwd->listen_port); 1807 } 1808 } 1809 forwarding_success(); 1810 } 1811 1812 static void 1813 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg) 1814 { 1815 debug("stdio forwarding: done"); 1816 cleanup_exit(0); 1817 } 1818 1819 static void 1820 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg) 1821 { 1822 if (!success) 1823 fatal("stdio forwarding failed"); 1824 } 1825 1826 static void 1827 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg) 1828 { 1829 if (!success) { 1830 error("Tunnel forwarding failed"); 1831 if (options.exit_on_forward_failure) 1832 cleanup_exit(255); 1833 } 1834 1835 debug("%s: tunnel forward established, id=%d", __func__, id); 1836 forwarding_success(); 1837 } 1838 1839 static void 1840 ssh_init_stdio_forwarding(struct ssh *ssh) 1841 { 1842 Channel *c; 1843 int in, out; 1844 1845 if (options.stdio_forward_host == NULL) 1846 return; 1847 1848 debug3("%s: %s:%d", __func__, options.stdio_forward_host, 1849 options.stdio_forward_port); 1850 1851 if ((in = dup(STDIN_FILENO)) == -1 || 1852 (out = dup(STDOUT_FILENO)) == -1) 1853 fatal("channel_connect_stdio_fwd: dup() in/out failed"); 1854 if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host, 1855 options.stdio_forward_port, in, out)) == NULL) 1856 fatal("%s: channel_connect_stdio_fwd failed", __func__); 1857 channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0); 1858 channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL); 1859 } 1860 1861 static void 1862 ssh_init_forwarding(struct ssh *ssh, char **ifname) 1863 { 1864 int success = 0; 1865 int i; 1866 1867 if (options.exit_on_forward_failure) 1868 forward_confirms_pending = 0; /* track pending requests */ 1869 /* Initiate local TCP/IP port forwardings. */ 1870 for (i = 0; i < options.num_local_forwards; i++) { 1871 debug("Local connections to %.200s:%d forwarded to remote " 1872 "address %.200s:%d", 1873 (options.local_forwards[i].listen_path != NULL) ? 1874 options.local_forwards[i].listen_path : 1875 (options.local_forwards[i].listen_host == NULL) ? 1876 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") : 1877 options.local_forwards[i].listen_host, 1878 options.local_forwards[i].listen_port, 1879 (options.local_forwards[i].connect_path != NULL) ? 1880 options.local_forwards[i].connect_path : 1881 options.local_forwards[i].connect_host, 1882 options.local_forwards[i].connect_port); 1883 success += channel_setup_local_fwd_listener(ssh, 1884 &options.local_forwards[i], &options.fwd_opts); 1885 } 1886 if (i > 0 && success != i && options.exit_on_forward_failure) 1887 fatal("Could not request local forwarding."); 1888 if (i > 0 && success == 0) 1889 error("Could not request local forwarding."); 1890 1891 /* Initiate remote TCP/IP port forwardings. */ 1892 for (i = 0; i < options.num_remote_forwards; i++) { 1893 debug("Remote connections from %.200s:%d forwarded to " 1894 "local address %.200s:%d", 1895 (options.remote_forwards[i].listen_path != NULL) ? 1896 options.remote_forwards[i].listen_path : 1897 (options.remote_forwards[i].listen_host == NULL) ? 1898 "LOCALHOST" : options.remote_forwards[i].listen_host, 1899 options.remote_forwards[i].listen_port, 1900 (options.remote_forwards[i].connect_path != NULL) ? 1901 options.remote_forwards[i].connect_path : 1902 options.remote_forwards[i].connect_host, 1903 options.remote_forwards[i].connect_port); 1904 if ((options.remote_forwards[i].handle = 1905 channel_request_remote_forwarding(ssh, 1906 &options.remote_forwards[i])) >= 0) { 1907 client_register_global_confirm( 1908 ssh_confirm_remote_forward, 1909 &options.remote_forwards[i]); 1910 forward_confirms_pending++; 1911 } else if (options.exit_on_forward_failure) 1912 fatal("Could not request remote forwarding."); 1913 else 1914 logit("Warning: Could not request remote forwarding."); 1915 } 1916 1917 /* Initiate tunnel forwarding. */ 1918 if (options.tun_open != SSH_TUNMODE_NO) { 1919 if ((*ifname = client_request_tun_fwd(ssh, 1920 options.tun_open, options.tun_local, 1921 options.tun_remote, ssh_tun_confirm, NULL)) != NULL) 1922 forward_confirms_pending++; 1923 else if (options.exit_on_forward_failure) 1924 fatal("Could not request tunnel forwarding."); 1925 else 1926 error("Could not request tunnel forwarding."); 1927 } 1928 if (forward_confirms_pending > 0) { 1929 debug("%s: expecting replies for %d forwards", __func__, 1930 forward_confirms_pending); 1931 } 1932 } 1933 1934 static void 1935 check_agent_present(void) 1936 { 1937 int r; 1938 1939 if (options.forward_agent) { 1940 /* Clear agent forwarding if we don't have an agent. */ 1941 if ((r = ssh_get_authentication_socket(NULL)) != 0) { 1942 options.forward_agent = 0; 1943 if (r != SSH_ERR_AGENT_NOT_PRESENT) 1944 debug("ssh_get_authentication_socket: %s", 1945 ssh_err(r)); 1946 } 1947 } 1948 } 1949 1950 static void 1951 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg) 1952 { 1953 extern char **environ; 1954 const char *display; 1955 int r, interactive = tty_flag; 1956 char *proto = NULL, *data = NULL; 1957 1958 if (!success) 1959 return; /* No need for error message, channels code sens one */ 1960 1961 display = getenv("DISPLAY"); 1962 if (display == NULL && options.forward_x11) 1963 debug("X11 forwarding requested but DISPLAY not set"); 1964 if (options.forward_x11 && client_x11_get_proto(ssh, display, 1965 options.xauth_location, options.forward_x11_trusted, 1966 options.forward_x11_timeout, &proto, &data) == 0) { 1967 /* Request forwarding with authentication spoofing. */ 1968 debug("Requesting X11 forwarding with authentication " 1969 "spoofing."); 1970 x11_request_forwarding_with_spoofing(ssh, id, display, proto, 1971 data, 1); 1972 client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN); 1973 /* XXX exit_on_forward_failure */ 1974 interactive = 1; 1975 } 1976 1977 check_agent_present(); 1978 if (options.forward_agent) { 1979 debug("Requesting authentication agent forwarding."); 1980 channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0); 1981 if ((r = sshpkt_send(ssh)) != 0) 1982 fatal("%s: %s", __func__, ssh_err(r)); 1983 } 1984 1985 /* Tell the packet module whether this is an interactive session. */ 1986 ssh_packet_set_interactive(ssh, interactive, 1987 options.ip_qos_interactive, options.ip_qos_bulk); 1988 1989 client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"), 1990 NULL, fileno(stdin), command, environ); 1991 } 1992 1993 /* open new channel for a session */ 1994 static int 1995 ssh_session2_open(struct ssh *ssh) 1996 { 1997 Channel *c; 1998 int window, packetmax, in, out, err; 1999 2000 if (stdin_null_flag) { 2001 in = open(_PATH_DEVNULL, O_RDONLY); 2002 } else { 2003 in = dup(STDIN_FILENO); 2004 } 2005 out = dup(STDOUT_FILENO); 2006 err = dup(STDERR_FILENO); 2007 2008 if (in == -1 || out == -1 || err == -1) 2009 fatal("dup() in/out/err failed"); 2010 2011 /* enable nonblocking unless tty */ 2012 if (!isatty(in)) 2013 set_nonblock(in); 2014 if (!isatty(out)) 2015 set_nonblock(out); 2016 if (!isatty(err)) 2017 set_nonblock(err); 2018 2019 window = CHAN_SES_WINDOW_DEFAULT; 2020 packetmax = CHAN_SES_PACKET_DEFAULT; 2021 if (tty_flag) { 2022 window >>= 1; 2023 packetmax >>= 1; 2024 } 2025 c = channel_new(ssh, 2026 "session", SSH_CHANNEL_OPENING, in, out, err, 2027 window, packetmax, CHAN_EXTENDED_WRITE, 2028 "client-session", /*nonblock*/0); 2029 2030 debug3("%s: channel_new: %d", __func__, c->self); 2031 2032 channel_send_open(ssh, c->self); 2033 if (!no_shell_flag) 2034 channel_register_open_confirm(ssh, c->self, 2035 ssh_session2_setup, NULL); 2036 2037 return c->self; 2038 } 2039 2040 static int 2041 ssh_session2(struct ssh *ssh, struct passwd *pw) 2042 { 2043 int r, devnull, id = -1; 2044 char *cp, *tun_fwd_ifname = NULL; 2045 2046 /* XXX should be pre-session */ 2047 if (!options.control_persist) 2048 ssh_init_stdio_forwarding(ssh); 2049 2050 ssh_init_forwarding(ssh, &tun_fwd_ifname); 2051 2052 if (options.local_command != NULL) { 2053 debug3("expanding LocalCommand: %s", options.local_command); 2054 cp = options.local_command; 2055 options.local_command = percent_expand(cp, 2056 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS, 2057 "d", pw->pw_dir, 2058 "h", host, 2059 "r", options.user, 2060 "u", pw->pw_name, 2061 "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname, 2062 (char *)NULL); 2063 debug3("expanded LocalCommand: %s", options.local_command); 2064 free(cp); 2065 } 2066 2067 /* Start listening for multiplex clients */ 2068 if (!ssh_packet_get_mux(ssh)) 2069 muxserver_listen(ssh); 2070 2071 /* 2072 * If we are in control persist mode and have a working mux listen 2073 * socket, then prepare to background ourselves and have a foreground 2074 * client attach as a control client. 2075 * NB. we must save copies of the flags that we override for 2076 * the backgrounding, since we defer attachment of the client until 2077 * after the connection is fully established (in particular, 2078 * async rfwd replies have been received for ExitOnForwardFailure). 2079 */ 2080 if (options.control_persist && muxserver_sock != -1) { 2081 ostdin_null_flag = stdin_null_flag; 2082 ono_shell_flag = no_shell_flag; 2083 orequest_tty = options.request_tty; 2084 otty_flag = tty_flag; 2085 stdin_null_flag = 1; 2086 no_shell_flag = 1; 2087 tty_flag = 0; 2088 if (!fork_after_authentication_flag) 2089 need_controlpersist_detach = 1; 2090 fork_after_authentication_flag = 1; 2091 } 2092 /* 2093 * ControlPersist mux listen socket setup failed, attempt the 2094 * stdio forward setup that we skipped earlier. 2095 */ 2096 if (options.control_persist && muxserver_sock == -1) 2097 ssh_init_stdio_forwarding(ssh); 2098 2099 if (!no_shell_flag) 2100 id = ssh_session2_open(ssh); 2101 else { 2102 ssh_packet_set_interactive(ssh, 2103 options.control_master == SSHCTL_MASTER_NO, 2104 options.ip_qos_interactive, options.ip_qos_bulk); 2105 } 2106 2107 /* If we don't expect to open a new session, then disallow it */ 2108 if (options.control_master == SSHCTL_MASTER_NO && 2109 (datafellows & SSH_NEW_OPENSSH)) { 2110 debug("Requesting no-more-sessions@openssh.com"); 2111 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 2112 (r = sshpkt_put_cstring(ssh, 2113 "no-more-sessions@openssh.com")) != 0 || 2114 (r = sshpkt_put_u8(ssh, 0)) != 0 || 2115 (r = sshpkt_send(ssh)) != 0) 2116 fatal("%s: %s", __func__, ssh_err(r)); 2117 } 2118 2119 /* Execute a local command */ 2120 if (options.local_command != NULL && 2121 options.permit_local_command) 2122 ssh_local_cmd(options.local_command); 2123 2124 /* 2125 * stdout is now owned by the session channel; clobber it here 2126 * so future channel closes are propagated to the local fd. 2127 * NB. this can only happen after LocalCommand has completed, 2128 * as it may want to write to stdout. 2129 */ 2130 if (!need_controlpersist_detach) { 2131 if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1) 2132 error("%s: open %s: %s", __func__, 2133 _PATH_DEVNULL, strerror(errno)); 2134 if (dup2(devnull, STDOUT_FILENO) == -1) 2135 fatal("%s: dup2() stdout failed", __func__); 2136 if (devnull > STDERR_FILENO) 2137 close(devnull); 2138 } 2139 2140 /* 2141 * If requested and we are not interested in replies to remote 2142 * forwarding requests, then let ssh continue in the background. 2143 */ 2144 if (fork_after_authentication_flag) { 2145 if (options.exit_on_forward_failure && 2146 options.num_remote_forwards > 0) { 2147 debug("deferring postauth fork until remote forward " 2148 "confirmation received"); 2149 } else 2150 fork_postauth(); 2151 } 2152 2153 return client_loop(ssh, tty_flag, tty_flag ? 2154 options.escape_char : SSH_ESCAPECHAR_NONE, id); 2155 } 2156 2157 /* Loads all IdentityFile and CertificateFile keys */ 2158 static void 2159 load_public_identity_files(struct passwd *pw) 2160 { 2161 char *filename, *cp; 2162 struct sshkey *public; 2163 int i; 2164 u_int n_ids, n_certs; 2165 char *identity_files[SSH_MAX_IDENTITY_FILES]; 2166 struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES]; 2167 int identity_file_userprovided[SSH_MAX_IDENTITY_FILES]; 2168 char *certificate_files[SSH_MAX_CERTIFICATE_FILES]; 2169 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES]; 2170 int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES]; 2171 #ifdef ENABLE_PKCS11 2172 struct sshkey **keys = NULL; 2173 char **comments = NULL; 2174 int nkeys; 2175 #endif /* PKCS11 */ 2176 2177 n_ids = n_certs = 0; 2178 memset(identity_files, 0, sizeof(identity_files)); 2179 memset(identity_keys, 0, sizeof(identity_keys)); 2180 memset(identity_file_userprovided, 0, 2181 sizeof(identity_file_userprovided)); 2182 memset(certificate_files, 0, sizeof(certificate_files)); 2183 memset(certificates, 0, sizeof(certificates)); 2184 memset(certificate_file_userprovided, 0, 2185 sizeof(certificate_file_userprovided)); 2186 2187 #ifdef ENABLE_PKCS11 2188 if (options.pkcs11_provider != NULL && 2189 options.num_identity_files < SSH_MAX_IDENTITY_FILES && 2190 (pkcs11_init(!options.batch_mode) == 0) && 2191 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL, 2192 &keys, &comments)) > 0) { 2193 for (i = 0; i < nkeys; i++) { 2194 if (n_ids >= SSH_MAX_IDENTITY_FILES) { 2195 sshkey_free(keys[i]); 2196 free(comments[i]); 2197 continue; 2198 } 2199 identity_keys[n_ids] = keys[i]; 2200 identity_files[n_ids] = comments[i]; /* transferred */ 2201 n_ids++; 2202 } 2203 free(keys); 2204 free(comments); 2205 } 2206 #endif /* ENABLE_PKCS11 */ 2207 for (i = 0; i < options.num_identity_files; i++) { 2208 if (n_ids >= SSH_MAX_IDENTITY_FILES || 2209 strcasecmp(options.identity_files[i], "none") == 0) { 2210 free(options.identity_files[i]); 2211 options.identity_files[i] = NULL; 2212 continue; 2213 } 2214 cp = tilde_expand_filename(options.identity_files[i], getuid()); 2215 filename = default_client_percent_dollar_expand(cp, 2216 pw->pw_dir, host, options.user, pw->pw_name); 2217 free(cp); 2218 check_load(sshkey_load_public(filename, &public, NULL), 2219 filename, "pubkey"); 2220 debug("identity file %s type %d", filename, 2221 public ? public->type : -1); 2222 free(options.identity_files[i]); 2223 identity_files[n_ids] = filename; 2224 identity_keys[n_ids] = public; 2225 identity_file_userprovided[n_ids] = 2226 options.identity_file_userprovided[i]; 2227 if (++n_ids >= SSH_MAX_IDENTITY_FILES) 2228 continue; 2229 2230 /* 2231 * If no certificates have been explicitly listed then try 2232 * to add the default certificate variant too. 2233 */ 2234 if (options.num_certificate_files != 0) 2235 continue; 2236 xasprintf(&cp, "%s-cert", filename); 2237 check_load(sshkey_load_public(cp, &public, NULL), 2238 filename, "pubkey"); 2239 debug("identity file %s type %d", cp, 2240 public ? public->type : -1); 2241 if (public == NULL) { 2242 free(cp); 2243 continue; 2244 } 2245 if (!sshkey_is_cert(public)) { 2246 debug("%s: key %s type %s is not a certificate", 2247 __func__, cp, sshkey_type(public)); 2248 sshkey_free(public); 2249 free(cp); 2250 continue; 2251 } 2252 /* NB. leave filename pointing to private key */ 2253 identity_files[n_ids] = xstrdup(filename); 2254 identity_keys[n_ids] = public; 2255 identity_file_userprovided[n_ids] = 2256 options.identity_file_userprovided[i]; 2257 n_ids++; 2258 } 2259 2260 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES) 2261 fatal("%s: too many certificates", __func__); 2262 for (i = 0; i < options.num_certificate_files; i++) { 2263 cp = tilde_expand_filename(options.certificate_files[i], 2264 getuid()); 2265 filename = default_client_percent_dollar_expand(cp, 2266 pw->pw_dir, host, options.user, pw->pw_name); 2267 free(cp); 2268 2269 check_load(sshkey_load_public(filename, &public, NULL), 2270 filename, "certificate"); 2271 debug("certificate file %s type %d", filename, 2272 public ? public->type : -1); 2273 free(options.certificate_files[i]); 2274 options.certificate_files[i] = NULL; 2275 if (public == NULL) { 2276 free(filename); 2277 continue; 2278 } 2279 if (!sshkey_is_cert(public)) { 2280 debug("%s: key %s type %s is not a certificate", 2281 __func__, filename, sshkey_type(public)); 2282 sshkey_free(public); 2283 free(filename); 2284 continue; 2285 } 2286 certificate_files[n_certs] = filename; 2287 certificates[n_certs] = public; 2288 certificate_file_userprovided[n_certs] = 2289 options.certificate_file_userprovided[i]; 2290 ++n_certs; 2291 } 2292 2293 options.num_identity_files = n_ids; 2294 memcpy(options.identity_files, identity_files, sizeof(identity_files)); 2295 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys)); 2296 memcpy(options.identity_file_userprovided, 2297 identity_file_userprovided, sizeof(identity_file_userprovided)); 2298 2299 options.num_certificate_files = n_certs; 2300 memcpy(options.certificate_files, 2301 certificate_files, sizeof(certificate_files)); 2302 memcpy(options.certificates, certificates, sizeof(certificates)); 2303 memcpy(options.certificate_file_userprovided, 2304 certificate_file_userprovided, 2305 sizeof(certificate_file_userprovided)); 2306 } 2307 2308 static void 2309 main_sigchld_handler(int sig) 2310 { 2311 int save_errno = errno; 2312 pid_t pid; 2313 int status; 2314 2315 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 2316 (pid == -1 && errno == EINTR)) 2317 ; 2318 errno = save_errno; 2319 } 2320