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