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