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