1 /* $OpenBSD: ssh.c,v 1.540 2020/10/18 11:32:02 djm Exp $ */ 2 /* 3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 5 * All rights reserved 6 * Ssh client program. This program can be used to log into a remote machine. 7 * The software supports strong authentication, encryption, and forwarding 8 * of X11, TCP/IP, and authentication connections. 9 * 10 * As far as I am concerned, the code I have written for this software 11 * can be used freely for any purpose. Any derived versions of this 12 * software must be clearly marked as such, and if the derived work is 13 * incompatible with the protocol description in the RFC file, it must be 14 * called by a name other than "ssh" or "Secure Shell". 15 * 16 * Copyright (c) 1999 Niels Provos. All rights reserved. 17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved. 18 * 19 * Modified to work with SSLeay by Niels Provos <provos@citi.umich.edu> 20 * in Canada (German citizen). 21 * 22 * Redistribution and use in source and binary forms, with or without 23 * modification, are permitted provided that the following conditions 24 * are met: 25 * 1. Redistributions of source code must retain the above copyright 26 * notice, this list of conditions and the following disclaimer. 27 * 2. Redistributions in binary form must reproduce the above copyright 28 * notice, this list of conditions and the following disclaimer in the 29 * documentation and/or other materials provided with the distribution. 30 * 31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 41 */ 42 43 #include <sys/types.h> 44 #include <sys/ioctl.h> 45 #include <sys/queue.h> 46 #include <sys/resource.h> 47 #include <sys/socket.h> 48 #include <sys/stat.h> 49 #include <sys/time.h> 50 #include <sys/wait.h> 51 52 #include <ctype.h> 53 #include <errno.h> 54 #include <fcntl.h> 55 #include <netdb.h> 56 #include <paths.h> 57 #include <pwd.h> 58 #include <signal.h> 59 #include <stddef.h> 60 #include <stdio.h> 61 #include <stdlib.h> 62 #include <string.h> 63 #include <stdarg.h> 64 #include <unistd.h> 65 #include <limits.h> 66 #include <locale.h> 67 68 #ifdef WITH_OPENSSL 69 #include <openssl/evp.h> 70 #include <openssl/err.h> 71 #endif 72 73 #include "xmalloc.h" 74 #include "ssh.h" 75 #include "ssh2.h" 76 #include "canohost.h" 77 #include "compat.h" 78 #include "cipher.h" 79 #include "packet.h" 80 #include "sshbuf.h" 81 #include "channels.h" 82 #include "sshkey.h" 83 #include "authfd.h" 84 #include "authfile.h" 85 #include "pathnames.h" 86 #include "dispatch.h" 87 #include "clientloop.h" 88 #include "log.h" 89 #include "misc.h" 90 #include "readconf.h" 91 #include "sshconnect.h" 92 #include "kex.h" 93 #include "mac.h" 94 #include "sshpty.h" 95 #include "match.h" 96 #include "msg.h" 97 #include "version.h" 98 #include "ssherr.h" 99 #include "myproposal.h" 100 101 #ifdef ENABLE_PKCS11 102 #include "ssh-pkcs11.h" 103 #endif 104 105 extern char *__progname; 106 107 /* Flag indicating whether debug mode is on. May be set on the command line. */ 108 int debug_flag = 0; 109 110 /* Flag indicating whether a tty should be requested */ 111 int tty_flag = 0; 112 113 /* don't exec a shell */ 114 int no_shell_flag = 0; 115 116 /* 117 * Flag indicating that nothing should be read from stdin. This can be set 118 * on the command line. 119 */ 120 int stdin_null_flag = 0; 121 122 /* 123 * Flag indicating that the current process should be backgrounded and 124 * a new mux-client launched in the foreground for ControlPersist. 125 */ 126 int need_controlpersist_detach = 0; 127 128 /* Copies of flags for ControlPersist foreground mux-client */ 129 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty; 130 131 /* 132 * Flag indicating that ssh should fork after authentication. This is useful 133 * so that the passphrase can be entered manually, and then ssh goes to the 134 * background. 135 */ 136 int fork_after_authentication_flag = 0; 137 138 /* 139 * General data structure for command line options and options configurable 140 * in configuration files. See readconf.h. 141 */ 142 Options options; 143 144 /* optional user configfile */ 145 char *config = NULL; 146 147 /* 148 * Name of the host we are connecting to. This is the name given on the 149 * command line, or the Hostname specified for the user-supplied name in a 150 * configuration file. 151 */ 152 char *host; 153 154 /* 155 * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is 156 * not NULL, forward the socket at this path instead. 157 */ 158 char *forward_agent_sock_path = NULL; 159 160 /* Various strings used to to percent_expand() arguments */ 161 static char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV]; 162 static char uidstr[32], *host_arg, *conn_hash_hex; 163 static const char *keyalias; 164 165 /* socket address the host resolves to */ 166 struct sockaddr_storage hostaddr; 167 168 /* Private host keys. */ 169 Sensitive sensitive_data; 170 171 /* command to be executed */ 172 struct sshbuf *command; 173 174 /* Should we execute a command or invoke a subsystem? */ 175 int subsystem_flag = 0; 176 177 /* # of replies received for global requests */ 178 static int forward_confirms_pending = -1; 179 180 /* mux.c */ 181 extern int muxserver_sock; 182 extern u_int muxclient_command; 183 184 /* Prints a help message to the user. This function never returns. */ 185 186 static void 187 usage(void) 188 { 189 fprintf(stderr, 190 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]\n" 191 " [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]\n" 192 " [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]\n" 193 " [-i identity_file] [-J [user@]host[:port]] [-L address]\n" 194 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n" 195 " [-Q query_option] [-R address] [-S ctl_path] [-W host:port]\n" 196 " [-w local_tun[:remote_tun]] destination [command]\n" 197 ); 198 exit(255); 199 } 200 201 static int ssh_session2(struct ssh *, struct passwd *); 202 static void load_public_identity_files(struct passwd *); 203 static void main_sigchld_handler(int); 204 205 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */ 206 static void 207 tilde_expand_paths(char **paths, u_int num_paths) 208 { 209 u_int i; 210 char *cp; 211 212 for (i = 0; i < num_paths; i++) { 213 cp = tilde_expand_filename(paths[i], getuid()); 214 free(paths[i]); 215 paths[i] = cp; 216 } 217 } 218 219 #define DEFAULT_CLIENT_PERCENT_EXPAND_ARGS \ 220 "C", conn_hash_hex, \ 221 "L", shorthost, \ 222 "i", uidstr, \ 223 "k", keyalias, \ 224 "l", thishost, \ 225 "n", host_arg, \ 226 "p", portstr 227 228 /* 229 * Expands the set of percent_expand options used by the majority of keywords 230 * in the client that support percent expansion. 231 * Caller must free returned string. 232 */ 233 static char * 234 default_client_percent_expand(const char *str, const char *homedir, 235 const char *remhost, const char *remuser, const char *locuser) 236 { 237 return percent_expand(str, 238 /* values from statics above */ 239 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS, 240 /* values from arguments */ 241 "d", homedir, 242 "h", remhost, 243 "r", remuser, 244 "u", locuser, 245 (char *)NULL); 246 } 247 248 /* 249 * Expands the set of percent_expand options used by the majority of keywords 250 * AND perform environment variable substitution. 251 * Caller must free returned string. 252 */ 253 static char * 254 default_client_percent_dollar_expand(const char *str, const char *homedir, 255 const char *remhost, const char *remuser, const char *locuser) 256 { 257 char *ret; 258 259 ret = percent_dollar_expand(str, 260 /* values from statics above */ 261 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS, 262 /* values from arguments */ 263 "d", homedir, 264 "h", remhost, 265 "r", remuser, 266 "u", locuser, 267 (char *)NULL); 268 if (ret == NULL) 269 fatal("invalid environment variable expansion"); 270 return ret; 271 } 272 273 /* 274 * Attempt to resolve a host name / port to a set of addresses and 275 * optionally return any CNAMEs encountered along the way. 276 * Returns NULL on failure. 277 * NB. this function must operate with a options having undefined members. 278 */ 279 static struct addrinfo * 280 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen) 281 { 282 char strport[NI_MAXSERV]; 283 struct addrinfo hints, *res; 284 int gaierr; 285 LogLevel loglevel = SYSLOG_LEVEL_DEBUG1; 286 287 if (port <= 0) 288 port = default_ssh_port(); 289 if (cname != NULL) 290 *cname = '\0'; 291 292 snprintf(strport, sizeof strport, "%d", port); 293 memset(&hints, 0, sizeof(hints)); 294 hints.ai_family = options.address_family == -1 ? 295 AF_UNSPEC : options.address_family; 296 hints.ai_socktype = SOCK_STREAM; 297 if (cname != NULL) 298 hints.ai_flags = AI_CANONNAME; 299 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) { 300 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA)) 301 loglevel = SYSLOG_LEVEL_ERROR; 302 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s", 303 __progname, name, ssh_gai_strerror(gaierr)); 304 return NULL; 305 } 306 if (cname != NULL && res->ai_canonname != NULL) { 307 if (strlcpy(cname, res->ai_canonname, clen) >= clen) { 308 error_f("host \"%s\" cname \"%s\" too long (max %lu)", 309 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_f("could not resolve name %.100s as address: %s", 374 name, ssh_gai_strerror(gaierr)); 375 return NULL; 376 } 377 if (res == NULL) { 378 debug_f("getaddrinfo %.100s returned no addresses", name); 379 return NULL; 380 } 381 if (res->ai_next != NULL) { 382 debug_f("getaddrinfo %.100s returned multiple addresses", name); 383 goto fail; 384 } 385 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen, 386 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) { 387 debug_f("Could not format address for name %.100s: %s", 388 name, ssh_gai_strerror(gaierr)); 389 goto fail; 390 } 391 if (strlcpy(caddr, addr, clen) >= clen) { 392 error_f("host \"%s\" addr \"%s\" too long (max %lu)", 393 name, addr, (u_long)clen); 394 if (clen > 0) 395 *caddr = '\0'; 396 fail: 397 freeaddrinfo(res); 398 return NULL; 399 } 400 return res; 401 } 402 403 /* 404 * Check whether the cname is a permitted replacement for the hostname 405 * and perform the replacement if it is. 406 * NB. this function must operate with a options having undefined members. 407 */ 408 static int 409 check_follow_cname(int direct, char **namep, const char *cname) 410 { 411 int i; 412 struct allowed_cname *rule; 413 414 if (*cname == '\0' || options.num_permitted_cnames == 0 || 415 strcmp(*namep, cname) == 0) 416 return 0; 417 if (options.canonicalize_hostname == SSH_CANONICALISE_NO) 418 return 0; 419 /* 420 * Don't attempt to canonicalize names that will be interpreted by 421 * a proxy or jump host unless the user specifically requests so. 422 */ 423 if (!direct && 424 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS) 425 return 0; 426 debug3_f("check \"%s\" CNAME \"%s\"", *namep, cname); 427 for (i = 0; i < options.num_permitted_cnames; i++) { 428 rule = options.permitted_cnames + i; 429 if (match_pattern_list(*namep, rule->source_list, 1) != 1 || 430 match_pattern_list(cname, rule->target_list, 1) != 1) 431 continue; 432 verbose("Canonicalized DNS aliased hostname " 433 "\"%s\" => \"%s\"", *namep, cname); 434 free(*namep); 435 *namep = xstrdup(cname); 436 return 1; 437 } 438 return 0; 439 } 440 441 /* 442 * Attempt to resolve the supplied hostname after applying the user's 443 * canonicalization rules. Returns the address list for the host or NULL 444 * if no name was found after canonicalization. 445 * NB. this function must operate with a options having undefined members. 446 */ 447 static struct addrinfo * 448 resolve_canonicalize(char **hostp, int port) 449 { 450 int i, direct, ndots; 451 char *cp, *fullhost, newname[NI_MAXHOST]; 452 struct addrinfo *addrs; 453 454 /* 455 * Attempt to canonicalise addresses, regardless of 456 * whether hostname canonicalisation was requested 457 */ 458 if ((addrs = resolve_addr(*hostp, port, 459 newname, sizeof(newname))) != NULL) { 460 debug2_f("hostname %.100s is address", *hostp); 461 if (strcasecmp(*hostp, newname) != 0) { 462 debug2_f("canonicalised address \"%s\" => \"%s\"", 463 *hostp, newname); 464 free(*hostp); 465 *hostp = xstrdup(newname); 466 } 467 return addrs; 468 } 469 470 /* 471 * If this looks like an address but didn't parse as one, it might 472 * be an address with an invalid interface scope. Skip further 473 * attempts at canonicalisation. 474 */ 475 if (is_addr_fast(*hostp)) { 476 debug_f("hostname %.100s is an unrecognised address", *hostp); 477 return NULL; 478 } 479 480 if (options.canonicalize_hostname == SSH_CANONICALISE_NO) 481 return NULL; 482 483 /* 484 * Don't attempt to canonicalize names that will be interpreted by 485 * a proxy unless the user specifically requests so. 486 */ 487 direct = option_clear_or_none(options.proxy_command) && 488 options.jump_host == NULL; 489 if (!direct && 490 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS) 491 return NULL; 492 493 /* If domain name is anchored, then resolve it now */ 494 if ((*hostp)[strlen(*hostp) - 1] == '.') { 495 debug3_f("name is fully qualified"); 496 fullhost = xstrdup(*hostp); 497 if ((addrs = resolve_host(fullhost, port, 0, 498 newname, sizeof(newname))) != NULL) 499 goto found; 500 free(fullhost); 501 goto notfound; 502 } 503 504 /* Don't apply canonicalization to sufficiently-qualified hostnames */ 505 ndots = 0; 506 for (cp = *hostp; *cp != '\0'; cp++) { 507 if (*cp == '.') 508 ndots++; 509 } 510 if (ndots > options.canonicalize_max_dots) { 511 debug3_f("not canonicalizing hostname \"%s\" (max dots %d)", 512 *hostp, options.canonicalize_max_dots); 513 return NULL; 514 } 515 /* Attempt each supplied suffix */ 516 for (i = 0; i < options.num_canonical_domains; i++) { 517 xasprintf(&fullhost, "%s.%s.", *hostp, 518 options.canonical_domains[i]); 519 debug3_f("attempting \"%s\" => \"%s\"", *hostp, fullhost); 520 if ((addrs = resolve_host(fullhost, port, 0, 521 newname, sizeof(newname))) == NULL) { 522 free(fullhost); 523 continue; 524 } 525 found: 526 /* Remove trailing '.' */ 527 fullhost[strlen(fullhost) - 1] = '\0'; 528 /* Follow CNAME if requested */ 529 if (!check_follow_cname(direct, &fullhost, newname)) { 530 debug("Canonicalized hostname \"%s\" => \"%s\"", 531 *hostp, fullhost); 532 } 533 free(*hostp); 534 *hostp = fullhost; 535 return addrs; 536 } 537 notfound: 538 if (!options.canonicalize_fallback_local) 539 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp); 540 debug2_f("host %s not found in any suffix", *hostp); 541 return NULL; 542 } 543 544 /* 545 * Check the result of hostkey loading, ignoring some errors and 546 * fatal()ing for others. 547 */ 548 static void 549 check_load(int r, const char *path, const char *message) 550 { 551 switch (r) { 552 case 0: 553 break; 554 case SSH_ERR_INTERNAL_ERROR: 555 case SSH_ERR_ALLOC_FAIL: 556 fatal_r(r, "load %s \"%s\"", message, path); 557 case SSH_ERR_SYSTEM_ERROR: 558 /* Ignore missing files */ 559 if (errno == ENOENT) 560 break; 561 /* FALLTHROUGH */ 562 default: 563 error_r(r, "load %s \"%s\"", message, path); 564 break; 565 } 566 } 567 568 /* 569 * Read per-user configuration file. Ignore the system wide config 570 * file if the user specifies a config file on the command line. 571 */ 572 static void 573 process_config_files(const char *host_name, struct passwd *pw, int final_pass, 574 int *want_final_pass) 575 { 576 char buf[PATH_MAX]; 577 int r; 578 579 if (config != NULL) { 580 if (strcasecmp(config, "none") != 0 && 581 !read_config_file(config, pw, host, host_name, &options, 582 SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0), 583 want_final_pass)) 584 fatal("Can't open user config file %.100s: " 585 "%.100s", config, strerror(errno)); 586 } else { 587 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir, 588 _PATH_SSH_USER_CONFFILE); 589 if (r > 0 && (size_t)r < sizeof(buf)) 590 (void)read_config_file(buf, pw, host, host_name, 591 &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF | 592 (final_pass ? SSHCONF_FINAL : 0), want_final_pass); 593 594 /* Read systemwide configuration file after user config. */ 595 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, 596 host, host_name, &options, 597 final_pass ? SSHCONF_FINAL : 0, want_final_pass); 598 } 599 } 600 601 /* Rewrite the port number in an addrinfo list of addresses */ 602 static void 603 set_addrinfo_port(struct addrinfo *addrs, int port) 604 { 605 struct addrinfo *addr; 606 607 for (addr = addrs; addr != NULL; addr = addr->ai_next) { 608 switch (addr->ai_family) { 609 case AF_INET: 610 ((struct sockaddr_in *)addr->ai_addr)-> 611 sin_port = htons(port); 612 break; 613 case AF_INET6: 614 ((struct sockaddr_in6 *)addr->ai_addr)-> 615 sin6_port = htons(port); 616 break; 617 } 618 } 619 } 620 621 /* 622 * Main program for the ssh client. 623 */ 624 int 625 main(int ac, char **av) 626 { 627 struct ssh *ssh = NULL; 628 int i, r, opt, exit_status, use_syslog, direct, timeout_ms; 629 int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0; 630 char *p, *cp, *line, *argv0, *logfile; 631 char cname[NI_MAXHOST]; 632 struct stat st; 633 struct passwd *pw; 634 extern int optind, optreset; 635 extern char *optarg; 636 struct Forward fwd; 637 struct addrinfo *addrs = NULL; 638 size_t n, len; 639 u_int j; 640 641 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 642 sanitise_stdfd(); 643 644 /* 645 * Discard other fds that are hanging around. These can cause problem 646 * with backgrounded ssh processes started by ControlPersist. 647 */ 648 closefrom(STDERR_FILENO + 1); 649 650 if (getuid() != geteuid()) 651 fatal("ssh setuid not supported."); 652 if (getgid() != getegid()) 653 fatal("ssh setgid not supported."); 654 655 /* Get user data. */ 656 pw = getpwuid(getuid()); 657 if (!pw) { 658 logit("No user exists for uid %lu", (u_long)getuid()); 659 exit(255); 660 } 661 /* Take a copy of the returned structure. */ 662 pw = pwcopy(pw); 663 664 /* 665 * Set our umask to something reasonable, as some files are created 666 * with the default umask. This will make them world-readable but 667 * writable only by the owner, which is ok for all files for which we 668 * don't set the modes explicitly. 669 */ 670 umask(022); 671 672 setlocale(LC_CTYPE, ""); 673 674 /* 675 * Initialize option structure to indicate that no values have been 676 * set. 677 */ 678 initialize_options(&options); 679 680 /* 681 * Prepare main ssh transport/connection structures 682 */ 683 if ((ssh = ssh_alloc_session_state()) == NULL) 684 fatal("Couldn't allocate session state"); 685 channel_init_channels(ssh); 686 687 /* Parse command-line arguments. */ 688 host = NULL; 689 use_syslog = 0; 690 logfile = NULL; 691 argv0 = av[0]; 692 693 again: 694 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx" 695 "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) { 696 switch (opt) { 697 case '1': 698 fatal("SSH protocol v.1 is no longer supported"); 699 break; 700 case '2': 701 /* Ignored */ 702 break; 703 case '4': 704 options.address_family = AF_INET; 705 break; 706 case '6': 707 options.address_family = AF_INET6; 708 break; 709 case 'n': 710 stdin_null_flag = 1; 711 break; 712 case 'f': 713 fork_after_authentication_flag = 1; 714 stdin_null_flag = 1; 715 break; 716 case 'x': 717 options.forward_x11 = 0; 718 break; 719 case 'X': 720 options.forward_x11 = 1; 721 break; 722 case 'y': 723 use_syslog = 1; 724 break; 725 case 'E': 726 logfile = optarg; 727 break; 728 case 'G': 729 config_test = 1; 730 break; 731 case 'Y': 732 options.forward_x11 = 1; 733 options.forward_x11_trusted = 1; 734 break; 735 case 'g': 736 options.fwd_opts.gateway_ports = 1; 737 break; 738 case 'O': 739 if (options.stdio_forward_host != NULL) 740 fatal("Cannot specify multiplexing " 741 "command with -W"); 742 else if (muxclient_command != 0) 743 fatal("Multiplexing command already specified"); 744 if (strcmp(optarg, "check") == 0) 745 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK; 746 else if (strcmp(optarg, "forward") == 0) 747 muxclient_command = SSHMUX_COMMAND_FORWARD; 748 else if (strcmp(optarg, "exit") == 0) 749 muxclient_command = SSHMUX_COMMAND_TERMINATE; 750 else if (strcmp(optarg, "stop") == 0) 751 muxclient_command = SSHMUX_COMMAND_STOP; 752 else if (strcmp(optarg, "cancel") == 0) 753 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD; 754 else if (strcmp(optarg, "proxy") == 0) 755 muxclient_command = SSHMUX_COMMAND_PROXY; 756 else 757 fatal("Invalid multiplex command."); 758 break; 759 case 'P': /* deprecated */ 760 break; 761 case 'Q': 762 cp = NULL; 763 if (strcmp(optarg, "cipher") == 0 || 764 strcasecmp(optarg, "Ciphers") == 0) 765 cp = cipher_alg_list('\n', 0); 766 else if (strcmp(optarg, "cipher-auth") == 0) 767 cp = cipher_alg_list('\n', 1); 768 else if (strcmp(optarg, "mac") == 0 || 769 strcasecmp(optarg, "MACs") == 0) 770 cp = mac_alg_list('\n'); 771 else if (strcmp(optarg, "kex") == 0 || 772 strcasecmp(optarg, "KexAlgorithms") == 0) 773 cp = kex_alg_list('\n'); 774 else if (strcmp(optarg, "key") == 0) 775 cp = sshkey_alg_list(0, 0, 0, '\n'); 776 else if (strcmp(optarg, "key-cert") == 0) 777 cp = sshkey_alg_list(1, 0, 0, '\n'); 778 else if (strcmp(optarg, "key-plain") == 0) 779 cp = sshkey_alg_list(0, 1, 0, '\n'); 780 else if (strcmp(optarg, "key-sig") == 0 || 781 strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || 782 strcasecmp(optarg, "HostKeyAlgorithms") == 0 || 783 strcasecmp(optarg, "HostbasedKeyTypes") == 0 || 784 strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0) 785 cp = sshkey_alg_list(0, 0, 1, '\n'); 786 else if (strcmp(optarg, "sig") == 0) 787 cp = sshkey_alg_list(0, 1, 1, '\n'); 788 else if (strcmp(optarg, "protocol-version") == 0) 789 cp = xstrdup("2"); 790 else if (strcmp(optarg, "compression") == 0) { 791 cp = xstrdup(compression_alg_list(0)); 792 len = strlen(cp); 793 for (n = 0; n < len; n++) 794 if (cp[n] == ',') 795 cp[n] = '\n'; 796 } else if (strcmp(optarg, "help") == 0) { 797 cp = xstrdup( 798 "cipher\ncipher-auth\ncompression\nkex\n" 799 "key\nkey-cert\nkey-plain\nkey-sig\nmac\n" 800 "protocol-version\nsig"); 801 } 802 if (cp == NULL) 803 fatal("Unsupported query \"%s\"", optarg); 804 printf("%s\n", cp); 805 free(cp); 806 exit(0); 807 break; 808 case 'a': 809 options.forward_agent = 0; 810 break; 811 case 'A': 812 options.forward_agent = 1; 813 break; 814 case 'k': 815 options.gss_deleg_creds = 0; 816 break; 817 case 'K': 818 options.gss_authentication = 1; 819 options.gss_deleg_creds = 1; 820 break; 821 case 'i': 822 p = tilde_expand_filename(optarg, getuid()); 823 if (stat(p, &st) == -1) 824 fprintf(stderr, "Warning: Identity file %s " 825 "not accessible: %s.\n", p, 826 strerror(errno)); 827 else 828 add_identity_file(&options, NULL, p, 1); 829 free(p); 830 break; 831 case 'I': 832 #ifdef ENABLE_PKCS11 833 free(options.pkcs11_provider); 834 options.pkcs11_provider = xstrdup(optarg); 835 #else 836 fprintf(stderr, "no support for PKCS#11.\n"); 837 #endif 838 break; 839 case 'J': 840 if (options.jump_host != NULL) { 841 fatal("Only a single -J option is permitted " 842 "(use commas to separate multiple " 843 "jump hops)"); 844 } 845 if (options.proxy_command != NULL) 846 fatal("Cannot specify -J with ProxyCommand"); 847 if (parse_jump(optarg, &options, 1) == -1) 848 fatal("Invalid -J argument"); 849 options.proxy_command = xstrdup("none"); 850 break; 851 case 't': 852 if (options.request_tty == REQUEST_TTY_YES) 853 options.request_tty = REQUEST_TTY_FORCE; 854 else 855 options.request_tty = REQUEST_TTY_YES; 856 break; 857 case 'v': 858 if (debug_flag == 0) { 859 debug_flag = 1; 860 options.log_level = SYSLOG_LEVEL_DEBUG1; 861 } else { 862 if (options.log_level < SYSLOG_LEVEL_DEBUG3) { 863 debug_flag++; 864 options.log_level++; 865 } 866 } 867 break; 868 case 'V': 869 fprintf(stderr, "%s, %s\n", 870 SSH_VERSION, 871 #ifdef WITH_OPENSSL 872 OpenSSL_version(OPENSSL_VERSION) 873 #else 874 "without OpenSSL" 875 #endif 876 ); 877 if (opt == 'V') 878 exit(0); 879 break; 880 case 'w': 881 if (options.tun_open == -1) 882 options.tun_open = SSH_TUNMODE_DEFAULT; 883 options.tun_local = a2tun(optarg, &options.tun_remote); 884 if (options.tun_local == SSH_TUNID_ERR) { 885 fprintf(stderr, 886 "Bad tun device '%s'\n", optarg); 887 exit(255); 888 } 889 break; 890 case 'W': 891 if (options.stdio_forward_host != NULL) 892 fatal("stdio forward already specified"); 893 if (muxclient_command != 0) 894 fatal("Cannot specify stdio forward with -O"); 895 if (parse_forward(&fwd, optarg, 1, 0)) { 896 options.stdio_forward_host = fwd.listen_host; 897 options.stdio_forward_port = fwd.listen_port; 898 free(fwd.connect_host); 899 } else { 900 fprintf(stderr, 901 "Bad stdio forwarding specification '%s'\n", 902 optarg); 903 exit(255); 904 } 905 options.request_tty = REQUEST_TTY_NO; 906 no_shell_flag = 1; 907 break; 908 case 'q': 909 options.log_level = SYSLOG_LEVEL_QUIET; 910 break; 911 case 'e': 912 if (optarg[0] == '^' && optarg[2] == 0 && 913 (u_char) optarg[1] >= 64 && 914 (u_char) optarg[1] < 128) 915 options.escape_char = (u_char) optarg[1] & 31; 916 else if (strlen(optarg) == 1) 917 options.escape_char = (u_char) optarg[0]; 918 else if (strcmp(optarg, "none") == 0) 919 options.escape_char = SSH_ESCAPECHAR_NONE; 920 else { 921 fprintf(stderr, "Bad escape character '%s'.\n", 922 optarg); 923 exit(255); 924 } 925 break; 926 case 'c': 927 if (!ciphers_valid(*optarg == '+' || *optarg == '^' ? 928 optarg + 1 : optarg)) { 929 fprintf(stderr, "Unknown cipher type '%s'\n", 930 optarg); 931 exit(255); 932 } 933 free(options.ciphers); 934 options.ciphers = xstrdup(optarg); 935 break; 936 case 'm': 937 if (mac_valid(optarg)) { 938 free(options.macs); 939 options.macs = xstrdup(optarg); 940 } else { 941 fprintf(stderr, "Unknown mac type '%s'\n", 942 optarg); 943 exit(255); 944 } 945 break; 946 case 'M': 947 if (options.control_master == SSHCTL_MASTER_YES) 948 options.control_master = SSHCTL_MASTER_ASK; 949 else 950 options.control_master = SSHCTL_MASTER_YES; 951 break; 952 case 'p': 953 if (options.port == -1) { 954 options.port = a2port(optarg); 955 if (options.port <= 0) { 956 fprintf(stderr, "Bad port '%s'\n", 957 optarg); 958 exit(255); 959 } 960 } 961 break; 962 case 'l': 963 if (options.user == NULL) 964 options.user = optarg; 965 break; 966 967 case 'L': 968 if (parse_forward(&fwd, optarg, 0, 0)) 969 add_local_forward(&options, &fwd); 970 else { 971 fprintf(stderr, 972 "Bad local forwarding specification '%s'\n", 973 optarg); 974 exit(255); 975 } 976 break; 977 978 case 'R': 979 if (parse_forward(&fwd, optarg, 0, 1) || 980 parse_forward(&fwd, optarg, 1, 1)) { 981 add_remote_forward(&options, &fwd); 982 } else { 983 fprintf(stderr, 984 "Bad remote forwarding specification " 985 "'%s'\n", optarg); 986 exit(255); 987 } 988 break; 989 990 case 'D': 991 if (parse_forward(&fwd, optarg, 1, 0)) { 992 add_local_forward(&options, &fwd); 993 } else { 994 fprintf(stderr, 995 "Bad dynamic forwarding specification " 996 "'%s'\n", optarg); 997 exit(255); 998 } 999 break; 1000 1001 case 'C': 1002 #ifdef WITH_ZLIB 1003 options.compression = 1; 1004 #else 1005 error("Compression not supported, disabling."); 1006 #endif 1007 break; 1008 case 'N': 1009 no_shell_flag = 1; 1010 options.request_tty = REQUEST_TTY_NO; 1011 break; 1012 case 'T': 1013 options.request_tty = REQUEST_TTY_NO; 1014 break; 1015 case 'o': 1016 line = xstrdup(optarg); 1017 if (process_config_line(&options, pw, 1018 host ? host : "", host ? host : "", line, 1019 "command-line", 0, NULL, SSHCONF_USERCONF) != 0) 1020 exit(255); 1021 free(line); 1022 break; 1023 case 's': 1024 subsystem_flag = 1; 1025 break; 1026 case 'S': 1027 free(options.control_path); 1028 options.control_path = xstrdup(optarg); 1029 break; 1030 case 'b': 1031 options.bind_address = optarg; 1032 break; 1033 case 'B': 1034 options.bind_interface = optarg; 1035 break; 1036 case 'F': 1037 config = optarg; 1038 break; 1039 default: 1040 usage(); 1041 } 1042 } 1043 1044 if (optind > 1 && strcmp(av[optind - 1], "--") == 0) 1045 opt_terminated = 1; 1046 1047 ac -= optind; 1048 av += optind; 1049 1050 if (ac > 0 && !host) { 1051 int tport; 1052 char *tuser; 1053 switch (parse_ssh_uri(*av, &tuser, &host, &tport)) { 1054 case -1: 1055 usage(); 1056 break; 1057 case 0: 1058 if (options.user == NULL) { 1059 options.user = tuser; 1060 tuser = NULL; 1061 } 1062 free(tuser); 1063 if (options.port == -1 && tport != -1) 1064 options.port = tport; 1065 break; 1066 default: 1067 p = xstrdup(*av); 1068 cp = strrchr(p, '@'); 1069 if (cp != NULL) { 1070 if (cp == p) 1071 usage(); 1072 if (options.user == NULL) { 1073 options.user = p; 1074 p = NULL; 1075 } 1076 *cp++ = '\0'; 1077 host = xstrdup(cp); 1078 free(p); 1079 } else 1080 host = p; 1081 break; 1082 } 1083 if (ac > 1 && !opt_terminated) { 1084 optind = optreset = 1; 1085 goto again; 1086 } 1087 ac--, av++; 1088 } 1089 1090 /* Check that we got a host name. */ 1091 if (!host) 1092 usage(); 1093 1094 host_arg = xstrdup(host); 1095 1096 #ifdef WITH_OPENSSL 1097 OpenSSL_add_all_algorithms(); 1098 ERR_load_crypto_strings(); 1099 #endif 1100 1101 /* Initialize the command to execute on remote host. */ 1102 if ((command = sshbuf_new()) == NULL) 1103 fatal("sshbuf_new failed"); 1104 1105 /* 1106 * Save the command to execute on the remote host in a buffer. There 1107 * is no limit on the length of the command, except by the maximum 1108 * packet size. Also sets the tty flag if there is no command. 1109 */ 1110 if (!ac) { 1111 /* No command specified - execute shell on a tty. */ 1112 if (subsystem_flag) { 1113 fprintf(stderr, 1114 "You must specify a subsystem to invoke.\n"); 1115 usage(); 1116 } 1117 } else { 1118 /* A command has been specified. Store it into the buffer. */ 1119 for (i = 0; i < ac; i++) { 1120 if ((r = sshbuf_putf(command, "%s%s", 1121 i ? " " : "", av[i])) != 0) 1122 fatal_fr(r, "buffer error"); 1123 } 1124 } 1125 1126 /* 1127 * Initialize "log" output. Since we are the client all output 1128 * goes to stderr unless otherwise specified by -y or -E. 1129 */ 1130 if (use_syslog && logfile != NULL) 1131 fatal("Can't specify both -y and -E"); 1132 if (logfile != NULL) 1133 log_redirect_stderr_to(logfile); 1134 log_init(argv0, 1135 options.log_level == SYSLOG_LEVEL_NOT_SET ? 1136 SYSLOG_LEVEL_INFO : options.log_level, 1137 options.log_facility == SYSLOG_FACILITY_NOT_SET ? 1138 SYSLOG_FACILITY_USER : options.log_facility, 1139 !use_syslog); 1140 1141 if (debug_flag) 1142 logit("%s, %s", SSH_VERSION, 1143 #ifdef WITH_OPENSSL 1144 OpenSSL_version(OPENSSL_VERSION) 1145 #else 1146 "without OpenSSL" 1147 #endif 1148 ); 1149 1150 /* Parse the configuration files */ 1151 process_config_files(host_arg, pw, 0, &want_final_pass); 1152 if (want_final_pass) 1153 debug("configuration requests final Match pass"); 1154 1155 /* Hostname canonicalisation needs a few options filled. */ 1156 fill_default_options_for_canonicalization(&options); 1157 1158 /* If the user has replaced the hostname then take it into use now */ 1159 if (options.hostname != NULL) { 1160 /* NB. Please keep in sync with readconf.c:match_cfg_line() */ 1161 cp = percent_expand(options.hostname, 1162 "h", host, (char *)NULL); 1163 free(host); 1164 host = cp; 1165 free(options.hostname); 1166 options.hostname = xstrdup(host); 1167 } 1168 1169 /* Don't lowercase addresses, they will be explicitly canonicalised */ 1170 if ((was_addr = is_addr(host)) == 0) 1171 lowercase(host); 1172 1173 /* 1174 * Try to canonicalize if requested by configuration or the 1175 * hostname is an address. 1176 */ 1177 if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr) 1178 addrs = resolve_canonicalize(&host, options.port); 1179 1180 /* 1181 * If CanonicalizePermittedCNAMEs have been specified but 1182 * other canonicalization did not happen (by not being requested 1183 * or by failing with fallback) then the hostname may still be changed 1184 * as a result of CNAME following. 1185 * 1186 * Try to resolve the bare hostname name using the system resolver's 1187 * usual search rules and then apply the CNAME follow rules. 1188 * 1189 * Skip the lookup if a ProxyCommand is being used unless the user 1190 * has specifically requested canonicalisation for this case via 1191 * CanonicalizeHostname=always 1192 */ 1193 direct = option_clear_or_none(options.proxy_command) && 1194 options.jump_host == NULL; 1195 if (addrs == NULL && options.num_permitted_cnames != 0 && (direct || 1196 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) { 1197 if ((addrs = resolve_host(host, options.port, 1198 direct, cname, sizeof(cname))) == NULL) { 1199 /* Don't fatal proxied host names not in the DNS */ 1200 if (direct) 1201 cleanup_exit(255); /* logged in resolve_host */ 1202 } else 1203 check_follow_cname(direct, &host, cname); 1204 } 1205 1206 /* 1207 * If canonicalisation is enabled then re-parse the configuration 1208 * files as new stanzas may match. 1209 */ 1210 if (options.canonicalize_hostname != 0 && !want_final_pass) { 1211 debug("hostname canonicalisation enabled, " 1212 "will re-parse configuration"); 1213 want_final_pass = 1; 1214 } 1215 1216 if (want_final_pass) { 1217 debug("re-parsing configuration"); 1218 free(options.hostname); 1219 options.hostname = xstrdup(host); 1220 process_config_files(host_arg, pw, 1, NULL); 1221 /* 1222 * Address resolution happens early with canonicalisation 1223 * enabled and the port number may have changed since, so 1224 * reset it in address list 1225 */ 1226 if (addrs != NULL && options.port > 0) 1227 set_addrinfo_port(addrs, options.port); 1228 } 1229 1230 /* Fill configuration defaults. */ 1231 fill_default_options(&options); 1232 1233 if (options.user == NULL) 1234 options.user = xstrdup(pw->pw_name); 1235 1236 /* 1237 * If ProxyJump option specified, then construct a ProxyCommand now. 1238 */ 1239 if (options.jump_host != NULL) { 1240 char port_s[8]; 1241 const char *jumpuser = options.jump_user, *sshbin = argv0; 1242 int port = options.port, jumpport = options.jump_port; 1243 1244 if (port <= 0) 1245 port = default_ssh_port(); 1246 if (jumpport <= 0) 1247 jumpport = default_ssh_port(); 1248 if (jumpuser == NULL) 1249 jumpuser = options.user; 1250 if (strcmp(options.jump_host, host) == 0 && port == jumpport && 1251 strcmp(options.user, jumpuser) == 0) 1252 fatal("jumphost loop via %s", options.jump_host); 1253 1254 /* 1255 * Try to use SSH indicated by argv[0], but fall back to 1256 * "ssh" if it appears unavailable. 1257 */ 1258 if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0) 1259 sshbin = "ssh"; 1260 1261 /* Consistency check */ 1262 if (options.proxy_command != NULL) 1263 fatal("inconsistent options: ProxyCommand+ProxyJump"); 1264 /* Never use FD passing for ProxyJump */ 1265 options.proxy_use_fdpass = 0; 1266 snprintf(port_s, sizeof(port_s), "%d", options.jump_port); 1267 xasprintf(&options.proxy_command, 1268 "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s", 1269 sshbin, 1270 /* Optional "-l user" argument if jump_user set */ 1271 options.jump_user == NULL ? "" : " -l ", 1272 options.jump_user == NULL ? "" : options.jump_user, 1273 /* Optional "-p port" argument if jump_port set */ 1274 options.jump_port <= 0 ? "" : " -p ", 1275 options.jump_port <= 0 ? "" : port_s, 1276 /* Optional additional jump hosts ",..." */ 1277 options.jump_extra == NULL ? "" : " -J ", 1278 options.jump_extra == NULL ? "" : options.jump_extra, 1279 /* Optional "-F" argumment if -F specified */ 1280 config == NULL ? "" : " -F ", 1281 config == NULL ? "" : config, 1282 /* Optional "-v" arguments if -v set */ 1283 debug_flag ? " -" : "", 1284 debug_flag, "vvv", 1285 /* Mandatory hostname */ 1286 options.jump_host); 1287 debug("Setting implicit ProxyCommand from ProxyJump: %s", 1288 options.proxy_command); 1289 } 1290 1291 if (options.port == 0) 1292 options.port = default_ssh_port(); 1293 channel_set_af(ssh, options.address_family); 1294 1295 /* Tidy and check options */ 1296 if (options.host_key_alias != NULL) 1297 lowercase(options.host_key_alias); 1298 if (options.proxy_command != NULL && 1299 strcmp(options.proxy_command, "-") == 0 && 1300 options.proxy_use_fdpass) 1301 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible"); 1302 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) { 1303 if (options.control_persist && options.control_path != NULL) { 1304 debug("UpdateHostKeys=ask is incompatible with " 1305 "ControlPersist; disabling"); 1306 options.update_hostkeys = 0; 1307 } else if (sshbuf_len(command) != 0 || 1308 options.remote_command != NULL || 1309 options.request_tty == REQUEST_TTY_NO) { 1310 debug("UpdateHostKeys=ask is incompatible with " 1311 "remote command execution; disabling"); 1312 options.update_hostkeys = 0; 1313 } else if (options.log_level < SYSLOG_LEVEL_INFO) { 1314 /* no point logging anything; user won't see it */ 1315 options.update_hostkeys = 0; 1316 } 1317 } 1318 if (options.connection_attempts <= 0) 1319 fatal("Invalid number of ConnectionAttempts"); 1320 1321 if (sshbuf_len(command) != 0 && options.remote_command != NULL) 1322 fatal("Cannot execute command-line and remote command."); 1323 1324 /* Cannot fork to background if no command. */ 1325 if (fork_after_authentication_flag && sshbuf_len(command) == 0 && 1326 options.remote_command == NULL && !no_shell_flag) 1327 fatal("Cannot fork into background without a command " 1328 "to execute."); 1329 1330 /* reinit */ 1331 log_init(argv0, options.log_level, options.log_facility, !use_syslog); 1332 for (j = 0; j < options.num_log_verbose; j++) 1333 log_verbose_add(options.log_verbose[j]); 1334 1335 if (options.request_tty == REQUEST_TTY_YES || 1336 options.request_tty == REQUEST_TTY_FORCE) 1337 tty_flag = 1; 1338 1339 /* Allocate a tty by default if no command specified. */ 1340 if (sshbuf_len(command) == 0 && options.remote_command == NULL) 1341 tty_flag = options.request_tty != REQUEST_TTY_NO; 1342 1343 /* Force no tty */ 1344 if (options.request_tty == REQUEST_TTY_NO || 1345 (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY)) 1346 tty_flag = 0; 1347 /* Do not allocate a tty if stdin is not a tty. */ 1348 if ((!isatty(fileno(stdin)) || stdin_null_flag) && 1349 options.request_tty != REQUEST_TTY_FORCE) { 1350 if (tty_flag) 1351 logit("Pseudo-terminal will not be allocated because " 1352 "stdin is not a terminal."); 1353 tty_flag = 0; 1354 } 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_fr(r, "buffer error"); 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.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_f("pubkey out of array bounds"); \ 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_f("cert out of array bounds"); \ 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 1678 debug_f("backgrounding master process"); 1679 1680 /* 1681 * master (current process) into the background, and make the 1682 * foreground process a client of the backgrounded master. 1683 */ 1684 switch ((pid = fork())) { 1685 case -1: 1686 fatal_f("fork: %s", strerror(errno)); 1687 case 0: 1688 /* Child: master process continues mainloop */ 1689 break; 1690 default: 1691 /* Parent: set up mux client to connect to backgrounded master */ 1692 debug2_f("background process is %ld", (long)pid); 1693 stdin_null_flag = ostdin_null_flag; 1694 options.request_tty = orequest_tty; 1695 tty_flag = otty_flag; 1696 close(muxserver_sock); 1697 muxserver_sock = -1; 1698 options.control_master = SSHCTL_MASTER_NO; 1699 muxclient(options.control_path); 1700 /* muxclient() doesn't return on success. */ 1701 fatal("Failed to connect to new control master"); 1702 } 1703 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1) 1704 error_f("stdfd_devnull failed"); 1705 daemon(1, 1); 1706 setproctitle("%s [mux]", options.control_path); 1707 } 1708 1709 /* Do fork() after authentication. Used by "ssh -f" */ 1710 static void 1711 fork_postauth(void) 1712 { 1713 if (need_controlpersist_detach) 1714 control_persist_detach(); 1715 debug("forking to background"); 1716 fork_after_authentication_flag = 0; 1717 if (daemon(1, 1) == -1) 1718 fatal("daemon() failed: %.200s", strerror(errno)); 1719 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1) 1720 error_f("stdfd_devnull failed"); 1721 } 1722 1723 static void 1724 forwarding_success(void) 1725 { 1726 if (forward_confirms_pending == -1) 1727 return; 1728 if (--forward_confirms_pending == 0) { 1729 debug_f("all expected forwarding replies received"); 1730 if (fork_after_authentication_flag) 1731 fork_postauth(); 1732 } else { 1733 debug2_f("%d expected forwarding replies remaining", 1734 forward_confirms_pending); 1735 } 1736 } 1737 1738 /* Callback for remote forward global requests */ 1739 static void 1740 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt) 1741 { 1742 struct Forward *rfwd = (struct Forward *)ctxt; 1743 u_int port; 1744 int r; 1745 1746 /* XXX verbose() on failure? */ 1747 debug("remote forward %s for: listen %s%s%d, connect %s:%d", 1748 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure", 1749 rfwd->listen_path ? rfwd->listen_path : 1750 rfwd->listen_host ? rfwd->listen_host : "", 1751 (rfwd->listen_path || rfwd->listen_host) ? ":" : "", 1752 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path : 1753 rfwd->connect_host, rfwd->connect_port); 1754 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) { 1755 if (type == SSH2_MSG_REQUEST_SUCCESS) { 1756 if ((r = sshpkt_get_u32(ssh, &port)) != 0) 1757 fatal_fr(r, "parse packet"); 1758 if (port > 65535) { 1759 error("Invalid allocated port %u for remote " 1760 "forward to %s:%d", port, 1761 rfwd->connect_host, rfwd->connect_port); 1762 /* Ensure failure processing runs below */ 1763 type = SSH2_MSG_REQUEST_FAILURE; 1764 channel_update_permission(ssh, 1765 rfwd->handle, -1); 1766 } else { 1767 rfwd->allocated_port = (int)port; 1768 logit("Allocated port %u for remote " 1769 "forward to %s:%d", 1770 rfwd->allocated_port, rfwd->connect_host, 1771 rfwd->connect_port); 1772 channel_update_permission(ssh, 1773 rfwd->handle, rfwd->allocated_port); 1774 } 1775 } else { 1776 channel_update_permission(ssh, rfwd->handle, -1); 1777 } 1778 } 1779 1780 if (type == SSH2_MSG_REQUEST_FAILURE) { 1781 if (options.exit_on_forward_failure) { 1782 if (rfwd->listen_path != NULL) 1783 fatal("Error: remote port forwarding failed " 1784 "for listen path %s", rfwd->listen_path); 1785 else 1786 fatal("Error: remote port forwarding failed " 1787 "for listen port %d", rfwd->listen_port); 1788 } else { 1789 if (rfwd->listen_path != NULL) 1790 logit("Warning: remote port forwarding failed " 1791 "for listen path %s", rfwd->listen_path); 1792 else 1793 logit("Warning: remote port forwarding failed " 1794 "for listen port %d", rfwd->listen_port); 1795 } 1796 } 1797 forwarding_success(); 1798 } 1799 1800 static void 1801 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg) 1802 { 1803 debug("stdio forwarding: done"); 1804 cleanup_exit(0); 1805 } 1806 1807 static void 1808 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg) 1809 { 1810 if (!success) 1811 fatal("stdio forwarding failed"); 1812 } 1813 1814 static void 1815 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg) 1816 { 1817 if (!success) { 1818 error("Tunnel forwarding failed"); 1819 if (options.exit_on_forward_failure) 1820 cleanup_exit(255); 1821 } 1822 1823 debug_f("tunnel forward established, id=%d", id); 1824 forwarding_success(); 1825 } 1826 1827 static void 1828 ssh_init_stdio_forwarding(struct ssh *ssh) 1829 { 1830 Channel *c; 1831 int in, out; 1832 1833 if (options.stdio_forward_host == NULL) 1834 return; 1835 1836 debug3_f("%s:%d", options.stdio_forward_host, 1837 options.stdio_forward_port); 1838 1839 if ((in = dup(STDIN_FILENO)) == -1 || 1840 (out = dup(STDOUT_FILENO)) == -1) 1841 fatal("channel_connect_stdio_fwd: dup() in/out failed"); 1842 if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host, 1843 options.stdio_forward_port, in, out)) == NULL) 1844 fatal_f("channel_connect_stdio_fwd failed"); 1845 channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0); 1846 channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL); 1847 } 1848 1849 static void 1850 ssh_init_forwarding(struct ssh *ssh, char **ifname) 1851 { 1852 int success = 0; 1853 int i; 1854 1855 if (options.exit_on_forward_failure) 1856 forward_confirms_pending = 0; /* track pending requests */ 1857 /* Initiate local TCP/IP port forwardings. */ 1858 for (i = 0; i < options.num_local_forwards; i++) { 1859 debug("Local connections to %.200s:%d forwarded to remote " 1860 "address %.200s:%d", 1861 (options.local_forwards[i].listen_path != NULL) ? 1862 options.local_forwards[i].listen_path : 1863 (options.local_forwards[i].listen_host == NULL) ? 1864 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") : 1865 options.local_forwards[i].listen_host, 1866 options.local_forwards[i].listen_port, 1867 (options.local_forwards[i].connect_path != NULL) ? 1868 options.local_forwards[i].connect_path : 1869 options.local_forwards[i].connect_host, 1870 options.local_forwards[i].connect_port); 1871 success += channel_setup_local_fwd_listener(ssh, 1872 &options.local_forwards[i], &options.fwd_opts); 1873 } 1874 if (i > 0 && success != i && options.exit_on_forward_failure) 1875 fatal("Could not request local forwarding."); 1876 if (i > 0 && success == 0) 1877 error("Could not request local forwarding."); 1878 1879 /* Initiate remote TCP/IP port forwardings. */ 1880 for (i = 0; i < options.num_remote_forwards; i++) { 1881 debug("Remote connections from %.200s:%d forwarded to " 1882 "local address %.200s:%d", 1883 (options.remote_forwards[i].listen_path != NULL) ? 1884 options.remote_forwards[i].listen_path : 1885 (options.remote_forwards[i].listen_host == NULL) ? 1886 "LOCALHOST" : options.remote_forwards[i].listen_host, 1887 options.remote_forwards[i].listen_port, 1888 (options.remote_forwards[i].connect_path != NULL) ? 1889 options.remote_forwards[i].connect_path : 1890 options.remote_forwards[i].connect_host, 1891 options.remote_forwards[i].connect_port); 1892 if ((options.remote_forwards[i].handle = 1893 channel_request_remote_forwarding(ssh, 1894 &options.remote_forwards[i])) >= 0) { 1895 client_register_global_confirm( 1896 ssh_confirm_remote_forward, 1897 &options.remote_forwards[i]); 1898 forward_confirms_pending++; 1899 } else if (options.exit_on_forward_failure) 1900 fatal("Could not request remote forwarding."); 1901 else 1902 logit("Warning: Could not request remote forwarding."); 1903 } 1904 1905 /* Initiate tunnel forwarding. */ 1906 if (options.tun_open != SSH_TUNMODE_NO) { 1907 if ((*ifname = client_request_tun_fwd(ssh, 1908 options.tun_open, options.tun_local, 1909 options.tun_remote, ssh_tun_confirm, NULL)) != NULL) 1910 forward_confirms_pending++; 1911 else if (options.exit_on_forward_failure) 1912 fatal("Could not request tunnel forwarding."); 1913 else 1914 error("Could not request tunnel forwarding."); 1915 } 1916 if (forward_confirms_pending > 0) { 1917 debug_f("expecting replies for %d forwards", 1918 forward_confirms_pending); 1919 } 1920 } 1921 1922 static void 1923 check_agent_present(void) 1924 { 1925 int r; 1926 1927 if (options.forward_agent) { 1928 /* Clear agent forwarding if we don't have an agent. */ 1929 if ((r = ssh_get_authentication_socket(NULL)) != 0) { 1930 options.forward_agent = 0; 1931 if (r != SSH_ERR_AGENT_NOT_PRESENT) 1932 debug_r(r, "ssh_get_authentication_socket"); 1933 } 1934 } 1935 } 1936 1937 static void 1938 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg) 1939 { 1940 extern char **environ; 1941 const char *display; 1942 int r, interactive = tty_flag; 1943 char *proto = NULL, *data = NULL; 1944 1945 if (!success) 1946 return; /* No need for error message, channels code sens one */ 1947 1948 display = getenv("DISPLAY"); 1949 if (display == NULL && options.forward_x11) 1950 debug("X11 forwarding requested but DISPLAY not set"); 1951 if (options.forward_x11 && client_x11_get_proto(ssh, display, 1952 options.xauth_location, options.forward_x11_trusted, 1953 options.forward_x11_timeout, &proto, &data) == 0) { 1954 /* Request forwarding with authentication spoofing. */ 1955 debug("Requesting X11 forwarding with authentication " 1956 "spoofing."); 1957 x11_request_forwarding_with_spoofing(ssh, id, display, proto, 1958 data, 1); 1959 client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN); 1960 /* XXX exit_on_forward_failure */ 1961 interactive = 1; 1962 } 1963 1964 check_agent_present(); 1965 if (options.forward_agent) { 1966 debug("Requesting authentication agent forwarding."); 1967 channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0); 1968 if ((r = sshpkt_send(ssh)) != 0) 1969 fatal_fr(r, "send packet"); 1970 } 1971 1972 /* Tell the packet module whether this is an interactive session. */ 1973 ssh_packet_set_interactive(ssh, interactive, 1974 options.ip_qos_interactive, options.ip_qos_bulk); 1975 1976 client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"), 1977 NULL, fileno(stdin), command, environ); 1978 } 1979 1980 /* open new channel for a session */ 1981 static int 1982 ssh_session2_open(struct ssh *ssh) 1983 { 1984 Channel *c; 1985 int window, packetmax, in, out, err; 1986 1987 if (stdin_null_flag) { 1988 in = open(_PATH_DEVNULL, O_RDONLY); 1989 } else { 1990 in = dup(STDIN_FILENO); 1991 } 1992 out = dup(STDOUT_FILENO); 1993 err = dup(STDERR_FILENO); 1994 1995 if (in == -1 || out == -1 || err == -1) 1996 fatal("dup() in/out/err failed"); 1997 1998 /* enable nonblocking unless tty */ 1999 if (!isatty(in)) 2000 set_nonblock(in); 2001 if (!isatty(out)) 2002 set_nonblock(out); 2003 if (!isatty(err)) 2004 set_nonblock(err); 2005 2006 window = CHAN_SES_WINDOW_DEFAULT; 2007 packetmax = CHAN_SES_PACKET_DEFAULT; 2008 if (tty_flag) { 2009 window >>= 1; 2010 packetmax >>= 1; 2011 } 2012 c = channel_new(ssh, 2013 "session", SSH_CHANNEL_OPENING, in, out, err, 2014 window, packetmax, CHAN_EXTENDED_WRITE, 2015 "client-session", /*nonblock*/0); 2016 2017 debug3_f("channel_new: %d", c->self); 2018 2019 channel_send_open(ssh, c->self); 2020 if (!no_shell_flag) 2021 channel_register_open_confirm(ssh, c->self, 2022 ssh_session2_setup, NULL); 2023 2024 return c->self; 2025 } 2026 2027 static int 2028 ssh_session2(struct ssh *ssh, struct passwd *pw) 2029 { 2030 int r, id = -1; 2031 char *cp, *tun_fwd_ifname = NULL; 2032 2033 /* XXX should be pre-session */ 2034 if (!options.control_persist) 2035 ssh_init_stdio_forwarding(ssh); 2036 2037 ssh_init_forwarding(ssh, &tun_fwd_ifname); 2038 2039 if (options.local_command != NULL) { 2040 debug3("expanding LocalCommand: %s", options.local_command); 2041 cp = options.local_command; 2042 options.local_command = percent_expand(cp, 2043 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS, 2044 "d", pw->pw_dir, 2045 "h", host, 2046 "r", options.user, 2047 "u", pw->pw_name, 2048 "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname, 2049 (char *)NULL); 2050 debug3("expanded LocalCommand: %s", options.local_command); 2051 free(cp); 2052 } 2053 2054 /* Start listening for multiplex clients */ 2055 if (!ssh_packet_get_mux(ssh)) 2056 muxserver_listen(ssh); 2057 2058 /* 2059 * If we are in control persist mode and have a working mux listen 2060 * socket, then prepare to background ourselves and have a foreground 2061 * client attach as a control client. 2062 * NB. we must save copies of the flags that we override for 2063 * the backgrounding, since we defer attachment of the client until 2064 * after the connection is fully established (in particular, 2065 * async rfwd replies have been received for ExitOnForwardFailure). 2066 */ 2067 if (options.control_persist && muxserver_sock != -1) { 2068 ostdin_null_flag = stdin_null_flag; 2069 ono_shell_flag = no_shell_flag; 2070 orequest_tty = options.request_tty; 2071 otty_flag = tty_flag; 2072 stdin_null_flag = 1; 2073 no_shell_flag = 1; 2074 tty_flag = 0; 2075 if (!fork_after_authentication_flag) 2076 need_controlpersist_detach = 1; 2077 fork_after_authentication_flag = 1; 2078 } 2079 /* 2080 * ControlPersist mux listen socket setup failed, attempt the 2081 * stdio forward setup that we skipped earlier. 2082 */ 2083 if (options.control_persist && muxserver_sock == -1) 2084 ssh_init_stdio_forwarding(ssh); 2085 2086 if (!no_shell_flag) 2087 id = ssh_session2_open(ssh); 2088 else { 2089 ssh_packet_set_interactive(ssh, 2090 options.control_master == SSHCTL_MASTER_NO, 2091 options.ip_qos_interactive, options.ip_qos_bulk); 2092 } 2093 2094 /* If we don't expect to open a new session, then disallow it */ 2095 if (options.control_master == SSHCTL_MASTER_NO && 2096 (datafellows & SSH_NEW_OPENSSH)) { 2097 debug("Requesting no-more-sessions@openssh.com"); 2098 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 2099 (r = sshpkt_put_cstring(ssh, 2100 "no-more-sessions@openssh.com")) != 0 || 2101 (r = sshpkt_put_u8(ssh, 0)) != 0 || 2102 (r = sshpkt_send(ssh)) != 0) 2103 fatal_fr(r, "send packet"); 2104 } 2105 2106 /* Execute a local command */ 2107 if (options.local_command != NULL && 2108 options.permit_local_command) 2109 ssh_local_cmd(options.local_command); 2110 2111 /* 2112 * stdout is now owned by the session channel; clobber it here 2113 * so future channel closes are propagated to the local fd. 2114 * NB. this can only happen after LocalCommand has completed, 2115 * as it may want to write to stdout. 2116 */ 2117 if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1) 2118 error_f("stdfd_devnull failed"); 2119 2120 /* 2121 * If requested and we are not interested in replies to remote 2122 * forwarding requests, then let ssh continue in the background. 2123 */ 2124 if (fork_after_authentication_flag) { 2125 if (options.exit_on_forward_failure && 2126 options.num_remote_forwards > 0) { 2127 debug("deferring postauth fork until remote forward " 2128 "confirmation received"); 2129 } else 2130 fork_postauth(); 2131 } 2132 2133 return client_loop(ssh, tty_flag, tty_flag ? 2134 options.escape_char : SSH_ESCAPECHAR_NONE, id); 2135 } 2136 2137 /* Loads all IdentityFile and CertificateFile keys */ 2138 static void 2139 load_public_identity_files(struct passwd *pw) 2140 { 2141 char *filename, *cp; 2142 struct sshkey *public; 2143 int i; 2144 u_int n_ids, n_certs; 2145 char *identity_files[SSH_MAX_IDENTITY_FILES]; 2146 struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES]; 2147 int identity_file_userprovided[SSH_MAX_IDENTITY_FILES]; 2148 char *certificate_files[SSH_MAX_CERTIFICATE_FILES]; 2149 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES]; 2150 int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES]; 2151 #ifdef ENABLE_PKCS11 2152 struct sshkey **keys = NULL; 2153 char **comments = NULL; 2154 int nkeys; 2155 #endif /* PKCS11 */ 2156 2157 n_ids = n_certs = 0; 2158 memset(identity_files, 0, sizeof(identity_files)); 2159 memset(identity_keys, 0, sizeof(identity_keys)); 2160 memset(identity_file_userprovided, 0, 2161 sizeof(identity_file_userprovided)); 2162 memset(certificate_files, 0, sizeof(certificate_files)); 2163 memset(certificates, 0, sizeof(certificates)); 2164 memset(certificate_file_userprovided, 0, 2165 sizeof(certificate_file_userprovided)); 2166 2167 #ifdef ENABLE_PKCS11 2168 if (options.pkcs11_provider != NULL && 2169 options.num_identity_files < SSH_MAX_IDENTITY_FILES && 2170 (pkcs11_init(!options.batch_mode) == 0) && 2171 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL, 2172 &keys, &comments)) > 0) { 2173 for (i = 0; i < nkeys; i++) { 2174 if (n_ids >= SSH_MAX_IDENTITY_FILES) { 2175 sshkey_free(keys[i]); 2176 free(comments[i]); 2177 continue; 2178 } 2179 identity_keys[n_ids] = keys[i]; 2180 identity_files[n_ids] = comments[i]; /* transferred */ 2181 n_ids++; 2182 } 2183 free(keys); 2184 free(comments); 2185 } 2186 #endif /* ENABLE_PKCS11 */ 2187 for (i = 0; i < options.num_identity_files; i++) { 2188 if (n_ids >= SSH_MAX_IDENTITY_FILES || 2189 strcasecmp(options.identity_files[i], "none") == 0) { 2190 free(options.identity_files[i]); 2191 options.identity_files[i] = NULL; 2192 continue; 2193 } 2194 cp = tilde_expand_filename(options.identity_files[i], getuid()); 2195 filename = default_client_percent_dollar_expand(cp, 2196 pw->pw_dir, host, options.user, pw->pw_name); 2197 free(cp); 2198 check_load(sshkey_load_public(filename, &public, NULL), 2199 filename, "pubkey"); 2200 debug("identity file %s type %d", filename, 2201 public ? public->type : -1); 2202 free(options.identity_files[i]); 2203 identity_files[n_ids] = filename; 2204 identity_keys[n_ids] = public; 2205 identity_file_userprovided[n_ids] = 2206 options.identity_file_userprovided[i]; 2207 if (++n_ids >= SSH_MAX_IDENTITY_FILES) 2208 continue; 2209 2210 /* 2211 * If no certificates have been explicitly listed then try 2212 * to add the default certificate variant too. 2213 */ 2214 if (options.num_certificate_files != 0) 2215 continue; 2216 xasprintf(&cp, "%s-cert", filename); 2217 check_load(sshkey_load_public(cp, &public, NULL), 2218 filename, "pubkey"); 2219 debug("identity file %s type %d", cp, 2220 public ? public->type : -1); 2221 if (public == NULL) { 2222 free(cp); 2223 continue; 2224 } 2225 if (!sshkey_is_cert(public)) { 2226 debug_f("key %s type %s is not a certificate", 2227 cp, sshkey_type(public)); 2228 sshkey_free(public); 2229 free(cp); 2230 continue; 2231 } 2232 /* NB. leave filename pointing to private key */ 2233 identity_files[n_ids] = xstrdup(filename); 2234 identity_keys[n_ids] = public; 2235 identity_file_userprovided[n_ids] = 2236 options.identity_file_userprovided[i]; 2237 n_ids++; 2238 } 2239 2240 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES) 2241 fatal_f("too many certificates"); 2242 for (i = 0; i < options.num_certificate_files; i++) { 2243 cp = tilde_expand_filename(options.certificate_files[i], 2244 getuid()); 2245 filename = default_client_percent_dollar_expand(cp, 2246 pw->pw_dir, host, options.user, pw->pw_name); 2247 free(cp); 2248 2249 check_load(sshkey_load_public(filename, &public, NULL), 2250 filename, "certificate"); 2251 debug("certificate file %s type %d", filename, 2252 public ? public->type : -1); 2253 free(options.certificate_files[i]); 2254 options.certificate_files[i] = NULL; 2255 if (public == NULL) { 2256 free(filename); 2257 continue; 2258 } 2259 if (!sshkey_is_cert(public)) { 2260 debug_f("key %s type %s is not a certificate", 2261 filename, sshkey_type(public)); 2262 sshkey_free(public); 2263 free(filename); 2264 continue; 2265 } 2266 certificate_files[n_certs] = filename; 2267 certificates[n_certs] = public; 2268 certificate_file_userprovided[n_certs] = 2269 options.certificate_file_userprovided[i]; 2270 ++n_certs; 2271 } 2272 2273 options.num_identity_files = n_ids; 2274 memcpy(options.identity_files, identity_files, sizeof(identity_files)); 2275 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys)); 2276 memcpy(options.identity_file_userprovided, 2277 identity_file_userprovided, sizeof(identity_file_userprovided)); 2278 2279 options.num_certificate_files = n_certs; 2280 memcpy(options.certificate_files, 2281 certificate_files, sizeof(certificate_files)); 2282 memcpy(options.certificates, certificates, sizeof(certificates)); 2283 memcpy(options.certificate_file_userprovided, 2284 certificate_file_userprovided, 2285 sizeof(certificate_file_userprovided)); 2286 } 2287 2288 static void 2289 main_sigchld_handler(int sig) 2290 { 2291 int save_errno = errno; 2292 pid_t pid; 2293 int status; 2294 2295 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 || 2296 (pid == -1 && errno == EINTR)) 2297 ; 2298 errno = save_errno; 2299 } 2300