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