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