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