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