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