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