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