xref: /freebsd/crypto/openssh/ssh.c (revision f5dc2263ab1be8a35a7e27e82103f9ccd41ae584)
1 /* $OpenBSD: ssh.c,v 1.634 2026/07/06 07:49:58 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 SSLeay 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 
45 #include <sys/types.h>
46 #include <sys/socket.h>
47 #include <sys/stat.h>
48 #include <sys/wait.h>
49 #include <sys/utsname.h>
50 
51 #include <ctype.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <netdb.h>
55 #include <paths.h>
56 #include <pwd.h>
57 #include <signal.h>
58 #include <stdarg.h>
59 #include <stddef.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 #include <limits.h>
65 #include <locale.h>
66 
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69 
70 #ifdef WITH_OPENSSL
71 #include <openssl/evp.h>
72 #include <openssl/err.h>
73 #endif
74 #include "openbsd-compat/openssl-compat.h"
75 
76 #include "xmalloc.h"
77 #include "ssh.h"
78 #include "ssh2.h"
79 #include "compat.h"
80 #include "cipher.h"
81 #include "packet.h"
82 #include "sshbuf.h"
83 #include "channels.h"
84 #include "sshkey.h"
85 #include "authfd.h"
86 #include "authfile.h"
87 #include "pathnames.h"
88 #include "clientloop.h"
89 #include "log.h"
90 #include "misc.h"
91 #include "readconf.h"
92 #include "sshconnect.h"
93 #include "kex.h"
94 #include "mac.h"
95 #include "match.h"
96 #include "version.h"
97 #include "ssherr.h"
98 #include "utf8.h"
99 
100 #ifdef ENABLE_PKCS11
101 #include "ssh-pkcs11.h"
102 #endif
103 
104 extern char *__progname;
105 
106 /* Saves a copy of argv for setproctitle emulation */
107 #ifndef HAVE_SETPROCTITLE
108 static char **saved_av;
109 #endif
110 
111 /* Flag indicating whether debug mode is on.  May be set on the command line. */
112 int debug_flag = 0;
113 
114 /* Flag indicating whether a tty should be requested */
115 int tty_flag = 0;
116 
117 /*
118  * Flag indicating that the current process should be backgrounded and
119  * a new mux-client launched in the foreground for ControlPersist.
120  */
121 static int need_controlpersist_detach = 0;
122 
123 /* Copies of flags for ControlPersist foreground mux-client */
124 static int ostdin_null_flag, osession_type, otty_flag, orequest_tty;
125 static int ofork_after_authentication;
126 
127 /*
128  * General data structure for command line options and options configurable
129  * in configuration files.  See readconf.h.
130  */
131 Options options;
132 
133 /* optional user configfile */
134 char *config = NULL;
135 
136 /*
137  * Name of the host we are connecting to.  This is the name given on the
138  * command line, or the Hostname specified for the user-supplied name in a
139  * configuration file.
140  */
141 char *host;
142 
143 /*
144  * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is
145  * not NULL, forward the socket at this path instead.
146  */
147 char *forward_agent_sock_path = NULL;
148 
149 /* socket address the host resolves to */
150 struct sockaddr_storage hostaddr;
151 
152 /* Private host keys. */
153 Sensitive sensitive_data;
154 
155 /* command to be executed */
156 struct sshbuf *command;
157 
158 /* # of replies received for global requests */
159 static int forward_confirms_pending = -1;
160 
161 /* mux.c */
162 extern int muxserver_sock;
163 extern u_int muxclient_command;
164 
165 /* Prints a help message to the user.  This function never returns. */
166 
167 static void
168 usage(void)
169 {
170 	fprintf(stderr,
171 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address]\n"
172 "           [-c cipher_spec] [-D [bind_address:]port] [-E log_file]\n"
173 "           [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file]\n"
174 "           [-J destination] [-L address] [-l login_name] [-m mac_spec]\n"
175 "           [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address]\n"
176 "           [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
177 "           destination [command [argument ...]]\n"
178 "       ssh [-Q query_option]\n"
179 	);
180 	exit(255);
181 }
182 
183 static int ssh_session2(struct ssh *, const struct ssh_conn_info *);
184 static void load_public_identity_files(const struct ssh_conn_info *);
185 static void main_sigchld_handler(int);
186 
187 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
188 static void
189 tilde_expand_paths(char **paths, u_int num_paths)
190 {
191 	u_int i;
192 	char *cp;
193 
194 	for (i = 0; i < num_paths; i++) {
195 		cp = tilde_expand_filename(paths[i], getuid());
196 		free(paths[i]);
197 		paths[i] = cp;
198 	}
199 }
200 
201 /*
202  * Expands the set of percent_expand options used by the majority of keywords
203  * in the client that support percent expansion.
204  * Caller must free returned string.
205  */
206 static char *
207 default_client_percent_expand(const char *str,
208     const struct ssh_conn_info *cinfo)
209 {
210 	return percent_expand(str,
211 	    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
212 	    (char *)NULL);
213 }
214 
215 /*
216  * Expands the set of percent_expand options used by the majority of keywords
217  * AND perform environment variable substitution.
218  * Caller must free returned string.
219  */
220 static char *
221 default_client_percent_dollar_expand(const char *str,
222     const struct ssh_conn_info *cinfo)
223 {
224 	char *ret;
225 
226 	ret = percent_dollar_expand(str,
227 	    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
228 	    (char *)NULL);
229 	if (ret == NULL)
230 		fatal("invalid environment variable expansion");
231 	return ret;
232 }
233 
234 /*
235  * Attempt to resolve a host name / port to a set of addresses and
236  * optionally return any CNAMEs encountered along the way.
237  * Returns NULL on failure.
238  * NB. this function must operate with a options having undefined members.
239  */
240 static struct addrinfo *
241 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
242 {
243 	char strport[NI_MAXSERV];
244 	const char *errstr = NULL;
245 	struct addrinfo hints, *res;
246 	int gaierr;
247 	LogLevel loglevel = SYSLOG_LEVEL_DEBUG1;
248 
249 	if (port <= 0)
250 		port = default_ssh_port();
251 	if (cname != NULL)
252 		*cname = '\0';
253 	debug3_f("lookup %s:%d", name, port);
254 
255 	snprintf(strport, sizeof strport, "%d", port);
256 	memset(&hints, 0, sizeof(hints));
257 	hints.ai_family = options.address_family == -1 ?
258 	    AF_UNSPEC : options.address_family;
259 	hints.ai_socktype = SOCK_STREAM;
260 	if (cname != NULL)
261 		hints.ai_flags = AI_CANONNAME;
262 	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
263 		if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
264 			loglevel = SYSLOG_LEVEL_ERROR;
265 		do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
266 		    __progname, name, ssh_gai_strerror(gaierr));
267 		return NULL;
268 	}
269 	if (cname != NULL && res->ai_canonname != NULL) {
270 		if (!valid_domain(res->ai_canonname, 0, &errstr)) {
271 			error("ignoring bad CNAME \"%s\" for host \"%s\": %s",
272 			    res->ai_canonname, name, errstr);
273 		} else if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
274 			error_f("host \"%s\" cname \"%s\" too long (max %lu)",
275 			    name,  res->ai_canonname, (u_long)clen);
276 			if (clen > 0)
277 				*cname = '\0';
278 		}
279 	}
280 	return res;
281 }
282 
283 /* Returns non-zero if name can only be an address and not a hostname */
284 static int
285 is_addr_fast(const char *name)
286 {
287 	return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
288 	    strspn(name, "0123456789.") == strlen(name));
289 }
290 
291 /* Returns non-zero if name represents a valid, single address */
292 static int
293 is_addr(const char *name)
294 {
295 	char strport[NI_MAXSERV];
296 	struct addrinfo hints, *res;
297 
298 	if (is_addr_fast(name))
299 		return 1;
300 
301 	snprintf(strport, sizeof strport, "%u", default_ssh_port());
302 	memset(&hints, 0, sizeof(hints));
303 	hints.ai_family = options.address_family == -1 ?
304 	    AF_UNSPEC : options.address_family;
305 	hints.ai_socktype = SOCK_STREAM;
306 	hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
307 	if (getaddrinfo(name, strport, &hints, &res) != 0)
308 		return 0;
309 	if (res == NULL || res->ai_next != NULL) {
310 		freeaddrinfo(res);
311 		return 0;
312 	}
313 	freeaddrinfo(res);
314 	return 1;
315 }
316 
317 /*
318  * Attempt to resolve a numeric host address / port to a single address.
319  * Returns a canonical address string.
320  * Returns NULL on failure.
321  * NB. this function must operate with a options having undefined members.
322  */
323 static struct addrinfo *
324 resolve_addr(const char *name, int port, char *caddr, size_t clen)
325 {
326 	char addr[NI_MAXHOST], strport[NI_MAXSERV];
327 	struct addrinfo hints, *res;
328 	int gaierr;
329 
330 	if (port <= 0)
331 		port = default_ssh_port();
332 	snprintf(strport, sizeof strport, "%u", port);
333 	memset(&hints, 0, sizeof(hints));
334 	hints.ai_family = options.address_family == -1 ?
335 	    AF_UNSPEC : options.address_family;
336 	hints.ai_socktype = SOCK_STREAM;
337 	hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
338 	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
339 		debug2_f("could not resolve name %.100s as address: %s",
340 		    name, ssh_gai_strerror(gaierr));
341 		return NULL;
342 	}
343 	if (res == NULL) {
344 		debug_f("getaddrinfo %.100s returned no addresses", name);
345 		return NULL;
346 	}
347 	if (res->ai_next != NULL) {
348 		debug_f("getaddrinfo %.100s returned multiple addresses", name);
349 		goto fail;
350 	}
351 	if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
352 	    addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
353 		debug_f("Could not format address for name %.100s: %s",
354 		    name, ssh_gai_strerror(gaierr));
355 		goto fail;
356 	}
357 	if (strlcpy(caddr, addr, clen) >= clen) {
358 		error_f("host \"%s\" addr \"%s\" too long (max %lu)",
359 		    name,  addr, (u_long)clen);
360 		if (clen > 0)
361 			*caddr = '\0';
362  fail:
363 		freeaddrinfo(res);
364 		return NULL;
365 	}
366 	return res;
367 }
368 
369 /*
370  * Check whether the cname is a permitted replacement for the hostname
371  * and perform the replacement if it is.
372  * NB. this function must operate with a options having undefined members.
373  */
374 static int
375 check_follow_cname(int direct, char **namep, const char *cname)
376 {
377 	int i;
378 	struct allowed_cname *rule;
379 
380 	if (*cname == '\0' || !config_has_permitted_cnames(&options) ||
381 	    strcmp(*namep, cname) == 0)
382 		return 0;
383 	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
384 		return 0;
385 	/*
386 	 * Don't attempt to canonicalize names that will be interpreted by
387 	 * a proxy or jump host unless the user specifically requests so.
388 	 */
389 	if (!direct &&
390 	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
391 		return 0;
392 	debug3_f("check \"%s\" CNAME \"%s\"", *namep, cname);
393 	for (i = 0; i < options.num_permitted_cnames; i++) {
394 		rule = options.permitted_cnames + i;
395 		if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
396 		    match_pattern_list(cname, rule->target_list, 1) != 1)
397 			continue;
398 		verbose("Canonicalized DNS aliased hostname "
399 		    "\"%s\" => \"%s\"", *namep, cname);
400 		free(*namep);
401 		*namep = xstrdup(cname);
402 		lowercase(*namep);
403 		return 1;
404 	}
405 	return 0;
406 }
407 
408 /*
409  * Attempt to resolve the supplied hostname after applying the user's
410  * canonicalization rules. Returns the address list for the host or NULL
411  * if no name was found after canonicalization.
412  * NB. this function must operate with a options having undefined members.
413  */
414 static struct addrinfo *
415 resolve_canonicalize(char **hostp, int port)
416 {
417 	int i, direct, ndots;
418 	char *cp, *fullhost, newname[NI_MAXHOST];
419 	struct addrinfo *addrs;
420 
421 	/*
422 	 * Attempt to canonicalise addresses, regardless of
423 	 * whether hostname canonicalisation was requested
424 	 */
425 	if ((addrs = resolve_addr(*hostp, port,
426 	    newname, sizeof(newname))) != NULL) {
427 		debug2_f("hostname %.100s is address", *hostp);
428 		if (strcasecmp(*hostp, newname) != 0) {
429 			debug2_f("canonicalised address \"%s\" => \"%s\"",
430 			    *hostp, newname);
431 			free(*hostp);
432 			*hostp = xstrdup(newname);
433 		}
434 		return addrs;
435 	}
436 
437 	/*
438 	 * If this looks like an address but didn't parse as one, it might
439 	 * be an address with an invalid interface scope. Skip further
440 	 * attempts at canonicalisation.
441 	 */
442 	if (is_addr_fast(*hostp)) {
443 		debug_f("hostname %.100s is an unrecognised address", *hostp);
444 		return NULL;
445 	}
446 
447 	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
448 		return NULL;
449 
450 	/*
451 	 * Don't attempt to canonicalize names that will be interpreted by
452 	 * a proxy unless the user specifically requests so.
453 	 */
454 	direct = option_clear_or_none(options.proxy_command) &&
455 	    option_clear_or_none(options.jump_host);
456 	if (!direct &&
457 	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
458 		return NULL;
459 
460 	/* If domain name is anchored, then resolve it now */
461 	if ((*hostp)[strlen(*hostp) - 1] == '.') {
462 		debug3_f("name is fully qualified");
463 		fullhost = xstrdup(*hostp);
464 		if ((addrs = resolve_host(fullhost, port, 0,
465 		    newname, sizeof(newname))) != NULL)
466 			goto found;
467 		free(fullhost);
468 		goto notfound;
469 	}
470 
471 	/* Don't apply canonicalization to sufficiently-qualified hostnames */
472 	ndots = 0;
473 	for (cp = *hostp; *cp != '\0'; cp++) {
474 		if (*cp == '.')
475 			ndots++;
476 	}
477 	if (ndots > options.canonicalize_max_dots) {
478 		debug3_f("not canonicalizing hostname \"%s\" (max dots %d)",
479 		    *hostp, options.canonicalize_max_dots);
480 		return NULL;
481 	}
482 	/* Attempt each supplied suffix */
483 	for (i = 0; i < options.num_canonical_domains; i++) {
484 		if (strcasecmp(options.canonical_domains[i], "none") == 0)
485 			break;
486 		xasprintf(&fullhost, "%s.%s.", *hostp,
487 		    options.canonical_domains[i]);
488 		debug3_f("attempting \"%s\" => \"%s\"", *hostp, fullhost);
489 		if ((addrs = resolve_host(fullhost, port, 0,
490 		    newname, sizeof(newname))) == NULL) {
491 			free(fullhost);
492 			continue;
493 		}
494  found:
495 		/* Remove trailing '.' */
496 		fullhost[strlen(fullhost) - 1] = '\0';
497 		/* Follow CNAME if requested */
498 		if (!check_follow_cname(direct, &fullhost, newname)) {
499 			debug("Canonicalized hostname \"%s\" => \"%s\"",
500 			    *hostp, fullhost);
501 		}
502 		free(*hostp);
503 		*hostp = fullhost;
504 		return addrs;
505 	}
506  notfound:
507 	if (!options.canonicalize_fallback_local)
508 		fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
509 	debug2_f("host %s not found in any suffix", *hostp);
510 	return NULL;
511 }
512 
513 /*
514  * Check the result of hostkey loading, ignoring some errors and either
515  * discarding the key or fatal()ing for others.
516  */
517 static void
518 check_load(int r, struct sshkey **k, const char *path, const char *message)
519 {
520 	char *fp;
521 
522 	switch (r) {
523 	case 0:
524 		if (k == NULL || *k == NULL)
525 			return;
526 		/* Check RSA keys size and discard if undersized */
527 		if ((r = sshkey_check_rsa_length(*k,
528 		    options.required_rsa_size)) != 0) {
529 			error_r(r, "load %s \"%s\"", message, path);
530 			free(*k);
531 			*k = NULL;
532 			break;
533 		}
534 		if ((fp = sshkey_fingerprint(*k,
535 		    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
536 			fatal_f("failed to fingerprint %s %s key from %s",
537 			    sshkey_type(*k), message, path);
538 		}
539 		debug("loaded %s from %s: %s %s", message, path,
540 		    sshkey_type(*k), fp);
541 		free(fp);
542 		break;
543 	case SSH_ERR_INTERNAL_ERROR:
544 	case SSH_ERR_ALLOC_FAIL:
545 		fatal_r(r, "load %s \"%s\"", message, path);
546 	case SSH_ERR_SYSTEM_ERROR:
547 		/* Ignore missing files */
548 		if (errno == ENOENT)
549 			break;
550 		/* FALLTHROUGH */
551 	default:
552 		error_r(r, "load %s \"%s\"", message, path);
553 		break;
554 	}
555 	if (k != NULL && *k == NULL)
556 		debug("no %s loaded from %s", message, path);
557 }
558 
559 /*
560  * Read per-user configuration file.  Ignore the system wide config
561  * file if the user specifies a config file on the command line.
562  */
563 static void
564 process_config_files(const char *host_name, struct passwd *pw,
565     int final_pass, int *want_final_pass)
566 {
567 	char *cmd, buf[PATH_MAX];
568 	int r;
569 
570 	if ((cmd = sshbuf_dup_string(command)) == NULL)
571 		fatal_f("sshbuf_dup_string failed");
572 	if (config != NULL) {
573 		if (strcasecmp(config, "none") != 0 &&
574 		    !read_config_file(config, pw, host, host_name, cmd,
575 		    &options,
576 		    SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0),
577 		    want_final_pass))
578 			fatal("Can't open user config file %.100s: "
579 			    "%.100s", config, strerror(errno));
580 	} else {
581 		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
582 		    _PATH_SSH_USER_CONFFILE);
583 		if (r > 0 && (size_t)r < sizeof(buf))
584 			(void)read_config_file(buf, pw, host, host_name, cmd,
585 			    &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
586 			    (final_pass ? SSHCONF_FINAL : 0), want_final_pass);
587 
588 		/* Read systemwide configuration file after user config. */
589 		(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
590 		    host, host_name, cmd, &options,
591 		    final_pass ? SSHCONF_FINAL : 0, want_final_pass);
592 	}
593 	free(cmd);
594 }
595 
596 /* Rewrite the port number in an addrinfo list of addresses */
597 static void
598 set_addrinfo_port(struct addrinfo *addrs, int port)
599 {
600 	struct addrinfo *addr;
601 
602 	for (addr = addrs; addr != NULL; addr = addr->ai_next) {
603 		switch (addr->ai_family) {
604 		case AF_INET:
605 			((struct sockaddr_in *)addr->ai_addr)->
606 			    sin_port = htons(port);
607 			break;
608 		case AF_INET6:
609 			((struct sockaddr_in6 *)addr->ai_addr)->
610 			    sin6_port = htons(port);
611 			break;
612 		}
613 	}
614 }
615 
616 /*
617  * Main program for the ssh client.
618  */
619 int
620 main(int ac, char **av)
621 {
622 	struct ssh *ssh = NULL;
623 	int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
624 	int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
625 	int user_on_commandline = 0, user_was_default = 0, user_expanded = 0;
626 	char *p, *cp, *line, *argv0, *logfile, *args;
627 	char cname[NI_MAXHOST], thishost[NI_MAXHOST];
628 	struct stat st;
629 	struct passwd *pw;
630 	extern int optind, optreset;
631 	extern char *optarg;
632 	struct Forward fwd;
633 	struct addrinfo *addrs = NULL;
634 	size_t n, len;
635 	u_int j;
636 	struct utsname utsname;
637 	struct ssh_conn_info *cinfo = NULL;
638 
639 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
640 	sanitise_stdfd();
641 
642 	/*
643 	 * Discard other fds that are hanging around. These can cause problem
644 	 * with backgrounded ssh processes started by ControlPersist.
645 	 */
646 	closefrom(STDERR_FILENO + 1);
647 
648 	__progname = ssh_get_progname(av[0]);
649 
650 #ifndef HAVE_SETPROCTITLE
651 	/* Prepare for later setproctitle emulation */
652 	/* Save argv so it isn't clobbered by setproctitle() emulation */
653 	saved_av = xcalloc(ac + 1, sizeof(*saved_av));
654 	for (i = 0; i < ac; i++)
655 		saved_av[i] = xstrdup(av[i]);
656 	saved_av[i] = NULL;
657 	compat_init_setproctitle(ac, av);
658 	av = saved_av;
659 #endif
660 
661 	seed_rng();
662 
663 	/* Get user data. */
664 	pw = getpwuid(getuid());
665 	if (!pw) {
666 		logit("No user exists for uid %lu", (u_long)getuid());
667 		exit(255);
668 	}
669 	/* Take a copy of the returned structure. */
670 	pw = pwcopy(pw);
671 
672 	/*
673 	 * Set our umask to something reasonable, as some files are created
674 	 * with the default umask.  This will make them world-readable but
675 	 * writable only by the owner, which is ok for all files for which we
676 	 * don't set the modes explicitly.
677 	 */
678 	umask(022 | umask(077));
679 
680 	msetlocale();
681 
682 	/*
683 	 * Initialize option structure to indicate that no values have been
684 	 * set.
685 	 */
686 	initialize_options(&options);
687 
688 	/*
689 	 * Prepare main ssh transport/connection structures
690 	 */
691 	if ((ssh = ssh_alloc_session_state()) == NULL)
692 		fatal("Couldn't allocate session state");
693 	channel_init_channels(ssh);
694 
695 	/* Parse command-line arguments. */
696 	args = argv_assemble(ac, av); /* logged later */
697 	host = NULL;
698 	use_syslog = 0;
699 	logfile = NULL;
700 	argv0 = av[0];
701 
702  again:
703 	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
704 	    "AB:CD:E:F:GI:J:KL:MNO:P:Q:R:S:TVw:W:XYy")) != -1) { /* HUZdhjruz */
705 		switch (opt) {
706 		case '1':
707 			fatal("SSH protocol v.1 is no longer supported");
708 			break;
709 		case '2':
710 			/* Ignored */
711 			break;
712 		case '4':
713 			options.address_family = AF_INET;
714 			break;
715 		case '6':
716 			options.address_family = AF_INET6;
717 			break;
718 		case 'n':
719 			options.stdin_null = 1;
720 			break;
721 		case 'f':
722 			options.fork_after_authentication = 1;
723 			options.stdin_null = 1;
724 			break;
725 		case 'x':
726 			options.forward_x11 = 0;
727 			break;
728 		case 'X':
729 			options.forward_x11 = 1;
730 			break;
731 		case 'y':
732 			use_syslog = 1;
733 			break;
734 		case 'E':
735 			logfile = optarg;
736 			break;
737 		case 'G':
738 			config_test = 1;
739 			break;
740 		case 'Y':
741 			options.forward_x11 = 1;
742 			options.forward_x11_trusted = 1;
743 			break;
744 		case 'g':
745 			options.fwd_opts.gateway_ports = 1;
746 			break;
747 		case 'O':
748 			if (options.stdio_forward_host != NULL)
749 				fatal("Cannot specify multiplexing "
750 				    "command with -W");
751 			else if (muxclient_command != 0)
752 				fatal("Multiplexing command already specified");
753 			if (strcmp(optarg, "check") == 0)
754 				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
755 			else if (strcmp(optarg, "conninfo") == 0)
756 				muxclient_command = SSHMUX_COMMAND_CONNINFO;
757 			else if (strcmp(optarg, "channels") == 0)
758 				muxclient_command = SSHMUX_COMMAND_CHANINFO;
759 			else if (strcmp(optarg, "forward") == 0)
760 				muxclient_command = SSHMUX_COMMAND_FORWARD;
761 			else if (strcmp(optarg, "exit") == 0)
762 				muxclient_command = SSHMUX_COMMAND_TERMINATE;
763 			else if (strcmp(optarg, "stop") == 0)
764 				muxclient_command = SSHMUX_COMMAND_STOP;
765 			else if (strcmp(optarg, "cancel") == 0)
766 				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
767 			else if (strcmp(optarg, "proxy") == 0)
768 				muxclient_command = SSHMUX_COMMAND_PROXY;
769 			else
770 				fatal("Invalid multiplex command.");
771 			break;
772 		case 'P':
773 			if (options.tag == NULL)
774 				options.tag = xstrdup(optarg);
775 			break;
776 		case 'Q':
777 			cp = NULL;
778 			if (strcmp(optarg, "cipher") == 0 ||
779 			    strcasecmp(optarg, "Ciphers") == 0)
780 				cp = cipher_alg_list('\n', 0);
781 			else if (strcmp(optarg, "cipher-auth") == 0)
782 				cp = cipher_alg_list('\n', 1);
783 			else if (strcmp(optarg, "mac") == 0 ||
784 			    strcasecmp(optarg, "MACs") == 0)
785 				cp = mac_alg_list('\n');
786 			else if (strcmp(optarg, "kex") == 0 ||
787 			    strcasecmp(optarg, "KexAlgorithms") == 0)
788 				cp = kex_alg_list('\n');
789 			else if (strcmp(optarg, "key") == 0)
790 				cp = sshkey_alg_list(0, 0, 0, '\n');
791 			else if (strcmp(optarg, "key-cert") == 0)
792 				cp = sshkey_alg_list(1, 0, 0, '\n');
793 			else if (strcmp(optarg, "key-plain") == 0)
794 				cp = sshkey_alg_list(0, 1, 0, '\n');
795 			else if (strcmp(optarg, "key-ca-sign") == 0 ||
796 			    strcasecmp(optarg, "CASignatureAlgorithms") == 0)
797 				cp = sshkey_alg_list(0, 1, 1, '\n');
798 			else if (strcmp(optarg, "key-sig") == 0 ||
799 			    strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
800 			    strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
801 			    strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
802 			    strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
803 			    strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
804 			    strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
805 				cp = sshkey_alg_list(0, 0, 1, '\n');
806 			else if (strcmp(optarg, "sig") == 0)
807 				cp = sshkey_alg_list(0, 1, 1, '\n');
808 			else if (strcmp(optarg, "protocol-version") == 0)
809 				cp = xstrdup("2");
810 			else if (strcmp(optarg, "compression") == 0) {
811 				cp = xstrdup(compression_alg_list(0));
812 				len = strlen(cp);
813 				for (n = 0; n < len; n++)
814 					if (cp[n] == ',')
815 						cp[n] = '\n';
816 			} else if (strcmp(optarg, "help") == 0) {
817 				cp = xstrdup(
818 				    "cipher\ncipher-auth\ncompression\nkex\n"
819 				    "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
820 				    "protocol-version\nsig");
821 			}
822 			if (cp == NULL)
823 				fatal("Unsupported query \"%s\"", optarg);
824 			printf("%s\n", cp);
825 			free(cp);
826 			exit(0);
827 			break;
828 		case 'a':
829 			options.forward_agent = 0;
830 			break;
831 		case 'A':
832 			options.forward_agent = 1;
833 			break;
834 		case 'k':
835 			options.gss_deleg_creds = 0;
836 			break;
837 		case 'K':
838 			options.gss_authentication = 1;
839 			options.gss_deleg_creds = 1;
840 			break;
841 		case 'i':
842 			p = tilde_expand_filename(optarg, getuid());
843 			if (stat(p, &st) == -1)
844 				fprintf(stderr, "Warning: Identity file %s "
845 				    "not accessible: %s.\n", p,
846 				    strerror(errno));
847 			else
848 				add_identity_file(&options, NULL, p, 1);
849 			free(p);
850 			break;
851 		case 'I':
852 #ifdef ENABLE_PKCS11
853 			free(options.pkcs11_provider);
854 			options.pkcs11_provider = xstrdup(optarg);
855 #else
856 			fprintf(stderr, "no support for PKCS#11.\n");
857 #endif
858 			break;
859 		case 'J':
860 			if (options.jump_host != NULL) {
861 				fatal("Only a single -J option is permitted "
862 				    "(use commas to separate multiple "
863 				    "jump hops)");
864 			}
865 			if (options.proxy_command != NULL)
866 				fatal("Cannot specify -J with ProxyCommand");
867 			if (parse_jump(optarg, &options, 1, 1) == -1)
868 
869 				fatal("Invalid -J argument");
870 			break;
871 		case 't':
872 			if (options.request_tty == REQUEST_TTY_YES)
873 				options.request_tty = REQUEST_TTY_FORCE;
874 			else
875 				options.request_tty = REQUEST_TTY_YES;
876 			break;
877 		case 'v':
878 			if (debug_flag == 0) {
879 				debug_flag = 1;
880 				options.log_level = SYSLOG_LEVEL_DEBUG1;
881 			} else {
882 				if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
883 					debug_flag++;
884 					options.log_level++;
885 				}
886 			}
887 			break;
888 		case 'V':
889 			fprintf(stderr, "%s, %s\n",
890 			    SSH_RELEASE, SSH_OPENSSL_VERSION);
891 			exit(0);
892 			break;
893 		case 'w':
894 			if (options.tun_open == -1)
895 				options.tun_open = SSH_TUNMODE_DEFAULT;
896 			options.tun_local = a2tun(optarg, &options.tun_remote);
897 			if (options.tun_local == SSH_TUNID_ERR) {
898 				fprintf(stderr,
899 				    "Bad tun device '%s'\n", optarg);
900 				exit(255);
901 			}
902 			break;
903 		case 'W':
904 			if (options.stdio_forward_host != NULL)
905 				fatal("stdio forward already specified");
906 			if (muxclient_command != 0)
907 				fatal("Cannot specify stdio forward with -O");
908 			if (parse_forward(&fwd, optarg, 1, 0)) {
909 				options.stdio_forward_host =
910 				    fwd.listen_port == PORT_STREAMLOCAL ?
911 				    fwd.listen_path : fwd.listen_host;
912 				options.stdio_forward_port = fwd.listen_port;
913 				free(fwd.connect_host);
914 			} else {
915 				fprintf(stderr,
916 				    "Bad stdio forwarding specification '%s'\n",
917 				    optarg);
918 				exit(255);
919 			}
920 			options.request_tty = REQUEST_TTY_NO;
921 			options.session_type = SESSION_TYPE_NONE;
922 			break;
923 		case 'q':
924 			options.log_level = SYSLOG_LEVEL_QUIET;
925 			break;
926 		case 'e':
927 			if (strlen(optarg) == 2 && optarg[0] == '^' &&
928 			    (u_char) optarg[1] >= 64 &&
929 			    (u_char) optarg[1] < 128)
930 				options.escape_char = (u_char) optarg[1] & 31;
931 			else if (strlen(optarg) == 1)
932 				options.escape_char = (u_char) optarg[0];
933 			else if (strcmp(optarg, "none") == 0)
934 				options.escape_char = SSH_ESCAPECHAR_NONE;
935 			else {
936 				fprintf(stderr, "Bad escape character '%s'.\n",
937 				    optarg);
938 				exit(255);
939 			}
940 			break;
941 		case 'c':
942 			if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
943 			    optarg + 1 : optarg)) {
944 				fprintf(stderr, "Unknown cipher type '%s'\n",
945 				    optarg);
946 				exit(255);
947 			}
948 			free(options.ciphers);
949 			options.ciphers = xstrdup(optarg);
950 			break;
951 		case 'm':
952 			if (mac_valid(optarg)) {
953 				free(options.macs);
954 				options.macs = xstrdup(optarg);
955 			} else {
956 				fprintf(stderr, "Unknown mac type '%s'\n",
957 				    optarg);
958 				exit(255);
959 			}
960 			break;
961 		case 'M':
962 			if (options.control_master == SSHCTL_MASTER_YES)
963 				options.control_master = SSHCTL_MASTER_ASK;
964 			else
965 				options.control_master = SSHCTL_MASTER_YES;
966 			break;
967 		case 'p':
968 			if (options.port == -1) {
969 				options.port = a2port(optarg);
970 				if (options.port <= 0) {
971 					fprintf(stderr, "Bad port '%s'\n",
972 					    optarg);
973 					exit(255);
974 				}
975 			}
976 			break;
977 		case 'l':
978 			if (options.user == NULL) {
979 				options.user = xstrdup(optarg);
980 				user_on_commandline = 1;
981 			}
982 			break;
983 
984 		case 'L':
985 			if (parse_forward(&fwd, optarg, 0, 0))
986 				add_local_forward(&options, &fwd);
987 			else {
988 				fprintf(stderr,
989 				    "Bad local forwarding specification '%s'\n",
990 				    optarg);
991 				exit(255);
992 			}
993 			break;
994 
995 		case 'R':
996 			if (parse_forward(&fwd, optarg, 0, 1) ||
997 			    parse_forward(&fwd, optarg, 1, 1)) {
998 				add_remote_forward(&options, &fwd);
999 			} else {
1000 				fprintf(stderr,
1001 				    "Bad remote forwarding specification "
1002 				    "'%s'\n", optarg);
1003 				exit(255);
1004 			}
1005 			break;
1006 
1007 		case 'D':
1008 			if (parse_forward(&fwd, optarg, 1, 0)) {
1009 				add_local_forward(&options, &fwd);
1010 			} else {
1011 				fprintf(stderr,
1012 				    "Bad dynamic forwarding specification "
1013 				    "'%s'\n", optarg);
1014 				exit(255);
1015 			}
1016 			break;
1017 
1018 		case 'C':
1019 #ifdef WITH_ZLIB
1020 			options.compression = 1;
1021 #else
1022 			error("Compression not supported, disabling.");
1023 #endif
1024 			break;
1025 		case 'N':
1026 			if (options.session_type != -1 &&
1027 			    options.session_type != SESSION_TYPE_NONE)
1028 				fatal("Cannot specify -N with -s/SessionType");
1029 			options.session_type = SESSION_TYPE_NONE;
1030 			options.request_tty = REQUEST_TTY_NO;
1031 			break;
1032 		case 'T':
1033 			options.request_tty = REQUEST_TTY_NO;
1034 			break;
1035 		case 'o':
1036 			line = xstrdup(optarg);
1037 			if (process_config_line(&options, pw,
1038 			    host ? host : "", host ? host : "", "", line,
1039 			    "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1040 				exit(255);
1041 			free(line);
1042 			break;
1043 		case 's':
1044 			if (options.session_type != -1 &&
1045 			    options.session_type != SESSION_TYPE_SUBSYSTEM)
1046 				fatal("Cannot specify -s with -N/SessionType");
1047 			options.session_type = SESSION_TYPE_SUBSYSTEM;
1048 			break;
1049 		case 'S':
1050 			free(options.control_path);
1051 			options.control_path = xstrdup(optarg);
1052 			break;
1053 		case 'b':
1054 			options.bind_address = optarg;
1055 			break;
1056 		case 'B':
1057 			options.bind_interface = optarg;
1058 			break;
1059 		case 'F':
1060 			config = optarg;
1061 			break;
1062 		default:
1063 			usage();
1064 		}
1065 	}
1066 
1067 	if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1068 		opt_terminated = 1;
1069 
1070 	ac -= optind;
1071 	av += optind;
1072 
1073 	if (ac > 0 && !host) {
1074 		int tport;
1075 		char *tuser;
1076 		switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1077 		case -1:
1078 			usage();
1079 			break;
1080 		case 0:
1081 			if (options.user == NULL) {
1082 				options.user = tuser;
1083 				tuser = NULL;
1084 				user_on_commandline = 1;
1085 			}
1086 			free(tuser);
1087 			if (options.port == -1 && tport != -1)
1088 				options.port = tport;
1089 			break;
1090 		default:
1091 			p = xstrdup(*av);
1092 			cp = strrchr(p, '@');
1093 			if (cp != NULL) {
1094 				if (cp == p)
1095 					usage();
1096 				if (options.user == NULL) {
1097 					options.user = p;
1098 					p = NULL;
1099 					user_on_commandline = 1;
1100 				}
1101 				*cp++ = '\0';
1102 				host = xstrdup(cp);
1103 				free(p);
1104 			} else
1105 				host = p;
1106 			break;
1107 		}
1108 		if (ac > 1 && !opt_terminated) {
1109 			optind = optreset = 1;
1110 			goto again;
1111 		}
1112 		ac--, av++;
1113 	}
1114 
1115 	/* Check that we got a host name. */
1116 	if (!host)
1117 		usage();
1118 
1119 	/*
1120 	 * Validate commandline-specified values that end up in %tokens
1121 	 * before they are used in config parsing.
1122 	 */
1123 	if (options.user != NULL && !ssh_valid_ruser(options.user))
1124 		fatal("remote username contains invalid characters");
1125 	if (!ssh_valid_hostname(host))
1126 		fatal("hostname contains invalid characters");
1127 
1128 	options.host_arg = xstrdup(host);
1129 
1130 	/* Initialize the command to execute on remote host. */
1131 	if ((command = sshbuf_new()) == NULL)
1132 		fatal("sshbuf_new failed");
1133 
1134 	/*
1135 	 * Save the command to execute on the remote host in a buffer. There
1136 	 * is no limit on the length of the command, except by the maximum
1137 	 * packet size.  Also sets the tty flag if there is no command.
1138 	 */
1139 	if (!ac) {
1140 		/* No command specified - execute shell on a tty. */
1141 		if (options.session_type == SESSION_TYPE_SUBSYSTEM) {
1142 			fprintf(stderr,
1143 			    "You must specify a subsystem to invoke.\n");
1144 			usage();
1145 		}
1146 	} else {
1147 		/* A command has been specified.  Store it into the buffer. */
1148 		for (i = 0; i < ac; i++) {
1149 			if ((r = sshbuf_putf(command, "%s%s",
1150 			    i ? " " : "", av[i])) != 0)
1151 				fatal_fr(r, "buffer error");
1152 		}
1153 	}
1154 
1155 	ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1156 
1157 	/*
1158 	 * Initialize "log" output.  Since we are the client all output
1159 	 * goes to stderr unless otherwise specified by -y or -E.
1160 	 */
1161 	if (use_syslog && logfile != NULL)
1162 		fatal("Can't specify both -y and -E");
1163 	if (logfile != NULL)
1164 		log_redirect_stderr_to(logfile);
1165 	log_init(argv0,
1166 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1167 	    SYSLOG_LEVEL_INFO : options.log_level,
1168 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1169 	    SYSLOG_FACILITY_USER : options.log_facility,
1170 	    !use_syslog);
1171 
1172 	debug("%s, %s", SSH_RELEASE, SSH_OPENSSL_VERSION);
1173 	if (uname(&utsname) != 0) {
1174 		memset(&utsname, 0, sizeof(utsname));
1175 		strlcpy(utsname.sysname, "UNKNOWN", sizeof(utsname.sysname));
1176 	}
1177 	debug3("Running on %s %s %s %s", utsname.sysname, utsname.release,
1178 	    utsname.version, utsname.machine);
1179 	debug3("Started with: %s", args);
1180 	free(args);
1181 
1182 	/* Parse the configuration files */
1183 	process_config_files(options.host_arg, pw, 0, &want_final_pass);
1184 	if (want_final_pass)
1185 		debug("configuration requests final Match pass");
1186 
1187 	/* Hostname canonicalisation needs a few options filled. */
1188 	fill_default_options_for_canonicalization(&options);
1189 
1190 	/* If the user has replaced the hostname then take it into use now */
1191 	if (options.hostname != NULL) {
1192 		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
1193 		cp = percent_expand(options.hostname,
1194 		    "h", host, (char *)NULL);
1195 		free(host);
1196 		host = cp;
1197 		free(options.hostname);
1198 		options.hostname = xstrdup(host);
1199 	}
1200 
1201 	/* Don't lowercase addresses, they will be explicitly canonicalised */
1202 	if ((was_addr = is_addr(host)) == 0)
1203 		lowercase(host);
1204 
1205 	/*
1206 	 * Try to canonicalize if requested by configuration or the
1207 	 * hostname is an address.
1208 	 */
1209 	if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1210 		addrs = resolve_canonicalize(&host, options.port);
1211 
1212 	/*
1213 	 * If CanonicalizePermittedCNAMEs have been specified but
1214 	 * other canonicalization did not happen (by not being requested
1215 	 * or by failing with fallback) then the hostname may still be changed
1216 	 * as a result of CNAME following.
1217 	 *
1218 	 * Try to resolve the bare hostname name using the system resolver's
1219 	 * usual search rules and then apply the CNAME follow rules.
1220 	 *
1221 	 * Skip the lookup if a ProxyCommand is being used unless the user
1222 	 * has specifically requested canonicalisation for this case via
1223 	 * CanonicalizeHostname=always
1224 	 */
1225 	direct = option_clear_or_none(options.proxy_command) &&
1226 	    option_clear_or_none(options.jump_host);
1227 	if (addrs == NULL && config_has_permitted_cnames(&options) && (direct ||
1228 	    options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1229 		if ((addrs = resolve_host(host, options.port,
1230 		    direct, cname, sizeof(cname))) == NULL) {
1231 			/* Don't fatal proxied host names not in the DNS */
1232 			if (direct)
1233 				cleanup_exit(255); /* logged in resolve_host */
1234 		} else
1235 			check_follow_cname(direct, &host, cname);
1236 	}
1237 
1238 	/*
1239 	 * If canonicalisation is enabled then re-parse the configuration
1240 	 * files as new stanzas may match.
1241 	 */
1242 	if (options.canonicalize_hostname != 0 && !want_final_pass) {
1243 		debug("hostname canonicalisation enabled, "
1244 		    "will re-parse configuration");
1245 		want_final_pass = 1;
1246 	}
1247 
1248 	if (want_final_pass) {
1249 		debug("re-parsing configuration");
1250 		free(options.hostname);
1251 		options.hostname = xstrdup(host);
1252 		process_config_files(options.host_arg, pw, 1, NULL);
1253 		/*
1254 		 * Address resolution happens early with canonicalisation
1255 		 * enabled and the port number may have changed since, so
1256 		 * reset it in address list
1257 		 */
1258 		if (addrs != NULL && options.port > 0)
1259 			set_addrinfo_port(addrs, options.port);
1260 	}
1261 
1262 	/* Fill configuration defaults. */
1263 	if (fill_default_options(&options) != 0)
1264 		cleanup_exit(255);
1265 
1266 	if (options.user == NULL) {
1267 		user_was_default = 1;
1268 		options.user = xstrdup(pw->pw_name);
1269 	}
1270 
1271 	/*
1272 	 * If ProxyJump option specified, then construct a ProxyCommand now.
1273 	 */
1274 	if (options.jump_host != NULL) {
1275 		char port_s[8];
1276 		const char *jumpuser = options.jump_user, *sshbin = argv0;
1277 		int port = options.port, jumpport = options.jump_port;
1278 
1279 		if (port <= 0)
1280 			port = default_ssh_port();
1281 		if (jumpport <= 0)
1282 			jumpport = default_ssh_port();
1283 		if (jumpuser == NULL)
1284 			jumpuser = options.user;
1285 		if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1286 		    strcmp(options.user, jumpuser) == 0)
1287 			fatal("jumphost loop via %s", options.jump_host);
1288 
1289 		/*
1290 		 * Try to use SSH indicated by argv[0], but fall back to
1291 		 * "ssh" if it appears unavailable.
1292 		 */
1293 		if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1294 			sshbin = "ssh";
1295 
1296 		/* Consistency check */
1297 		if (options.proxy_command != NULL &&
1298 		    strcasecmp(options.proxy_command, "none") != 0)
1299 			fatal("inconsistent options: ProxyCommand+ProxyJump");
1300 		/* Never use FD passing for ProxyJump */
1301 		options.proxy_use_fdpass = 0;
1302 		snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1303 		xasprintf(&options.proxy_command,
1304 		    "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1305 		    sshbin,
1306 		    /* Optional "-l user" argument if jump_user set */
1307 		    options.jump_user == NULL ? "" : " -l ",
1308 		    options.jump_user == NULL ? "" : options.jump_user,
1309 		    /* Optional "-p port" argument if jump_port set */
1310 		    options.jump_port <= 0 ? "" : " -p ",
1311 		    options.jump_port <= 0 ? "" : port_s,
1312 		    /* Optional additional jump hosts ",..." */
1313 		    options.jump_extra == NULL ? "" : " -J ",
1314 		    options.jump_extra == NULL ? "" : options.jump_extra,
1315 		    /* Optional "-F" argument if -F specified */
1316 		    config == NULL ? "" : " -F ",
1317 		    config == NULL ? "" : config,
1318 		    /* Optional "-v" arguments if -v set */
1319 		    debug_flag ? " -" : "",
1320 		    debug_flag, "vvv",
1321 		    /* Mandatory hostname */
1322 		    options.jump_host);
1323 		debug("Setting implicit ProxyCommand from ProxyJump: %s",
1324 		    options.proxy_command);
1325 	}
1326 
1327 	if (options.port == 0)
1328 		options.port = default_ssh_port();
1329 	channel_set_af(ssh, options.address_family);
1330 	ssh_packet_set_qos(ssh, options.ip_qos_interactive,
1331 	    options.ip_qos_bulk);
1332 
1333 	/* Tidy and check options */
1334 	if (options.host_key_alias != NULL)
1335 		lowercase(options.host_key_alias);
1336 	if (options.proxy_command != NULL &&
1337 	    strcmp(options.proxy_command, "-") == 0 &&
1338 	    options.proxy_use_fdpass)
1339 		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1340 	if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1341 		if (options.control_persist && options.control_path != NULL) {
1342 			debug("UpdateHostKeys=ask is incompatible with "
1343 			    "ControlPersist; disabling");
1344 			options.update_hostkeys = 0;
1345 		} else if (sshbuf_len(command) != 0 ||
1346 		    options.remote_command != NULL ||
1347 		    options.request_tty == REQUEST_TTY_NO) {
1348 			debug("UpdateHostKeys=ask is incompatible with "
1349 			    "remote command execution; disabling");
1350 			options.update_hostkeys = 0;
1351 		} else if (options.log_level < SYSLOG_LEVEL_INFO) {
1352 			/* no point logging anything; user won't see it */
1353 			options.update_hostkeys = 0;
1354 		}
1355 	}
1356 	if (options.connection_attempts <= 0)
1357 		fatal("Invalid number of ConnectionAttempts");
1358 
1359 	if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1360 		fatal("Cannot execute command-line and remote command.");
1361 
1362 	/* Cannot fork to background if no command. */
1363 	if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
1364 	    options.remote_command == NULL &&
1365 	    options.session_type != SESSION_TYPE_NONE)
1366 		fatal("Cannot fork into background without a command "
1367 		    "to execute.");
1368 
1369 	/* reinit */
1370 	log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1371 	for (j = 0; j < options.num_log_verbose; j++) {
1372 		if (strcasecmp(options.log_verbose[j], "none") == 0)
1373 			break;
1374 		log_verbose_add(options.log_verbose[j]);
1375 	}
1376 
1377 	if (options.request_tty == REQUEST_TTY_YES ||
1378 	    options.request_tty == REQUEST_TTY_FORCE)
1379 		tty_flag = 1;
1380 
1381 	/* Allocate a tty by default if no command specified. */
1382 	if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1383 		tty_flag = options.request_tty != REQUEST_TTY_NO;
1384 
1385 	/* Force no tty */
1386 	if (options.request_tty == REQUEST_TTY_NO ||
1387 	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY) ||
1388 	    options.session_type == SESSION_TYPE_NONE)
1389 		tty_flag = 0;
1390 	/* Do not allocate a tty if stdin is not a tty. */
1391 	if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1392 	    options.request_tty != REQUEST_TTY_FORCE) {
1393 		if (tty_flag)
1394 			logit("Pseudo-terminal will not be allocated because "
1395 			    "stdin is not a terminal.");
1396 		tty_flag = 0;
1397 	}
1398 
1399 	/* Set up strings used to percent_expand() arguments */
1400 	cinfo = xcalloc(1, sizeof(*cinfo));
1401 	if (gethostname(thishost, sizeof(thishost)) == -1)
1402 		fatal("gethostname: %s", strerror(errno));
1403 	cinfo->thishost = xstrdup(thishost);
1404 	thishost[strcspn(thishost, ".")] = '\0';
1405 	cinfo->shorthost = xstrdup(thishost);
1406 	xasprintf(&cinfo->portstr, "%d", options.port);
1407 	xasprintf(&cinfo->uidstr, "%llu",
1408 	    (unsigned long long)pw->pw_uid);
1409 	cinfo->keyalias = xstrdup(options.host_key_alias ?
1410 	    options.host_key_alias : options.host_arg);
1411 	cinfo->host_arg = xstrdup(options.host_arg);
1412 	cinfo->remhost = xstrdup(host);
1413 	cinfo->homedir = xstrdup(pw->pw_dir);
1414 	cinfo->locuser = xstrdup(pw->pw_name);
1415 	cinfo->jmphost = xstrdup(options.jump_host == NULL ?
1416 	    "" : options.jump_host);
1417 
1418 	/*
1419 	 * If the user was specified via a configuration directive then attempt
1420 	 * to expand it. It cannot contain %r (itself) or %C since User is
1421 	 * a component of the hash.
1422 	 */
1423 	if (!user_on_commandline && !user_was_default) {
1424 		if ((p = percent_dollar_expand(options.user,
1425 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS_NOUSER(cinfo),
1426 		    (char *)NULL)) == NULL)
1427 			fatal("invalid environment variable expansion");
1428 		user_expanded = strcmp(p, options.user) != 0;
1429 		free(options.user);
1430 		options.user = p;
1431 	}
1432 
1433 	/*
1434 	 * Usernames specified on the commandline or expanded from the
1435 	 * configuration file must be validated.
1436 	 * Conversely, usernames from getpwnam(3) or specified as literals
1437 	 * via configuration (i.e. not expanded) are not subject to validation.
1438 	 */
1439 	if ((user_on_commandline || user_expanded) &&
1440 	    !ssh_valid_ruser(options.user))
1441 		fatal("remote username contains invalid characters");
1442 
1443 	/* Now User is expanded, store it and calculate hash. */
1444 	cinfo->remuser = xstrdup(options.user);
1445 	cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost,
1446 	    cinfo->remhost, cinfo->portstr, cinfo->remuser, cinfo->jmphost);
1447 
1448 	/* Find canonic host name. */
1449 	if (strchr(host, '.') == NULL) {
1450 		struct addrinfo hints;
1451 		struct addrinfo *ai = NULL;
1452 		int errgai;
1453 
1454 		memset(&hints, 0, sizeof(hints));
1455 		hints.ai_family = options.address_family;
1456 		hints.ai_flags = AI_CANONNAME;
1457 		hints.ai_socktype = SOCK_STREAM;
1458 		errgai = getaddrinfo(host, NULL, &hints, &ai);
1459 		if (errgai == 0) {
1460 			if (ai->ai_canonname != NULL) {
1461 				free(host);
1462 				host = xstrdup(ai->ai_canonname);
1463 			}
1464 			freeaddrinfo(ai);
1465 		}
1466 	}
1467 
1468 	/*
1469 	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1470 	 * after port-forwarding is set up, so it may pick up any local
1471 	 * tunnel interface name allocated.
1472 	 */
1473 	if (options.remote_command != NULL) {
1474 		debug3("expanding RemoteCommand: %s", options.remote_command);
1475 		cp = options.remote_command;
1476 		options.remote_command = default_client_percent_expand(cp,
1477 		    cinfo);
1478 		debug3("expanded RemoteCommand: %s", options.remote_command);
1479 		free(cp);
1480 		if ((r = sshbuf_put(command, options.remote_command,
1481 		    strlen(options.remote_command))) != 0)
1482 			fatal_fr(r, "buffer error");
1483 	}
1484 
1485 	if (options.control_path != NULL) {
1486 		cp = tilde_expand_filename(options.control_path, getuid());
1487 		free(options.control_path);
1488 		options.control_path = default_client_percent_dollar_expand(cp,
1489 		    cinfo);
1490 		free(cp);
1491 	}
1492 
1493 	if (options.identity_agent != NULL) {
1494 		p = tilde_expand_filename(options.identity_agent, getuid());
1495 		cp = default_client_percent_dollar_expand(p, cinfo);
1496 		free(p);
1497 		free(options.identity_agent);
1498 		options.identity_agent = cp;
1499 	}
1500 
1501 	for (j = 0; j < options.num_revoked_host_keys; j++) {
1502 		p = tilde_expand_filename(options.revoked_host_keys[j],
1503 		    getuid());
1504 		cp = default_client_percent_dollar_expand(p, cinfo);
1505 		free(p);
1506 		free(options.revoked_host_keys[j]);
1507 		options.revoked_host_keys[j] = cp;
1508 	}
1509 
1510 	if (options.forward_agent_sock_path != NULL) {
1511 		p = tilde_expand_filename(options.forward_agent_sock_path,
1512 		    getuid());
1513 		cp = default_client_percent_dollar_expand(p, cinfo);
1514 		free(p);
1515 		free(options.forward_agent_sock_path);
1516 		options.forward_agent_sock_path = cp;
1517 		if (stat(options.forward_agent_sock_path, &st) != 0) {
1518 			error("Cannot forward agent socket path \"%s\": %s",
1519 			    options.forward_agent_sock_path, strerror(errno));
1520 			if (options.exit_on_forward_failure)
1521 				cleanup_exit(255);
1522 		}
1523 	}
1524 
1525 	if (options.version_addendum != NULL) {
1526 		cp = default_client_percent_dollar_expand(
1527 		    options.version_addendum, cinfo);
1528 		free(options.version_addendum);
1529 		options.version_addendum = cp;
1530 	}
1531 
1532 	if (options.num_system_hostfiles > 0 &&
1533 	    strcasecmp(options.system_hostfiles[0], "none") == 0) {
1534 		if (options.num_system_hostfiles > 1)
1535 			fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1536 			    "appears with other entries");
1537 		free(options.system_hostfiles[0]);
1538 		options.system_hostfiles[0] = NULL;
1539 		options.num_system_hostfiles = 0;
1540 	}
1541 
1542 	if (options.num_user_hostfiles > 0 &&
1543 	    strcasecmp(options.user_hostfiles[0], "none") == 0) {
1544 		if (options.num_user_hostfiles > 1)
1545 			fatal("Invalid UserKnownHostsFiles: \"none\" "
1546 			    "appears with other entries");
1547 		free(options.user_hostfiles[0]);
1548 		options.user_hostfiles[0] = NULL;
1549 		options.num_user_hostfiles = 0;
1550 	}
1551 	for (j = 0; j < options.num_user_hostfiles; j++) {
1552 		if (options.user_hostfiles[j] == NULL)
1553 			continue;
1554 		cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1555 		p = default_client_percent_dollar_expand(cp, cinfo);
1556 		if (strcmp(options.user_hostfiles[j], p) != 0)
1557 			debug3("expanded UserKnownHostsFile '%s' -> "
1558 			    "'%s'", options.user_hostfiles[j], p);
1559 		free(options.user_hostfiles[j]);
1560 		free(cp);
1561 		options.user_hostfiles[j] = p;
1562 	}
1563 
1564 	for (j = 0; j < options.num_setenv; j++) {
1565 		char *name = options.setenv[j], *value;
1566 
1567 		if (name == NULL)
1568 			continue;
1569 		/* Expand only the value portion, not the variable name. */
1570 		if ((value = strchr(name, '=')) == NULL) {
1571 			/* shouldn't happen; vars are checked in readconf.c */
1572 			fatal("Invalid config SetEnv: %s", name);
1573 		}
1574 		*value++ = '\0';
1575 		cp = default_client_percent_dollar_expand(value, cinfo);
1576 		xasprintf(&p, "%s=%s", name, cp);
1577 		if (strcmp(value, p) != 0) {
1578 			debug3("expanded SetEnv '%s' '%s' -> '%s'",
1579 			    name, value, cp);
1580 		}
1581 		free(options.setenv[j]);
1582 		free(cp);
1583 		options.setenv[j] = p;
1584 	}
1585 
1586 	for (i = 0; i < options.num_local_forwards; i++) {
1587 		if (options.local_forwards[i].listen_path != NULL) {
1588 			cp = options.local_forwards[i].listen_path;
1589 			p = options.local_forwards[i].listen_path =
1590 			    default_client_percent_expand(cp, cinfo);
1591 			if (strcmp(cp, p) != 0)
1592 				debug3("expanded LocalForward listen path "
1593 				    "'%s' -> '%s'", cp, p);
1594 			free(cp);
1595 		}
1596 		if (options.local_forwards[i].connect_path != NULL) {
1597 			cp = options.local_forwards[i].connect_path;
1598 			p = options.local_forwards[i].connect_path =
1599 			    default_client_percent_expand(cp, cinfo);
1600 			if (strcmp(cp, p) != 0)
1601 				debug3("expanded LocalForward connect path "
1602 				    "'%s' -> '%s'", cp, p);
1603 			free(cp);
1604 		}
1605 	}
1606 
1607 	for (i = 0; i < options.num_remote_forwards; i++) {
1608 		if (options.remote_forwards[i].listen_path != NULL) {
1609 			cp = options.remote_forwards[i].listen_path;
1610 			p = options.remote_forwards[i].listen_path =
1611 			    default_client_percent_expand(cp, cinfo);
1612 			if (strcmp(cp, p) != 0)
1613 				debug3("expanded RemoteForward listen path "
1614 				    "'%s' -> '%s'", cp, p);
1615 			free(cp);
1616 		}
1617 		if (options.remote_forwards[i].connect_path != NULL) {
1618 			cp = options.remote_forwards[i].connect_path;
1619 			p = options.remote_forwards[i].connect_path =
1620 			    default_client_percent_expand(cp, cinfo);
1621 			if (strcmp(cp, p) != 0)
1622 				debug3("expanded RemoteForward connect path "
1623 				    "'%s' -> '%s'", cp, p);
1624 			free(cp);
1625 		}
1626 	}
1627 
1628 	if (config_test) {
1629 		dump_client_config(&options, host);
1630 		exit(0);
1631 	}
1632 
1633 	/* Expand SecurityKeyProvider if it refers to an environment variable */
1634 	if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1635 	    strlen(options.sk_provider) > 1) {
1636 		if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1637 			debug("Authenticator provider %s did not resolve; "
1638 			    "disabling", options.sk_provider);
1639 			free(options.sk_provider);
1640 			options.sk_provider = NULL;
1641 		} else {
1642 			debug2("resolved SecurityKeyProvider %s => %s",
1643 			    options.sk_provider, cp);
1644 			free(options.sk_provider);
1645 			options.sk_provider = xstrdup(cp);
1646 		}
1647 	}
1648 
1649 	if (muxclient_command != 0 && options.control_path == NULL)
1650 		fatal("No ControlPath specified for \"-O\" command");
1651 	if (options.control_path != NULL) {
1652 		int sock;
1653 		if ((sock = muxclient(options.control_path)) >= 0) {
1654 			if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
1655 				fatal("ssh_packet_set_connection failed");
1656 			ssh_packet_set_mux(ssh);
1657 			goto skip_connect;
1658 		}
1659 	}
1660 
1661 	/*
1662 	 * If hostname canonicalisation was not enabled, then we may not
1663 	 * have yet resolved the hostname. Do so now.
1664 	 */
1665 	if (addrs == NULL && options.proxy_command == NULL) {
1666 		debug2("resolving \"%s\" port %d", host, options.port);
1667 		if ((addrs = resolve_host(host, options.port, 1,
1668 		    cname, sizeof(cname))) == NULL)
1669 			cleanup_exit(255); /* resolve_host logs the error */
1670 	}
1671 
1672 	if (options.connection_timeout >= INT_MAX/1000)
1673 		timeout_ms = INT_MAX;
1674 	else
1675 		timeout_ms = options.connection_timeout * 1000;
1676 
1677 	/* Apply channels timeouts, if set */
1678 	channel_clear_timeouts(ssh);
1679 	for (j = 0; j < options.num_channel_timeouts; j++) {
1680 		debug3("applying channel timeout %s",
1681 		    options.channel_timeouts[j]);
1682 		if (parse_pattern_interval(options.channel_timeouts[j],
1683 		    &cp, &i) != 0) {
1684 			fatal_f("internal error: bad timeout %s",
1685 			    options.channel_timeouts[j]);
1686 		}
1687 		channel_add_timeout(ssh, cp, i);
1688 		free(cp);
1689 	}
1690 
1691 	/* Open a connection to the remote host. */
1692 	if (ssh_connect(ssh, host, options.host_arg, addrs, &hostaddr,
1693 	    options.port, options.connection_attempts,
1694 	    &timeout_ms, options.tcp_keep_alive) != 0)
1695 		exit(255);
1696 
1697 
1698 	ssh_packet_set_timeout(ssh, options.server_alive_interval,
1699 	    options.server_alive_count_max);
1700 
1701 	if (timeout_ms > 0)
1702 		debug3("timeout: %d ms remain after connect", timeout_ms);
1703 
1704 	/*
1705 	 * If we successfully made the connection and we have hostbased auth
1706 	 * enabled, load the public keys so we can later use the ssh-keysign
1707 	 * helper to sign challenges.
1708 	 */
1709 	sensitive_data.nkeys = 0;
1710 	sensitive_data.keys = NULL;
1711 	if (options.hostbased_authentication) {
1712 		int loaded = 0;
1713 
1714 		sensitive_data.nkeys = 10;
1715 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1716 		    sizeof(*sensitive_data.keys));
1717 
1718 		/* XXX check errors? */
1719 #define L_PUBKEY(p,o) do { \
1720 	if ((o) >= sensitive_data.nkeys) \
1721 		fatal_f("pubkey out of array bounds"); \
1722 	check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1723 	    &(sensitive_data.keys[o]), p, "hostbased pubkey"); \
1724 	if (sensitive_data.keys[o] != NULL) { \
1725 		debug2("hostbased pubkey \"%s\" in slot %d", p, o); \
1726 		loaded++; \
1727 	} \
1728 } while (0)
1729 #define L_CERT(p,o) do { \
1730 	if ((o) >= sensitive_data.nkeys) \
1731 		fatal_f("cert out of array bounds"); \
1732 	check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), \
1733 	    &(sensitive_data.keys[o]), p, "hostbased cert"); \
1734 	if (sensitive_data.keys[o] != NULL) { \
1735 		debug2("hostbased cert \"%s\" in slot %d", p, o); \
1736 		loaded++; \
1737 	} \
1738 } while (0)
1739 
1740 		if (options.hostbased_authentication == 1) {
1741 			L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1742 			L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1743 			L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1744 			L_CERT(_PATH_HOST_MLDSA44_ED25519_KEY_FILE, 3);
1745 			L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1746 			L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1747 			L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1748 			L_PUBKEY(_PATH_HOST_MLDSA44_ED25519_KEY_FILE, 7);
1749 			if (loaded == 0)
1750 				debug("HostbasedAuthentication enabled but no "
1751 				   "local public host keys could be loaded.");
1752 		}
1753 	}
1754 
1755 	/* load options.identity_files */
1756 	load_public_identity_files(cinfo);
1757 
1758 	/* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1759 	if (options.identity_agent &&
1760 	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1761 		if (strcmp(options.identity_agent, "none") == 0) {
1762 			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1763 		} else {
1764 			cp = options.identity_agent;
1765 			/* legacy (limited) format */
1766 			if (cp[0] == '$' && cp[1] != '{') {
1767 				if (!valid_env_name(cp + 1)) {
1768 					fatal("Invalid IdentityAgent "
1769 					    "environment variable name %s", cp);
1770 				}
1771 				if ((p = getenv(cp + 1)) == NULL)
1772 					unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1773 				else
1774 					setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1775 			} else {
1776 				/* identity_agent specifies a path directly */
1777 				setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1778 			}
1779 		}
1780 	}
1781 
1782 	if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1783 		cp = options.forward_agent_sock_path;
1784 		if (cp[0] == '$') {
1785 			if (!valid_env_name(cp + 1)) {
1786 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1787 			}
1788 			if ((p = getenv(cp + 1)) != NULL)
1789 				forward_agent_sock_path = xstrdup(p);
1790 			else
1791 				options.forward_agent = 0;
1792 			free(cp);
1793 		} else {
1794 			forward_agent_sock_path = cp;
1795 		}
1796 	}
1797 
1798 	/* Expand ~ in known host file names. */
1799 	tilde_expand_paths(options.system_hostfiles,
1800 	    options.num_system_hostfiles);
1801 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1802 
1803 	ssh_signal(SIGCHLD, main_sigchld_handler);
1804 
1805 	/* Log into the remote system.  Never returns if the login fails. */
1806 	ssh_login(ssh, &sensitive_data, host, &hostaddr, options.port,
1807 	    pw, timeout_ms, cinfo);
1808 
1809 	/* We no longer need the private host keys.  Clear them now. */
1810 	if (sensitive_data.nkeys != 0) {
1811 		for (i = 0; i < sensitive_data.nkeys; i++) {
1812 			if (sensitive_data.keys[i] != NULL) {
1813 				/* Destroys contents safely */
1814 				debug3("clear hostkey %d", i);
1815 				sshkey_free(sensitive_data.keys[i]);
1816 				sensitive_data.keys[i] = NULL;
1817 			}
1818 		}
1819 		free(sensitive_data.keys);
1820 	}
1821 	for (i = 0; i < options.num_identity_files; i++) {
1822 		free(options.identity_files[i]);
1823 		options.identity_files[i] = NULL;
1824 		if (options.identity_keys[i]) {
1825 			sshkey_free(options.identity_keys[i]);
1826 			options.identity_keys[i] = NULL;
1827 		}
1828 	}
1829 	for (i = 0; i < options.num_certificate_files; i++) {
1830 		free(options.certificate_files[i]);
1831 		options.certificate_files[i] = NULL;
1832 	}
1833 
1834 #ifdef ENABLE_PKCS11
1835 	(void)pkcs11_del_provider(options.pkcs11_provider);
1836 #endif
1837 
1838  skip_connect:
1839 	if (addrs != NULL)
1840 		freeaddrinfo(addrs);
1841 	exit_status = ssh_session2(ssh, cinfo);
1842 	ssh_conn_info_free(cinfo);
1843 	channel_free_channels(ssh);
1844 	ssh_packet_free(ssh);
1845 	pwfree(pw);
1846 
1847 	if (options.control_path != NULL && muxserver_sock != -1)
1848 		unlink(options.control_path);
1849 
1850 	/* Kill ProxyCommand if it is running. */
1851 	ssh_kill_proxy_command();
1852 
1853 	return exit_status;
1854 }
1855 
1856 static void
1857 control_persist_detach(void)
1858 {
1859 	pid_t pid;
1860 
1861 	debug_f("backgrounding master process");
1862 
1863 	/*
1864 	 * master (current process) into the background, and make the
1865 	 * foreground process a client of the backgrounded master.
1866 	 */
1867 	switch ((pid = fork())) {
1868 	case -1:
1869 		fatal_f("fork: %s", strerror(errno));
1870 	case 0:
1871 		/* Child: master process continues mainloop */
1872 		break;
1873 	default:
1874 		/*
1875 		 * Parent: set up mux client to connect to backgrounded
1876 		 * master.
1877 		 */
1878 		debug2_f("background process is %ld", (long)pid);
1879 		options.stdin_null = ostdin_null_flag;
1880 		options.request_tty = orequest_tty;
1881 		tty_flag = otty_flag;
1882 		options.fork_after_authentication = ofork_after_authentication;
1883 		options.session_type = osession_type;
1884 		close(muxserver_sock);
1885 		muxserver_sock = -1;
1886 		options.control_master = SSHCTL_MASTER_NO;
1887 		(void)muxclient(options.control_path);
1888 		/* muxclient() doesn't return on success. */
1889 		fatal("Failed to connect to new control master");
1890 	}
1891 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1892 		error_f("stdfd_devnull failed");
1893 	daemon(1, 1);
1894 	setproctitle("%s [mux]", options.control_path);
1895 }
1896 
1897 /* Do fork() after authentication. Used by "ssh -f" */
1898 static void
1899 fork_postauth(void)
1900 {
1901 	if (need_controlpersist_detach)
1902 		control_persist_detach();
1903 	debug("forking to background");
1904 	options.fork_after_authentication = 0;
1905 	if (daemon(1, 1) == -1)
1906 		fatal("daemon() failed: %.200s", strerror(errno));
1907 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1908 		error_f("stdfd_devnull failed");
1909 }
1910 
1911 static void
1912 forwarding_success(void)
1913 {
1914 	if (forward_confirms_pending == -1)
1915 		return;
1916 	if (--forward_confirms_pending == 0) {
1917 		debug_f("all expected forwarding replies received");
1918 		if (options.fork_after_authentication)
1919 			fork_postauth();
1920 	} else {
1921 		debug2_f("%d expected forwarding replies remaining",
1922 		    forward_confirms_pending);
1923 	}
1924 }
1925 
1926 /* Callback for remote forward global requests */
1927 static void
1928 ssh_confirm_remote_forward(struct ssh *ssh, int type, uint32_t seq, void *ctxt)
1929 {
1930 	struct Forward *rfwd = (struct Forward *)ctxt;
1931 	u_int port;
1932 	int r;
1933 
1934 	/* XXX verbose() on failure? */
1935 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1936 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1937 	    rfwd->listen_path ? rfwd->listen_path :
1938 	    rfwd->listen_host ? rfwd->listen_host : "",
1939 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1940 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1941 	    rfwd->connect_host, rfwd->connect_port);
1942 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1943 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1944 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1945 				fatal_fr(r, "parse packet");
1946 			if (port > 65535) {
1947 				error("Invalid allocated port %u for remote "
1948 				    "forward to %s:%d", port,
1949 				    rfwd->connect_host, rfwd->connect_port);
1950 				/* Ensure failure processing runs below */
1951 				type = SSH2_MSG_REQUEST_FAILURE;
1952 				channel_update_permission(ssh,
1953 				    rfwd->handle, -1);
1954 			} else {
1955 				rfwd->allocated_port = (int)port;
1956 				logit("Allocated port %u for remote "
1957 				    "forward to %s:%d",
1958 				    rfwd->allocated_port, rfwd->connect_path ?
1959 				    rfwd->connect_path : rfwd->connect_host,
1960 				    rfwd->connect_port);
1961 				channel_update_permission(ssh,
1962 				    rfwd->handle, rfwd->allocated_port);
1963 			}
1964 		} else {
1965 			channel_update_permission(ssh, rfwd->handle, -1);
1966 		}
1967 	}
1968 
1969 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1970 		if (options.exit_on_forward_failure) {
1971 			if (rfwd->listen_path != NULL)
1972 				fatal("Error: remote port forwarding failed "
1973 				    "for listen path %s", rfwd->listen_path);
1974 			else
1975 				fatal("Error: remote port forwarding failed "
1976 				    "for listen port %d", rfwd->listen_port);
1977 		} else {
1978 			if (rfwd->listen_path != NULL)
1979 				logit("Warning: remote port forwarding failed "
1980 				    "for listen path %s", rfwd->listen_path);
1981 			else
1982 				logit("Warning: remote port forwarding failed "
1983 				    "for listen port %d", rfwd->listen_port);
1984 		}
1985 	}
1986 	forwarding_success();
1987 }
1988 
1989 static void
1990 client_cleanup_stdio_fwd(struct ssh *ssh, int id, int force, void *arg)
1991 {
1992 	debug("stdio forwarding: done");
1993 	cleanup_exit(0);
1994 }
1995 
1996 static void
1997 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1998 {
1999 	if (!success)
2000 		fatal("stdio forwarding failed");
2001 }
2002 
2003 static void
2004 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
2005 {
2006 	if (!success) {
2007 		error("Tunnel forwarding failed");
2008 		if (options.exit_on_forward_failure)
2009 			cleanup_exit(255);
2010 	}
2011 
2012 	debug_f("tunnel forward established, id=%d", id);
2013 	forwarding_success();
2014 }
2015 
2016 static void
2017 ssh_init_stdio_forwarding(struct ssh *ssh)
2018 {
2019 	Channel *c;
2020 	int in, out;
2021 
2022 	if (options.stdio_forward_host == NULL)
2023 		return;
2024 
2025 	debug3_f("%s:%d", options.stdio_forward_host,
2026 	    options.stdio_forward_port);
2027 
2028 	if ((in = dup(STDIN_FILENO)) == -1 ||
2029 	    (out = dup(STDOUT_FILENO)) == -1)
2030 		fatal_f("dup() in/out failed");
2031 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
2032 	    options.stdio_forward_port, in, out,
2033 	    CHANNEL_NONBLOCK_STDIO)) == NULL)
2034 		fatal_f("channel_connect_stdio_fwd failed");
2035 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
2036 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
2037 }
2038 
2039 static void
2040 ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
2041     u_int num_opens)
2042 {
2043 	u_int i;
2044 	int port;
2045 	char *addr, *arg, *oarg;
2046 	int where = FORWARD_LOCAL;
2047 
2048 	channel_clear_permission(ssh, FORWARD_ADM, where);
2049 	if (num_opens == 0)
2050 		return; /* permit any */
2051 
2052 	/* handle keywords: "any" / "none" */
2053 	if (num_opens == 1 && strcmp(opens[0], "any") == 0)
2054 		return;
2055 	if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
2056 		channel_disable_admin(ssh, where);
2057 		return;
2058 	}
2059 	/* Otherwise treat it as a list of permitted host:port */
2060 	for (i = 0; i < num_opens; i++) {
2061 		oarg = arg = xstrdup(opens[i]);
2062 		addr = hpdelim(&arg);
2063 		if (addr == NULL)
2064 			fatal_f("missing host in %s", what);
2065 		addr = cleanhostname(addr);
2066 		if (arg == NULL || ((port = permitopen_port(arg)) < 0))
2067 			fatal_f("bad port number in %s", what);
2068 		/* Send it to channels layer */
2069 		channel_add_permission(ssh, FORWARD_ADM,
2070 		    where, addr, port);
2071 		free(oarg);
2072 	}
2073 }
2074 
2075 static void
2076 ssh_init_forwarding(struct ssh *ssh, char **ifname)
2077 {
2078 	int success = 0;
2079 	int i;
2080 
2081 	ssh_init_forward_permissions(ssh, "permitremoteopen",
2082 	    options.permitted_remote_opens,
2083 	    options.num_permitted_remote_opens);
2084 
2085 	if (options.exit_on_forward_failure)
2086 		forward_confirms_pending = 0; /* track pending requests */
2087 	/* Initiate local TCP/IP port forwardings. */
2088 	for (i = 0; i < options.num_local_forwards; i++) {
2089 		debug("Local connections to %.200s:%d forwarded to remote "
2090 		    "address %.200s:%d",
2091 		    (options.local_forwards[i].listen_path != NULL) ?
2092 		    options.local_forwards[i].listen_path :
2093 		    (options.local_forwards[i].listen_host == NULL) ?
2094 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
2095 		    options.local_forwards[i].listen_host,
2096 		    options.local_forwards[i].listen_port,
2097 		    (options.local_forwards[i].connect_path != NULL) ?
2098 		    options.local_forwards[i].connect_path :
2099 		    options.local_forwards[i].connect_host,
2100 		    options.local_forwards[i].connect_port);
2101 		success += channel_setup_local_fwd_listener(ssh,
2102 		    &options.local_forwards[i], &options.fwd_opts);
2103 	}
2104 	if (i > 0 && success != i && options.exit_on_forward_failure)
2105 		fatal("Could not request local forwarding.");
2106 	if (i > 0 && success == 0)
2107 		error("Could not request local forwarding.");
2108 
2109 	/* Initiate remote TCP/IP port forwardings. */
2110 	for (i = 0; i < options.num_remote_forwards; i++) {
2111 		debug("Remote connections from %.200s:%d forwarded to "
2112 		    "local address %.200s:%d",
2113 		    (options.remote_forwards[i].listen_path != NULL) ?
2114 		    options.remote_forwards[i].listen_path :
2115 		    (options.remote_forwards[i].listen_host == NULL) ?
2116 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
2117 		    options.remote_forwards[i].listen_port,
2118 		    (options.remote_forwards[i].connect_path != NULL) ?
2119 		    options.remote_forwards[i].connect_path :
2120 		    options.remote_forwards[i].connect_host,
2121 		    options.remote_forwards[i].connect_port);
2122 		if ((options.remote_forwards[i].handle =
2123 		    channel_request_remote_forwarding(ssh,
2124 		    &options.remote_forwards[i])) >= 0) {
2125 			client_register_global_confirm(
2126 			    ssh_confirm_remote_forward,
2127 			    &options.remote_forwards[i]);
2128 			forward_confirms_pending++;
2129 		} else if (options.exit_on_forward_failure)
2130 			fatal("Could not request remote forwarding.");
2131 		else
2132 			logit("Warning: Could not request remote forwarding.");
2133 	}
2134 
2135 	/* Initiate tunnel forwarding. */
2136 	if (options.tun_open != SSH_TUNMODE_NO) {
2137 		if ((*ifname = client_request_tun_fwd(ssh,
2138 		    options.tun_open, options.tun_local,
2139 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
2140 			forward_confirms_pending++;
2141 		else if (options.exit_on_forward_failure)
2142 			fatal("Could not request tunnel forwarding.");
2143 		else
2144 			error("Could not request tunnel forwarding.");
2145 	}
2146 	if (forward_confirms_pending > 0) {
2147 		debug_f("expecting replies for %d forwards",
2148 		    forward_confirms_pending);
2149 	}
2150 }
2151 
2152 static void
2153 check_agent_present(void)
2154 {
2155 	int r;
2156 
2157 	if (options.forward_agent) {
2158 		/* Clear agent forwarding if we don't have an agent. */
2159 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2160 			options.forward_agent = 0;
2161 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
2162 				debug_r(r, "ssh_get_authentication_socket");
2163 		}
2164 	}
2165 }
2166 
2167 static void
2168 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2169 {
2170 	extern char **environ;
2171 	const char *display, *term;
2172 	char *proto = NULL, *data = NULL;
2173 
2174 	if (!success)
2175 		return; /* No need for error message, channels code sends one */
2176 
2177 	display = getenv("DISPLAY");
2178 	if (display == NULL && options.forward_x11)
2179 		debug("X11 forwarding requested but DISPLAY not set");
2180 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
2181 	    options.xauth_location, options.forward_x11_trusted,
2182 	    options.forward_x11_timeout, &proto, &data) == 0) {
2183 		/* Request forwarding with authentication spoofing. */
2184 		debug("Requesting X11 forwarding with authentication "
2185 		    "spoofing.");
2186 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2187 		    data, 1);
2188 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2189 		/* XXX exit_on_forward_failure */
2190 	}
2191 
2192 	check_agent_present();
2193 	if (options.forward_agent)
2194 		client_channel_reqest_agent_forwarding(ssh, id);
2195 
2196 	if ((term = lookup_env_in_list("TERM", options.setenv,
2197 	    options.num_setenv)) == NULL || *term == '\0')
2198 		term = getenv("TERM");
2199 	client_session2_setup(ssh, id, tty_flag,
2200 	    options.session_type == SESSION_TYPE_SUBSYSTEM, term,
2201 	    NULL, fileno(stdin), command, environ);
2202 }
2203 
2204 /* open new channel for a session */
2205 static int
2206 ssh_session2_open(struct ssh *ssh)
2207 {
2208 	Channel *c;
2209 	int window, packetmax, in, out, err;
2210 
2211 	if (options.stdin_null) {
2212 		in = open(_PATH_DEVNULL, O_RDONLY);
2213 	} else {
2214 		in = dup(STDIN_FILENO);
2215 	}
2216 	out = dup(STDOUT_FILENO);
2217 	err = dup(STDERR_FILENO);
2218 
2219 	if (in == -1 || out == -1 || err == -1)
2220 		fatal("dup() in/out/err failed");
2221 
2222 	window = CHAN_SES_WINDOW_DEFAULT;
2223 	packetmax = CHAN_SES_PACKET_DEFAULT;
2224 	if (tty_flag) {
2225 		window >>= 1;
2226 		packetmax >>= 1;
2227 	}
2228 	c = channel_new(ssh,
2229 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2230 	    window, packetmax, CHAN_EXTENDED_WRITE,
2231 	    "client-session", CHANNEL_NONBLOCK_STDIO);
2232 	if (tty_flag)
2233 		channel_set_tty(ssh, c);
2234 	debug3_f("channel_new: %d%s", c->self, tty_flag ? " (tty)" : "");
2235 
2236 	channel_send_open(ssh, c->self);
2237 	if (options.session_type != SESSION_TYPE_NONE)
2238 		channel_register_open_confirm(ssh, c->self,
2239 		    ssh_session2_setup, NULL);
2240 
2241 	return c->self;
2242 }
2243 
2244 static int
2245 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2246 {
2247 	int r, id = -1;
2248 	char *cp, *tun_fwd_ifname = NULL;
2249 
2250 	/* XXX should be pre-session */
2251 	if (!options.control_persist)
2252 		ssh_init_stdio_forwarding(ssh);
2253 
2254 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2255 
2256 	if (options.local_command != NULL) {
2257 		debug3("expanding LocalCommand: %s", options.local_command);
2258 		cp = options.local_command;
2259 		options.local_command = percent_expand(cp,
2260 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2261 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2262 		    (char *)NULL);
2263 		debug3("expanded LocalCommand: %s", options.local_command);
2264 		free(cp);
2265 	}
2266 
2267 	/* Start listening for multiplex clients */
2268 	if (!ssh_packet_get_mux(ssh))
2269 		muxserver_listen(ssh);
2270 
2271 	/*
2272 	 * If we are in control persist mode and have a working mux listen
2273 	 * socket, then prepare to background ourselves and have a foreground
2274 	 * client attach as a control client.
2275 	 * NB. we must save copies of the flags that we override for
2276 	 * the backgrounding, since we defer attachment of the client until
2277 	 * after the connection is fully established (in particular,
2278 	 * async rfwd replies have been received for ExitOnForwardFailure).
2279 	 */
2280 	if (options.control_persist && muxserver_sock != -1) {
2281 		ostdin_null_flag = options.stdin_null;
2282 		osession_type = options.session_type;
2283 		orequest_tty = options.request_tty;
2284 		otty_flag = tty_flag;
2285 		ofork_after_authentication = options.fork_after_authentication;
2286 		options.stdin_null = 1;
2287 		options.session_type = SESSION_TYPE_NONE;
2288 		tty_flag = 0;
2289 		if ((osession_type != SESSION_TYPE_NONE ||
2290 		    options.stdio_forward_host != NULL))
2291 			need_controlpersist_detach = 1;
2292 		options.fork_after_authentication = 1;
2293 	}
2294 	/*
2295 	 * ControlPersist mux listen socket setup failed, attempt the
2296 	 * stdio forward setup that we skipped earlier.
2297 	 */
2298 	if (options.control_persist && muxserver_sock == -1)
2299 		ssh_init_stdio_forwarding(ssh);
2300 
2301 	if (options.session_type != SESSION_TYPE_NONE)
2302 		id = ssh_session2_open(ssh);
2303 
2304 	/* If we don't expect to open a new session, then disallow it */
2305 	if (options.control_master == SSHCTL_MASTER_NO &&
2306 	    (ssh->compat & SSH_NEW_OPENSSH)) {
2307 		debug("Requesting no-more-sessions@openssh.com");
2308 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2309 		    (r = sshpkt_put_cstring(ssh,
2310 		    "no-more-sessions@openssh.com")) != 0 ||
2311 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2312 		    (r = sshpkt_send(ssh)) != 0)
2313 			fatal_fr(r, "send packet");
2314 	}
2315 
2316 	/* Execute a local command */
2317 	if (options.local_command != NULL &&
2318 	    options.permit_local_command)
2319 		ssh_local_cmd(options.local_command);
2320 
2321 	/*
2322 	 * stdout is now owned by the session channel; clobber it here
2323 	 * so future channel closes are propagated to the local fd.
2324 	 * NB. this can only happen after LocalCommand has completed,
2325 	 * as it may want to write to stdout.
2326 	 */
2327 	if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2328 		error_f("stdfd_devnull failed");
2329 
2330 	/*
2331 	 * If requested and we are not interested in replies to remote
2332 	 * forwarding requests, then let ssh continue in the background.
2333 	 */
2334 	if (options.fork_after_authentication) {
2335 		if (options.exit_on_forward_failure &&
2336 		    options.num_remote_forwards > 0) {
2337 			debug("deferring postauth fork until remote forward "
2338 			    "confirmation received");
2339 		} else
2340 			fork_postauth();
2341 	}
2342 
2343 	return client_loop(ssh, tty_flag, tty_flag ?
2344 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2345 }
2346 
2347 /* Loads all IdentityFile and CertificateFile keys */
2348 static void
2349 load_public_identity_files(const struct ssh_conn_info *cinfo)
2350 {
2351 	char *filename, *cp;
2352 	struct sshkey *public;
2353 	int i;
2354 	u_int n_ids, n_certs;
2355 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2356 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2357 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2358 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2359 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2360 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2361 #ifdef ENABLE_PKCS11
2362 	struct sshkey **keys = NULL;
2363 	char **comments = NULL;
2364 	int nkeys;
2365 #endif /* PKCS11 */
2366 
2367 	n_ids = n_certs = 0;
2368 	memset(identity_files, 0, sizeof(identity_files));
2369 	memset(identity_keys, 0, sizeof(identity_keys));
2370 	memset(identity_file_userprovided, 0,
2371 	    sizeof(identity_file_userprovided));
2372 	memset(certificate_files, 0, sizeof(certificate_files));
2373 	memset(certificates, 0, sizeof(certificates));
2374 	memset(certificate_file_userprovided, 0,
2375 	    sizeof(certificate_file_userprovided));
2376 
2377 #ifdef ENABLE_PKCS11
2378 	if (options.pkcs11_provider != NULL &&
2379 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2380 	    (pkcs11_init(!options.batch_mode) == 0) &&
2381 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2382 	    &keys, &comments)) > 0) {
2383 		for (i = 0; i < nkeys; i++) {
2384 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2385 				sshkey_free(keys[i]);
2386 				free(comments[i]);
2387 				continue;
2388 			}
2389 			identity_keys[n_ids] = keys[i];
2390 			identity_files[n_ids] = comments[i]; /* transferred */
2391 			n_ids++;
2392 		}
2393 		free(keys);
2394 		free(comments);
2395 	}
2396 #endif /* ENABLE_PKCS11 */
2397 	for (i = 0; i < options.num_identity_files; i++) {
2398 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2399 		    strcasecmp(options.identity_files[i], "none") == 0) {
2400 			free(options.identity_files[i]);
2401 			options.identity_files[i] = NULL;
2402 			continue;
2403 		}
2404 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2405 		filename = default_client_percent_dollar_expand(cp, cinfo);
2406 		free(cp);
2407 		check_load(sshkey_load_public(filename, &public, NULL),
2408 		    &public, filename, "pubkey");
2409 		debug("identity file %s type %d", filename,
2410 		    public ? public->type : -1);
2411 		free(options.identity_files[i]);
2412 		identity_files[n_ids] = filename;
2413 		identity_keys[n_ids] = public;
2414 		identity_file_userprovided[n_ids] =
2415 		    options.identity_file_userprovided[i];
2416 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2417 			continue;
2418 
2419 		/*
2420 		 * If no certificates have been explicitly listed then try
2421 		 * to add the default certificate variant too.
2422 		 */
2423 		if (options.num_certificate_files != 0)
2424 			continue;
2425 		xasprintf(&cp, "%s-cert", filename);
2426 		check_load(sshkey_load_public(cp, &public, NULL),
2427 		    &public, filename, "identity pubkey");
2428 		if (public == NULL) {
2429 			free(cp);
2430 			continue;
2431 		}
2432 		if (!sshkey_is_cert(public)) {
2433 			debug_f("key %s type %s is not a certificate",
2434 			    cp, sshkey_type(public));
2435 			sshkey_free(public);
2436 			free(cp);
2437 			continue;
2438 		}
2439 		free(cp);
2440 		/* NB. leave filename pointing to private key */
2441 		identity_files[n_ids] = xstrdup(filename);
2442 		identity_keys[n_ids] = public;
2443 		identity_file_userprovided[n_ids] =
2444 		    options.identity_file_userprovided[i];
2445 		n_ids++;
2446 	}
2447 
2448 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2449 		fatal_f("too many certificates");
2450 	for (i = 0; i < options.num_certificate_files; i++) {
2451 		cp = tilde_expand_filename(options.certificate_files[i],
2452 		    getuid());
2453 		filename = default_client_percent_dollar_expand(cp, cinfo);
2454 		free(cp);
2455 
2456 		check_load(sshkey_load_public(filename, &public, NULL),
2457 		    &public, filename, "identity cert");
2458 		free(options.certificate_files[i]);
2459 		options.certificate_files[i] = NULL;
2460 		if (public == NULL) {
2461 			free(filename);
2462 			continue;
2463 		}
2464 		if (!sshkey_is_cert(public)) {
2465 			debug_f("key %s type %s is not a certificate",
2466 			    filename, sshkey_type(public));
2467 			sshkey_free(public);
2468 			free(filename);
2469 			continue;
2470 		}
2471 		certificate_files[n_certs] = filename;
2472 		certificates[n_certs] = public;
2473 		certificate_file_userprovided[n_certs] =
2474 		    options.certificate_file_userprovided[i];
2475 		++n_certs;
2476 	}
2477 
2478 	options.num_identity_files = n_ids;
2479 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2480 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2481 	memcpy(options.identity_file_userprovided,
2482 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2483 
2484 	options.num_certificate_files = n_certs;
2485 	memcpy(options.certificate_files,
2486 	    certificate_files, sizeof(certificate_files));
2487 	memcpy(options.certificates, certificates, sizeof(certificates));
2488 	memcpy(options.certificate_file_userprovided,
2489 	    certificate_file_userprovided,
2490 	    sizeof(certificate_file_userprovided));
2491 }
2492 
2493 static void
2494 main_sigchld_handler(int sig)
2495 {
2496 	int save_errno = errno;
2497 	pid_t pid;
2498 	int status;
2499 
2500 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2501 	    (pid == -1 && errno == EINTR))
2502 		;
2503 	errno = save_errno;
2504 }
2505