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