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