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