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