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