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