1 /* $OpenBSD: ssh.c,v 1.579 2022/10/24 22:43: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 "includes.h"
44 __RCSID("$FreeBSD: stable/12/crypto/openssh/ssh.c 373094 2023-06-05 19:07:15Z emaste $");
45 
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
49 #endif
50 #include <sys/resource.h>
51 #include <sys/ioctl.h>
52 #include <sys/socket.h>
53 #include <sys/wait.h>
54 
55 #include <ctype.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <netdb.h>
59 #ifdef HAVE_PATHS_H
60 #include <paths.h>
61 #endif
62 #include <pwd.h>
63 #include <signal.h>
64 #include <stdarg.h>
65 #include <stddef.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <stdarg.h>
70 #include <unistd.h>
71 #include <limits.h>
72 #include <locale.h>
73 
74 #include <netinet/in.h>
75 #include <arpa/inet.h>
76 
77 #ifdef WITH_OPENSSL
78 #include <openssl/evp.h>
79 #include <openssl/err.h>
80 #endif
81 #include "openbsd-compat/openssl-compat.h"
82 #include "openbsd-compat/sys-queue.h"
83 
84 #include "xmalloc.h"
85 #include "ssh.h"
86 #include "ssh2.h"
87 #include "canohost.h"
88 #include "compat.h"
89 #include "cipher.h"
90 #include "packet.h"
91 #include "sshbuf.h"
92 #include "channels.h"
93 #include "sshkey.h"
94 #include "authfd.h"
95 #include "authfile.h"
96 #include "pathnames.h"
97 #include "dispatch.h"
98 #include "clientloop.h"
99 #include "log.h"
100 #include "misc.h"
101 #include "readconf.h"
102 #include "sshconnect.h"
103 #include "kex.h"
104 #include "mac.h"
105 #include "sshpty.h"
106 #include "match.h"
107 #include "msg.h"
108 #include "version.h"
109 #include "ssherr.h"
110 #include "myproposal.h"
111 #include "utf8.h"
112 
113 #ifdef ENABLE_PKCS11
114 #include "ssh-pkcs11.h"
115 #endif
116 
117 extern char *__progname;
118 
119 /* Saves a copy of argv for setproctitle emulation */
120 #ifndef HAVE_SETPROCTITLE
121 static char **saved_av;
122 #endif
123 
124 /* Flag indicating whether debug mode is on.  May be set on the command line. */
125 int debug_flag = 0;
126 
127 /* Flag indicating whether a tty should be requested */
128 int tty_flag = 0;
129 
130 /*
131  * Flag indicating that the current process should be backgrounded and
132  * a new mux-client launched in the foreground for ControlPersist.
133  */
134 int need_controlpersist_detach = 0;
135 
136 /* Copies of flags for ControlPersist foreground mux-client */
137 int ostdin_null_flag, osession_type, otty_flag, orequest_tty;
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
usage(void)180 usage(void)
181 {
182 	fprintf(stderr,
183 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]\n"
184 "           [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]\n"
185 "           [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]\n"
186 "           [-i identity_file] [-J [user@]host[:port]] [-L address]\n"
187 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
188 "           [-Q query_option] [-R address] [-S ctl_path] [-W host:port]\n"
189 "           [-w local_tun[:remote_tun]] 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
tilde_expand_paths(char ** paths,u_int num_paths)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 *
default_client_percent_expand(const char * str,const struct ssh_conn_info * cinfo)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 *
default_client_percent_dollar_expand(const char * str,const struct ssh_conn_info * cinfo)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 *
resolve_host(const char * name,int port,int logerr,char * cname,size_t clen)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
is_addr_fast(const char * name)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
is_addr(const char * name)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 *
resolve_addr(const char * name,int port,char * caddr,size_t clen)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
check_follow_cname(int direct,char ** namep,const char * cname)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 *
resolve_canonicalize(char ** hostp,int port)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 	    options.jump_host == NULL;
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
check_load(int r,struct sshkey ** k,const char * path,const char * message)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
process_config_files(const char * host_name,struct passwd * pw,int final_pass,int * want_final_pass)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
set_addrinfo_port(struct addrinfo * addrs,int port)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
ssh_conn_info_free(struct ssh_conn_info * cinfo)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
main(int ac,char ** av)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, *host_arg;
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);
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:PQ: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':	/* deprecated */
777 			break;
778 		case 'Q':
779 			cp = NULL;
780 			if (strcmp(optarg, "cipher") == 0 ||
781 			    strcasecmp(optarg, "Ciphers") == 0)
782 				cp = cipher_alg_list('\n', 0);
783 			else if (strcmp(optarg, "cipher-auth") == 0)
784 				cp = cipher_alg_list('\n', 1);
785 			else if (strcmp(optarg, "mac") == 0 ||
786 			    strcasecmp(optarg, "MACs") == 0)
787 				cp = mac_alg_list('\n');
788 			else if (strcmp(optarg, "kex") == 0 ||
789 			    strcasecmp(optarg, "KexAlgorithms") == 0)
790 				cp = kex_alg_list('\n');
791 			else if (strcmp(optarg, "key") == 0)
792 				cp = sshkey_alg_list(0, 0, 0, '\n');
793 			else if (strcmp(optarg, "key-cert") == 0)
794 				cp = sshkey_alg_list(1, 0, 0, '\n');
795 			else if (strcmp(optarg, "key-plain") == 0)
796 				cp = sshkey_alg_list(0, 1, 0, '\n');
797 			else if (strcmp(optarg, "key-sig") == 0 ||
798 			    strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
799 			    strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
800 			    strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
801 			    strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
802 			    strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
803 			    strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
804 				cp = sshkey_alg_list(0, 0, 1, '\n');
805 			else if (strcmp(optarg, "sig") == 0)
806 				cp = sshkey_alg_list(0, 1, 1, '\n');
807 			else if (strcmp(optarg, "protocol-version") == 0)
808 				cp = xstrdup("2");
809 			else if (strcmp(optarg, "compression") == 0) {
810 				cp = xstrdup(compression_alg_list(0));
811 				len = strlen(cp);
812 				for (n = 0; n < len; n++)
813 					if (cp[n] == ',')
814 						cp[n] = '\n';
815 			} else if (strcmp(optarg, "help") == 0) {
816 				cp = xstrdup(
817 				    "cipher\ncipher-auth\ncompression\nkex\n"
818 				    "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
819 				    "protocol-version\nsig");
820 			}
821 			if (cp == NULL)
822 				fatal("Unsupported query \"%s\"", optarg);
823 			printf("%s\n", cp);
824 			free(cp);
825 			exit(0);
826 			break;
827 		case 'a':
828 			options.forward_agent = 0;
829 			break;
830 		case 'A':
831 			options.forward_agent = 1;
832 			break;
833 		case 'k':
834 			options.gss_deleg_creds = 0;
835 			break;
836 		case 'K':
837 			options.gss_authentication = 1;
838 			options.gss_deleg_creds = 1;
839 			break;
840 		case 'i':
841 			p = tilde_expand_filename(optarg, getuid());
842 			if (stat(p, &st) == -1)
843 				fprintf(stderr, "Warning: Identity file %s "
844 				    "not accessible: %s.\n", p,
845 				    strerror(errno));
846 			else
847 				add_identity_file(&options, NULL, p, 1);
848 			free(p);
849 			break;
850 		case 'I':
851 #ifdef ENABLE_PKCS11
852 			free(options.pkcs11_provider);
853 			options.pkcs11_provider = xstrdup(optarg);
854 #else
855 			fprintf(stderr, "no support for PKCS#11.\n");
856 #endif
857 			break;
858 		case 'J':
859 			if (options.jump_host != NULL) {
860 				fatal("Only a single -J option is permitted "
861 				    "(use commas to separate multiple "
862 				    "jump hops)");
863 			}
864 			if (options.proxy_command != NULL)
865 				fatal("Cannot specify -J with ProxyCommand");
866 			if (parse_jump(optarg, &options, 1) == -1)
867 				fatal("Invalid -J argument");
868 			options.proxy_command = xstrdup("none");
869 			break;
870 		case 't':
871 			if (options.request_tty == REQUEST_TTY_YES)
872 				options.request_tty = REQUEST_TTY_FORCE;
873 			else
874 				options.request_tty = REQUEST_TTY_YES;
875 			break;
876 		case 'v':
877 			if (debug_flag == 0) {
878 				debug_flag = 1;
879 				options.log_level = SYSLOG_LEVEL_DEBUG1;
880 			} else {
881 				if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
882 					debug_flag++;
883 					options.log_level++;
884 				}
885 			}
886 			break;
887 		case 'V':
888 			if (options.version_addendum != NULL &&
889 			    *options.version_addendum != '\0')
890 				fprintf(stderr, "%s %s, %s\n", SSH_RELEASE,
891 				    options.version_addendum,
892 				    SSH_OPENSSL_VERSION);
893 			else
894 				fprintf(stderr, "%s, %s\n", SSH_RELEASE,
895 				    SSH_OPENSSL_VERSION);
896 			if (opt == 'V')
897 				exit(0);
898 			break;
899 		case 'w':
900 			if (options.tun_open == -1)
901 				options.tun_open = SSH_TUNMODE_DEFAULT;
902 			options.tun_local = a2tun(optarg, &options.tun_remote);
903 			if (options.tun_local == SSH_TUNID_ERR) {
904 				fprintf(stderr,
905 				    "Bad tun device '%s'\n", optarg);
906 				exit(255);
907 			}
908 			break;
909 		case 'W':
910 			if (options.stdio_forward_host != NULL)
911 				fatal("stdio forward already specified");
912 			if (muxclient_command != 0)
913 				fatal("Cannot specify stdio forward with -O");
914 			if (parse_forward(&fwd, optarg, 1, 0)) {
915 				options.stdio_forward_host = 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 	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 		/* version_addendum is always NULL at this point */
1165 		logit("%s, %s", SSH_RELEASE, SSH_OPENSSL_VERSION);
1166 
1167 	/* Parse the configuration files */
1168 	process_config_files(host_arg, pw, 0, &want_final_pass);
1169 	if (want_final_pass)
1170 		debug("configuration requests final Match pass");
1171 
1172 	/* Hostname canonicalisation needs a few options filled. */
1173 	fill_default_options_for_canonicalization(&options);
1174 
1175 	/* If the user has replaced the hostname then take it into use now */
1176 	if (options.hostname != NULL) {
1177 		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
1178 		cp = percent_expand(options.hostname,
1179 		    "h", host, (char *)NULL);
1180 		free(host);
1181 		host = cp;
1182 		free(options.hostname);
1183 		options.hostname = xstrdup(host);
1184 	}
1185 
1186 	/* Don't lowercase addresses, they will be explicitly canonicalised */
1187 	if ((was_addr = is_addr(host)) == 0)
1188 		lowercase(host);
1189 
1190 	/*
1191 	 * Try to canonicalize if requested by configuration or the
1192 	 * hostname is an address.
1193 	 */
1194 	if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1195 		addrs = resolve_canonicalize(&host, options.port);
1196 
1197 	/*
1198 	 * If CanonicalizePermittedCNAMEs have been specified but
1199 	 * other canonicalization did not happen (by not being requested
1200 	 * or by failing with fallback) then the hostname may still be changed
1201 	 * as a result of CNAME following.
1202 	 *
1203 	 * Try to resolve the bare hostname name using the system resolver's
1204 	 * usual search rules and then apply the CNAME follow rules.
1205 	 *
1206 	 * Skip the lookup if a ProxyCommand is being used unless the user
1207 	 * has specifically requested canonicalisation for this case via
1208 	 * CanonicalizeHostname=always
1209 	 */
1210 	direct = option_clear_or_none(options.proxy_command) &&
1211 	    options.jump_host == NULL;
1212 	if (addrs == NULL && config_has_permitted_cnames(&options) && (direct ||
1213 	    options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1214 		if ((addrs = resolve_host(host, options.port,
1215 		    direct, cname, sizeof(cname))) == NULL) {
1216 			/* Don't fatal proxied host names not in the DNS */
1217 			if (direct)
1218 				cleanup_exit(255); /* logged in resolve_host */
1219 		} else
1220 			check_follow_cname(direct, &host, cname);
1221 	}
1222 
1223 	/*
1224 	 * If canonicalisation is enabled then re-parse the configuration
1225 	 * files as new stanzas may match.
1226 	 */
1227 	if (options.canonicalize_hostname != 0 && !want_final_pass) {
1228 		debug("hostname canonicalisation enabled, "
1229 		    "will re-parse configuration");
1230 		want_final_pass = 1;
1231 	}
1232 
1233 	if (want_final_pass) {
1234 		debug("re-parsing configuration");
1235 		free(options.hostname);
1236 		options.hostname = xstrdup(host);
1237 		process_config_files(host_arg, pw, 1, NULL);
1238 		/*
1239 		 * Address resolution happens early with canonicalisation
1240 		 * enabled and the port number may have changed since, so
1241 		 * reset it in address list
1242 		 */
1243 		if (addrs != NULL && options.port > 0)
1244 			set_addrinfo_port(addrs, options.port);
1245 	}
1246 
1247 	/* Fill configuration defaults. */
1248 	if (fill_default_options(&options) != 0)
1249 		cleanup_exit(255);
1250 
1251 	if (options.user == NULL)
1252 		options.user = xstrdup(pw->pw_name);
1253 
1254 	/*
1255 	 * If ProxyJump option specified, then construct a ProxyCommand now.
1256 	 */
1257 	if (options.jump_host != NULL) {
1258 		char port_s[8];
1259 		const char *jumpuser = options.jump_user, *sshbin = argv0;
1260 		int port = options.port, jumpport = options.jump_port;
1261 
1262 		if (port <= 0)
1263 			port = default_ssh_port();
1264 		if (jumpport <= 0)
1265 			jumpport = default_ssh_port();
1266 		if (jumpuser == NULL)
1267 			jumpuser = options.user;
1268 		if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1269 		    strcmp(options.user, jumpuser) == 0)
1270 			fatal("jumphost loop via %s", options.jump_host);
1271 
1272 		/*
1273 		 * Try to use SSH indicated by argv[0], but fall back to
1274 		 * "ssh" if it appears unavailable.
1275 		 */
1276 		if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1277 			sshbin = "ssh";
1278 
1279 		/* Consistency check */
1280 		if (options.proxy_command != NULL)
1281 			fatal("inconsistent options: ProxyCommand+ProxyJump");
1282 		/* Never use FD passing for ProxyJump */
1283 		options.proxy_use_fdpass = 0;
1284 		snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1285 		xasprintf(&options.proxy_command,
1286 		    "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1287 		    sshbin,
1288 		    /* Optional "-l user" argument if jump_user set */
1289 		    options.jump_user == NULL ? "" : " -l ",
1290 		    options.jump_user == NULL ? "" : options.jump_user,
1291 		    /* Optional "-p port" argument if jump_port set */
1292 		    options.jump_port <= 0 ? "" : " -p ",
1293 		    options.jump_port <= 0 ? "" : port_s,
1294 		    /* Optional additional jump hosts ",..." */
1295 		    options.jump_extra == NULL ? "" : " -J ",
1296 		    options.jump_extra == NULL ? "" : options.jump_extra,
1297 		    /* Optional "-F" argument if -F specified */
1298 		    config == NULL ? "" : " -F ",
1299 		    config == NULL ? "" : config,
1300 		    /* Optional "-v" arguments if -v set */
1301 		    debug_flag ? " -" : "",
1302 		    debug_flag, "vvv",
1303 		    /* Mandatory hostname */
1304 		    options.jump_host);
1305 		debug("Setting implicit ProxyCommand from ProxyJump: %s",
1306 		    options.proxy_command);
1307 	}
1308 
1309 	if (options.port == 0)
1310 		options.port = default_ssh_port();
1311 	channel_set_af(ssh, options.address_family);
1312 
1313 	/* Tidy and check options */
1314 	if (options.host_key_alias != NULL)
1315 		lowercase(options.host_key_alias);
1316 	if (options.proxy_command != NULL &&
1317 	    strcmp(options.proxy_command, "-") == 0 &&
1318 	    options.proxy_use_fdpass)
1319 		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1320 	if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1321 		if (options.control_persist && options.control_path != NULL) {
1322 			debug("UpdateHostKeys=ask is incompatible with "
1323 			    "ControlPersist; disabling");
1324 			options.update_hostkeys = 0;
1325 		} else if (sshbuf_len(command) != 0 ||
1326 		    options.remote_command != NULL ||
1327 		    options.request_tty == REQUEST_TTY_NO) {
1328 			debug("UpdateHostKeys=ask is incompatible with "
1329 			    "remote command execution; disabling");
1330 			options.update_hostkeys = 0;
1331 		} else if (options.log_level < SYSLOG_LEVEL_INFO) {
1332 			/* no point logging anything; user won't see it */
1333 			options.update_hostkeys = 0;
1334 		}
1335 	}
1336 	if (options.connection_attempts <= 0)
1337 		fatal("Invalid number of ConnectionAttempts");
1338 
1339 	if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1340 		fatal("Cannot execute command-line and remote command.");
1341 
1342 	/* Cannot fork to background if no command. */
1343 	if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
1344 	    options.remote_command == NULL &&
1345 	    options.session_type != SESSION_TYPE_NONE)
1346 		fatal("Cannot fork into background without a command "
1347 		    "to execute.");
1348 
1349 	/* reinit */
1350 	log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1351 	for (j = 0; j < options.num_log_verbose; j++) {
1352 		if (strcasecmp(options.log_verbose[j], "none") == 0)
1353 			break;
1354 		log_verbose_add(options.log_verbose[j]);
1355 	}
1356 
1357 	if (options.request_tty == REQUEST_TTY_YES ||
1358 	    options.request_tty == REQUEST_TTY_FORCE)
1359 		tty_flag = 1;
1360 
1361 	/* Allocate a tty by default if no command specified. */
1362 	if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1363 		tty_flag = options.request_tty != REQUEST_TTY_NO;
1364 
1365 	/* Force no tty */
1366 	if (options.request_tty == REQUEST_TTY_NO ||
1367 	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY) ||
1368 	    options.session_type == SESSION_TYPE_NONE)
1369 		tty_flag = 0;
1370 	/* Do not allocate a tty if stdin is not a tty. */
1371 	if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1372 	    options.request_tty != REQUEST_TTY_FORCE) {
1373 		if (tty_flag)
1374 			logit("Pseudo-terminal will not be allocated because "
1375 			    "stdin is not a terminal.");
1376 		tty_flag = 0;
1377 	}
1378 
1379 	/* Set up strings used to percent_expand() arguments */
1380 	cinfo = xcalloc(1, sizeof(*cinfo));
1381 	if (gethostname(thishost, sizeof(thishost)) == -1)
1382 		fatal("gethostname: %s", strerror(errno));
1383 	cinfo->thishost = xstrdup(thishost);
1384 	thishost[strcspn(thishost, ".")] = '\0';
1385 	cinfo->shorthost = xstrdup(thishost);
1386 	xasprintf(&cinfo->portstr, "%d", options.port);
1387 	xasprintf(&cinfo->uidstr, "%llu",
1388 	    (unsigned long long)pw->pw_uid);
1389 	cinfo->keyalias = xstrdup(options.host_key_alias ?
1390 	    options.host_key_alias : host_arg);
1391 	cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
1392 	    cinfo->portstr, options.user);
1393 	cinfo->host_arg = xstrdup(host_arg);
1394 	cinfo->remhost = xstrdup(host);
1395 	cinfo->remuser = xstrdup(options.user);
1396 	cinfo->homedir = xstrdup(pw->pw_dir);
1397 	cinfo->locuser = xstrdup(pw->pw_name);
1398 
1399 	/* Find canonic host name. */
1400 	if (strchr(host, '.') == NULL) {
1401 		struct addrinfo hints;
1402 		struct addrinfo *ai = NULL;
1403 		int errgai;
1404 
1405 		memset(&hints, 0, sizeof(hints));
1406 		hints.ai_family = options.address_family;
1407 		hints.ai_flags = AI_CANONNAME;
1408 		hints.ai_socktype = SOCK_STREAM;
1409 		errgai = getaddrinfo(host, NULL, &hints, &ai);
1410 		if (errgai == 0) {
1411 			if (ai->ai_canonname != NULL) {
1412 				free(host);
1413 				host = xstrdup(ai->ai_canonname);
1414 			}
1415 			freeaddrinfo(ai);
1416 		}
1417 	}
1418 
1419 	/*
1420 	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1421 	 * after port-forwarding is set up, so it may pick up any local
1422 	 * tunnel interface name allocated.
1423 	 */
1424 	if (options.remote_command != NULL) {
1425 		debug3("expanding RemoteCommand: %s", options.remote_command);
1426 		cp = options.remote_command;
1427 		options.remote_command = default_client_percent_expand(cp,
1428 		    cinfo);
1429 		debug3("expanded RemoteCommand: %s", options.remote_command);
1430 		free(cp);
1431 		if ((r = sshbuf_put(command, options.remote_command,
1432 		    strlen(options.remote_command))) != 0)
1433 			fatal_fr(r, "buffer error");
1434 	}
1435 
1436 	if (options.control_path != NULL) {
1437 		cp = tilde_expand_filename(options.control_path, getuid());
1438 		free(options.control_path);
1439 		options.control_path = default_client_percent_dollar_expand(cp,
1440 		    cinfo);
1441 		free(cp);
1442 	}
1443 
1444 	if (options.identity_agent != NULL) {
1445 		p = tilde_expand_filename(options.identity_agent, getuid());
1446 		cp = default_client_percent_dollar_expand(p, cinfo);
1447 		free(p);
1448 		free(options.identity_agent);
1449 		options.identity_agent = cp;
1450 	}
1451 
1452 	if (options.forward_agent_sock_path != NULL) {
1453 		p = tilde_expand_filename(options.forward_agent_sock_path,
1454 		    getuid());
1455 		cp = default_client_percent_dollar_expand(p, cinfo);
1456 		free(p);
1457 		free(options.forward_agent_sock_path);
1458 		options.forward_agent_sock_path = cp;
1459 		if (stat(options.forward_agent_sock_path, &st) != 0) {
1460 			error("Cannot forward agent socket path \"%s\": %s",
1461 			    options.forward_agent_sock_path, strerror(errno));
1462 			if (options.exit_on_forward_failure)
1463 				cleanup_exit(255);
1464 		}
1465 	}
1466 
1467 	if (options.num_system_hostfiles > 0 &&
1468 	    strcasecmp(options.system_hostfiles[0], "none") == 0) {
1469 		if (options.num_system_hostfiles > 1)
1470 			fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1471 			    "appears with other entries");
1472 		free(options.system_hostfiles[0]);
1473 		options.system_hostfiles[0] = NULL;
1474 		options.num_system_hostfiles = 0;
1475 	}
1476 
1477 	if (options.num_user_hostfiles > 0 &&
1478 	    strcasecmp(options.user_hostfiles[0], "none") == 0) {
1479 		if (options.num_user_hostfiles > 1)
1480 			fatal("Invalid UserKnownHostsFiles: \"none\" "
1481 			    "appears with other entries");
1482 		free(options.user_hostfiles[0]);
1483 		options.user_hostfiles[0] = NULL;
1484 		options.num_user_hostfiles = 0;
1485 	}
1486 	for (j = 0; j < options.num_user_hostfiles; j++) {
1487 		if (options.user_hostfiles[j] == NULL)
1488 			continue;
1489 		cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1490 		p = default_client_percent_dollar_expand(cp, cinfo);
1491 		if (strcmp(options.user_hostfiles[j], p) != 0)
1492 			debug3("expanded UserKnownHostsFile '%s' -> "
1493 			    "'%s'", options.user_hostfiles[j], p);
1494 		free(options.user_hostfiles[j]);
1495 		free(cp);
1496 		options.user_hostfiles[j] = p;
1497 	}
1498 
1499 	for (i = 0; i < options.num_local_forwards; i++) {
1500 		if (options.local_forwards[i].listen_path != NULL) {
1501 			cp = options.local_forwards[i].listen_path;
1502 			p = options.local_forwards[i].listen_path =
1503 			    default_client_percent_expand(cp, cinfo);
1504 			if (strcmp(cp, p) != 0)
1505 				debug3("expanded LocalForward listen path "
1506 				    "'%s' -> '%s'", cp, p);
1507 			free(cp);
1508 		}
1509 		if (options.local_forwards[i].connect_path != NULL) {
1510 			cp = options.local_forwards[i].connect_path;
1511 			p = options.local_forwards[i].connect_path =
1512 			    default_client_percent_expand(cp, cinfo);
1513 			if (strcmp(cp, p) != 0)
1514 				debug3("expanded LocalForward connect path "
1515 				    "'%s' -> '%s'", cp, p);
1516 			free(cp);
1517 		}
1518 	}
1519 
1520 	for (i = 0; i < options.num_remote_forwards; i++) {
1521 		if (options.remote_forwards[i].listen_path != NULL) {
1522 			cp = options.remote_forwards[i].listen_path;
1523 			p = options.remote_forwards[i].listen_path =
1524 			    default_client_percent_expand(cp, cinfo);
1525 			if (strcmp(cp, p) != 0)
1526 				debug3("expanded RemoteForward listen path "
1527 				    "'%s' -> '%s'", cp, p);
1528 			free(cp);
1529 		}
1530 		if (options.remote_forwards[i].connect_path != NULL) {
1531 			cp = options.remote_forwards[i].connect_path;
1532 			p = options.remote_forwards[i].connect_path =
1533 			    default_client_percent_expand(cp, cinfo);
1534 			if (strcmp(cp, p) != 0)
1535 				debug3("expanded RemoteForward connect path "
1536 				    "'%s' -> '%s'", cp, p);
1537 			free(cp);
1538 		}
1539 	}
1540 
1541 	if (config_test) {
1542 		dump_client_config(&options, host);
1543 		exit(0);
1544 	}
1545 
1546 	/* Expand SecurityKeyProvider if it refers to an environment variable */
1547 	if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1548 	    strlen(options.sk_provider) > 1) {
1549 		if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1550 			debug("Authenticator provider %s did not resolve; "
1551 			    "disabling", options.sk_provider);
1552 			free(options.sk_provider);
1553 			options.sk_provider = NULL;
1554 		} else {
1555 			debug2("resolved SecurityKeyProvider %s => %s",
1556 			    options.sk_provider, cp);
1557 			free(options.sk_provider);
1558 			options.sk_provider = xstrdup(cp);
1559 		}
1560 	}
1561 
1562 	if (muxclient_command != 0 && options.control_path == NULL)
1563 		fatal("No ControlPath specified for \"-O\" command");
1564 	if (options.control_path != NULL) {
1565 		int sock;
1566 		if ((sock = muxclient(options.control_path)) >= 0) {
1567 			ssh_packet_set_connection(ssh, sock, sock);
1568 			ssh_packet_set_mux(ssh);
1569 			goto skip_connect;
1570 		}
1571 	}
1572 
1573 	/*
1574 	 * If hostname canonicalisation was not enabled, then we may not
1575 	 * have yet resolved the hostname. Do so now.
1576 	 */
1577 	if (addrs == NULL && options.proxy_command == NULL) {
1578 		debug2("resolving \"%s\" port %d", host, options.port);
1579 		if ((addrs = resolve_host(host, options.port, 1,
1580 		    cname, sizeof(cname))) == NULL)
1581 			cleanup_exit(255); /* resolve_host logs the error */
1582 	}
1583 
1584 	if (options.connection_timeout >= INT_MAX/1000)
1585 		timeout_ms = INT_MAX;
1586 	else
1587 		timeout_ms = options.connection_timeout * 1000;
1588 
1589 	/* Open a connection to the remote host. */
1590 	if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port,
1591 	    options.connection_attempts,
1592 	    &timeout_ms, options.tcp_keep_alive) != 0)
1593 		exit(255);
1594 
1595 	if (addrs != NULL)
1596 		freeaddrinfo(addrs);
1597 
1598 	ssh_packet_set_timeout(ssh, options.server_alive_interval,
1599 	    options.server_alive_count_max);
1600 
1601 	if (timeout_ms > 0)
1602 		debug3("timeout: %d ms remain after connect", timeout_ms);
1603 
1604 	/*
1605 	 * If we successfully made the connection and we have hostbased auth
1606 	 * enabled, load the public keys so we can later use the ssh-keysign
1607 	 * helper to sign challenges.
1608 	 */
1609 	sensitive_data.nkeys = 0;
1610 	sensitive_data.keys = NULL;
1611 	if (options.hostbased_authentication) {
1612 		sensitive_data.nkeys = 10;
1613 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1614 		    sizeof(struct sshkey));
1615 
1616 		/* XXX check errors? */
1617 #define L_PUBKEY(p,o) do { \
1618 	if ((o) >= sensitive_data.nkeys) \
1619 		fatal_f("pubkey out of array bounds"); \
1620 	check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1621 	    &(sensitive_data.keys[o]), p, "pubkey"); \
1622 	if (sensitive_data.keys[o] != NULL) \
1623 		debug2("hostbased key %d: %s key from \"%s\"", o, \
1624 		    sshkey_ssh_name(sensitive_data.keys[o]), p); \
1625 } while (0)
1626 #define L_CERT(p,o) do { \
1627 	if ((o) >= sensitive_data.nkeys) \
1628 		fatal_f("cert out of array bounds"); \
1629 	check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), \
1630 	    &(sensitive_data.keys[o]), p, "cert"); \
1631 	if (sensitive_data.keys[o] != NULL) \
1632 		debug2("hostbased key %d: %s cert from \"%s\"", o, \
1633 		    sshkey_ssh_name(sensitive_data.keys[o]), p); \
1634 } while (0)
1635 
1636 		if (options.hostbased_authentication == 1) {
1637 			L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1638 			L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1639 			L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1640 			L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1641 			L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1642 			L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1643 			L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1644 			L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1645 			L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1646 			L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1647 		}
1648 	}
1649 
1650 	/* load options.identity_files */
1651 	load_public_identity_files(cinfo);
1652 
1653 	/* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1654 	if (options.identity_agent &&
1655 	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1656 		if (strcmp(options.identity_agent, "none") == 0) {
1657 			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1658 		} else {
1659 			cp = options.identity_agent;
1660 			/* legacy (limited) format */
1661 			if (cp[0] == '$' && cp[1] != '{') {
1662 				if (!valid_env_name(cp + 1)) {
1663 					fatal("Invalid IdentityAgent "
1664 					    "environment variable name %s", cp);
1665 				}
1666 				if ((p = getenv(cp + 1)) == NULL)
1667 					unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1668 				else
1669 					setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1670 			} else {
1671 				/* identity_agent specifies a path directly */
1672 				setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1673 			}
1674 		}
1675 	}
1676 
1677 	if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1678 		cp = options.forward_agent_sock_path;
1679 		if (cp[0] == '$') {
1680 			if (!valid_env_name(cp + 1)) {
1681 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1682 			}
1683 			if ((p = getenv(cp + 1)) != NULL)
1684 				forward_agent_sock_path = xstrdup(p);
1685 			else
1686 				options.forward_agent = 0;
1687 			free(cp);
1688 		} else {
1689 			forward_agent_sock_path = cp;
1690 		}
1691 	}
1692 
1693 	/* Expand ~ in known host file names. */
1694 	tilde_expand_paths(options.system_hostfiles,
1695 	    options.num_system_hostfiles);
1696 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1697 
1698 	ssh_signal(SIGCHLD, main_sigchld_handler);
1699 
1700 	/* Log into the remote system.  Never returns if the login fails. */
1701 	ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1702 	    options.port, pw, timeout_ms, cinfo);
1703 
1704 	/* We no longer need the private host keys.  Clear them now. */
1705 	if (sensitive_data.nkeys != 0) {
1706 		for (i = 0; i < sensitive_data.nkeys; i++) {
1707 			if (sensitive_data.keys[i] != NULL) {
1708 				/* Destroys contents safely */
1709 				debug3("clear hostkey %d", i);
1710 				sshkey_free(sensitive_data.keys[i]);
1711 				sensitive_data.keys[i] = NULL;
1712 			}
1713 		}
1714 		free(sensitive_data.keys);
1715 	}
1716 	for (i = 0; i < options.num_identity_files; i++) {
1717 		free(options.identity_files[i]);
1718 		options.identity_files[i] = NULL;
1719 		if (options.identity_keys[i]) {
1720 			sshkey_free(options.identity_keys[i]);
1721 			options.identity_keys[i] = NULL;
1722 		}
1723 	}
1724 	for (i = 0; i < options.num_certificate_files; i++) {
1725 		free(options.certificate_files[i]);
1726 		options.certificate_files[i] = NULL;
1727 	}
1728 
1729 #ifdef ENABLE_PKCS11
1730 	(void)pkcs11_del_provider(options.pkcs11_provider);
1731 #endif
1732 
1733  skip_connect:
1734 	exit_status = ssh_session2(ssh, cinfo);
1735 	ssh_conn_info_free(cinfo);
1736 	ssh_packet_close(ssh);
1737 
1738 	if (options.control_path != NULL && muxserver_sock != -1)
1739 		unlink(options.control_path);
1740 
1741 	/* Kill ProxyCommand if it is running. */
1742 	ssh_kill_proxy_command();
1743 
1744 	return exit_status;
1745 }
1746 
1747 static void
control_persist_detach(void)1748 control_persist_detach(void)
1749 {
1750 	pid_t pid;
1751 
1752 	debug_f("backgrounding master process");
1753 
1754 	/*
1755 	 * master (current process) into the background, and make the
1756 	 * foreground process a client of the backgrounded master.
1757 	 */
1758 	switch ((pid = fork())) {
1759 	case -1:
1760 		fatal_f("fork: %s", strerror(errno));
1761 	case 0:
1762 		/* Child: master process continues mainloop */
1763 		break;
1764 	default:
1765 		/* Parent: set up mux client to connect to backgrounded master */
1766 		debug2_f("background process is %ld", (long)pid);
1767 		options.stdin_null = ostdin_null_flag;
1768 		options.request_tty = orequest_tty;
1769 		tty_flag = otty_flag;
1770 		options.session_type = osession_type;
1771 		close(muxserver_sock);
1772 		muxserver_sock = -1;
1773 		options.control_master = SSHCTL_MASTER_NO;
1774 		muxclient(options.control_path);
1775 		/* muxclient() doesn't return on success. */
1776 		fatal("Failed to connect to new control master");
1777 	}
1778 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1779 		error_f("stdfd_devnull failed");
1780 	daemon(1, 1);
1781 	setproctitle("%s [mux]", options.control_path);
1782 }
1783 
1784 /* Do fork() after authentication. Used by "ssh -f" */
1785 static void
fork_postauth(void)1786 fork_postauth(void)
1787 {
1788 	if (need_controlpersist_detach)
1789 		control_persist_detach();
1790 	debug("forking to background");
1791 	options.fork_after_authentication = 0;
1792 	if (daemon(1, 1) == -1)
1793 		fatal("daemon() failed: %.200s", strerror(errno));
1794 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1795 		error_f("stdfd_devnull failed");
1796 }
1797 
1798 static void
forwarding_success(void)1799 forwarding_success(void)
1800 {
1801 	if (forward_confirms_pending == -1)
1802 		return;
1803 	if (--forward_confirms_pending == 0) {
1804 		debug_f("all expected forwarding replies received");
1805 		if (options.fork_after_authentication)
1806 			fork_postauth();
1807 	} else {
1808 		debug2_f("%d expected forwarding replies remaining",
1809 		    forward_confirms_pending);
1810 	}
1811 }
1812 
1813 /* Callback for remote forward global requests */
1814 static void
ssh_confirm_remote_forward(struct ssh * ssh,int type,u_int32_t seq,void * ctxt)1815 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1816 {
1817 	struct Forward *rfwd = (struct Forward *)ctxt;
1818 	u_int port;
1819 	int r;
1820 
1821 	/* XXX verbose() on failure? */
1822 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1823 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1824 	    rfwd->listen_path ? rfwd->listen_path :
1825 	    rfwd->listen_host ? rfwd->listen_host : "",
1826 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1827 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1828 	    rfwd->connect_host, rfwd->connect_port);
1829 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1830 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1831 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1832 				fatal_fr(r, "parse packet");
1833 			if (port > 65535) {
1834 				error("Invalid allocated port %u for remote "
1835 				    "forward to %s:%d", port,
1836 				    rfwd->connect_host, rfwd->connect_port);
1837 				/* Ensure failure processing runs below */
1838 				type = SSH2_MSG_REQUEST_FAILURE;
1839 				channel_update_permission(ssh,
1840 				    rfwd->handle, -1);
1841 			} else {
1842 				rfwd->allocated_port = (int)port;
1843 				logit("Allocated port %u for remote "
1844 				    "forward to %s:%d",
1845 				    rfwd->allocated_port, rfwd->connect_path ?
1846 				    rfwd->connect_path : rfwd->connect_host,
1847 				    rfwd->connect_port);
1848 				channel_update_permission(ssh,
1849 				    rfwd->handle, rfwd->allocated_port);
1850 			}
1851 		} else {
1852 			channel_update_permission(ssh, rfwd->handle, -1);
1853 		}
1854 	}
1855 
1856 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1857 		if (options.exit_on_forward_failure) {
1858 			if (rfwd->listen_path != NULL)
1859 				fatal("Error: remote port forwarding failed "
1860 				    "for listen path %s", rfwd->listen_path);
1861 			else
1862 				fatal("Error: remote port forwarding failed "
1863 				    "for listen port %d", rfwd->listen_port);
1864 		} else {
1865 			if (rfwd->listen_path != NULL)
1866 				logit("Warning: remote port forwarding failed "
1867 				    "for listen path %s", rfwd->listen_path);
1868 			else
1869 				logit("Warning: remote port forwarding failed "
1870 				    "for listen port %d", rfwd->listen_port);
1871 		}
1872 	}
1873 	forwarding_success();
1874 }
1875 
1876 static void
client_cleanup_stdio_fwd(struct ssh * ssh,int id,void * arg)1877 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1878 {
1879 	debug("stdio forwarding: done");
1880 	cleanup_exit(0);
1881 }
1882 
1883 static void
ssh_stdio_confirm(struct ssh * ssh,int id,int success,void * arg)1884 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1885 {
1886 	if (!success)
1887 		fatal("stdio forwarding failed");
1888 }
1889 
1890 static void
ssh_tun_confirm(struct ssh * ssh,int id,int success,void * arg)1891 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1892 {
1893 	if (!success) {
1894 		error("Tunnel forwarding failed");
1895 		if (options.exit_on_forward_failure)
1896 			cleanup_exit(255);
1897 	}
1898 
1899 	debug_f("tunnel forward established, id=%d", id);
1900 	forwarding_success();
1901 }
1902 
1903 static void
ssh_init_stdio_forwarding(struct ssh * ssh)1904 ssh_init_stdio_forwarding(struct ssh *ssh)
1905 {
1906 	Channel *c;
1907 	int in, out;
1908 
1909 	if (options.stdio_forward_host == NULL)
1910 		return;
1911 
1912 	debug3_f("%s:%d", options.stdio_forward_host,
1913 	    options.stdio_forward_port);
1914 
1915 	if ((in = dup(STDIN_FILENO)) == -1 ||
1916 	    (out = dup(STDOUT_FILENO)) == -1)
1917 		fatal_f("dup() in/out failed");
1918 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1919 	    options.stdio_forward_port, in, out,
1920 	    CHANNEL_NONBLOCK_STDIO)) == NULL)
1921 		fatal_f("channel_connect_stdio_fwd failed");
1922 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1923 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1924 }
1925 
1926 static void
ssh_init_forward_permissions(struct ssh * ssh,const char * what,char ** opens,u_int num_opens)1927 ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
1928     u_int num_opens)
1929 {
1930 	u_int i;
1931 	int port;
1932 	char *addr, *arg, *oarg;
1933 	int where = FORWARD_LOCAL;
1934 
1935 	channel_clear_permission(ssh, FORWARD_ADM, where);
1936 	if (num_opens == 0)
1937 		return; /* permit any */
1938 
1939 	/* handle keywords: "any" / "none" */
1940 	if (num_opens == 1 && strcmp(opens[0], "any") == 0)
1941 		return;
1942 	if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
1943 		channel_disable_admin(ssh, where);
1944 		return;
1945 	}
1946 	/* Otherwise treat it as a list of permitted host:port */
1947 	for (i = 0; i < num_opens; i++) {
1948 		oarg = arg = xstrdup(opens[i]);
1949 		addr = hpdelim(&arg);
1950 		if (addr == NULL)
1951 			fatal_f("missing host in %s", what);
1952 		addr = cleanhostname(addr);
1953 		if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1954 			fatal_f("bad port number in %s", what);
1955 		/* Send it to channels layer */
1956 		channel_add_permission(ssh, FORWARD_ADM,
1957 		    where, addr, port);
1958 		free(oarg);
1959 	}
1960 }
1961 
1962 static void
ssh_init_forwarding(struct ssh * ssh,char ** ifname)1963 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1964 {
1965 	int success = 0;
1966 	int i;
1967 
1968 	ssh_init_forward_permissions(ssh, "permitremoteopen",
1969 	    options.permitted_remote_opens,
1970 	    options.num_permitted_remote_opens);
1971 
1972 	if (options.exit_on_forward_failure)
1973 		forward_confirms_pending = 0; /* track pending requests */
1974 	/* Initiate local TCP/IP port forwardings. */
1975 	for (i = 0; i < options.num_local_forwards; i++) {
1976 		debug("Local connections to %.200s:%d forwarded to remote "
1977 		    "address %.200s:%d",
1978 		    (options.local_forwards[i].listen_path != NULL) ?
1979 		    options.local_forwards[i].listen_path :
1980 		    (options.local_forwards[i].listen_host == NULL) ?
1981 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1982 		    options.local_forwards[i].listen_host,
1983 		    options.local_forwards[i].listen_port,
1984 		    (options.local_forwards[i].connect_path != NULL) ?
1985 		    options.local_forwards[i].connect_path :
1986 		    options.local_forwards[i].connect_host,
1987 		    options.local_forwards[i].connect_port);
1988 		success += channel_setup_local_fwd_listener(ssh,
1989 		    &options.local_forwards[i], &options.fwd_opts);
1990 	}
1991 	if (i > 0 && success != i && options.exit_on_forward_failure)
1992 		fatal("Could not request local forwarding.");
1993 	if (i > 0 && success == 0)
1994 		error("Could not request local forwarding.");
1995 
1996 	/* Initiate remote TCP/IP port forwardings. */
1997 	for (i = 0; i < options.num_remote_forwards; i++) {
1998 		debug("Remote connections from %.200s:%d forwarded to "
1999 		    "local address %.200s:%d",
2000 		    (options.remote_forwards[i].listen_path != NULL) ?
2001 		    options.remote_forwards[i].listen_path :
2002 		    (options.remote_forwards[i].listen_host == NULL) ?
2003 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
2004 		    options.remote_forwards[i].listen_port,
2005 		    (options.remote_forwards[i].connect_path != NULL) ?
2006 		    options.remote_forwards[i].connect_path :
2007 		    options.remote_forwards[i].connect_host,
2008 		    options.remote_forwards[i].connect_port);
2009 		if ((options.remote_forwards[i].handle =
2010 		    channel_request_remote_forwarding(ssh,
2011 		    &options.remote_forwards[i])) >= 0) {
2012 			client_register_global_confirm(
2013 			    ssh_confirm_remote_forward,
2014 			    &options.remote_forwards[i]);
2015 			forward_confirms_pending++;
2016 		} else if (options.exit_on_forward_failure)
2017 			fatal("Could not request remote forwarding.");
2018 		else
2019 			logit("Warning: Could not request remote forwarding.");
2020 	}
2021 
2022 	/* Initiate tunnel forwarding. */
2023 	if (options.tun_open != SSH_TUNMODE_NO) {
2024 		if ((*ifname = client_request_tun_fwd(ssh,
2025 		    options.tun_open, options.tun_local,
2026 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
2027 			forward_confirms_pending++;
2028 		else if (options.exit_on_forward_failure)
2029 			fatal("Could not request tunnel forwarding.");
2030 		else
2031 			error("Could not request tunnel forwarding.");
2032 	}
2033 	if (forward_confirms_pending > 0) {
2034 		debug_f("expecting replies for %d forwards",
2035 		    forward_confirms_pending);
2036 	}
2037 }
2038 
2039 static void
check_agent_present(void)2040 check_agent_present(void)
2041 {
2042 	int r;
2043 
2044 	if (options.forward_agent) {
2045 		/* Clear agent forwarding if we don't have an agent. */
2046 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2047 			options.forward_agent = 0;
2048 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
2049 				debug_r(r, "ssh_get_authentication_socket");
2050 		}
2051 	}
2052 }
2053 
2054 static void
ssh_session2_setup(struct ssh * ssh,int id,int success,void * arg)2055 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2056 {
2057 	extern char **environ;
2058 	const char *display, *term;
2059 	int r, interactive = tty_flag;
2060 	char *proto = NULL, *data = NULL;
2061 
2062 	if (!success)
2063 		return; /* No need for error message, channels code sens one */
2064 
2065 	display = getenv("DISPLAY");
2066 	if (display == NULL && options.forward_x11)
2067 		debug("X11 forwarding requested but DISPLAY not set");
2068 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
2069 	    options.xauth_location, options.forward_x11_trusted,
2070 	    options.forward_x11_timeout, &proto, &data) == 0) {
2071 		/* Request forwarding with authentication spoofing. */
2072 		debug("Requesting X11 forwarding with authentication "
2073 		    "spoofing.");
2074 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2075 		    data, 1);
2076 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2077 		/* XXX exit_on_forward_failure */
2078 		interactive = 1;
2079 	}
2080 
2081 	check_agent_present();
2082 	if (options.forward_agent) {
2083 		debug("Requesting authentication agent forwarding.");
2084 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
2085 		if ((r = sshpkt_send(ssh)) != 0)
2086 			fatal_fr(r, "send packet");
2087 	}
2088 
2089 	/* Tell the packet module whether this is an interactive session. */
2090 	ssh_packet_set_interactive(ssh, interactive,
2091 	    options.ip_qos_interactive, options.ip_qos_bulk);
2092 
2093 	if ((term = lookup_env_in_list("TERM", options.setenv,
2094 	    options.num_setenv)) == NULL || *term == '\0')
2095 		term = getenv("TERM");
2096 	client_session2_setup(ssh, id, tty_flag,
2097 	    options.session_type == SESSION_TYPE_SUBSYSTEM, term,
2098 	    NULL, fileno(stdin), command, environ);
2099 }
2100 
2101 /* open new channel for a session */
2102 static int
ssh_session2_open(struct ssh * ssh)2103 ssh_session2_open(struct ssh *ssh)
2104 {
2105 	Channel *c;
2106 	int window, packetmax, in, out, err;
2107 
2108 	if (options.stdin_null) {
2109 		in = open(_PATH_DEVNULL, O_RDONLY);
2110 	} else {
2111 		in = dup(STDIN_FILENO);
2112 	}
2113 	out = dup(STDOUT_FILENO);
2114 	err = dup(STDERR_FILENO);
2115 
2116 	if (in == -1 || out == -1 || err == -1)
2117 		fatal("dup() in/out/err failed");
2118 
2119 	window = CHAN_SES_WINDOW_DEFAULT;
2120 	packetmax = CHAN_SES_PACKET_DEFAULT;
2121 	if (tty_flag) {
2122 		window >>= 1;
2123 		packetmax >>= 1;
2124 	}
2125 	c = channel_new(ssh,
2126 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2127 	    window, packetmax, CHAN_EXTENDED_WRITE,
2128 	    "client-session", CHANNEL_NONBLOCK_STDIO);
2129 
2130 	debug3_f("channel_new: %d", c->self);
2131 
2132 	channel_send_open(ssh, c->self);
2133 	if (options.session_type != SESSION_TYPE_NONE)
2134 		channel_register_open_confirm(ssh, c->self,
2135 		    ssh_session2_setup, NULL);
2136 
2137 	return c->self;
2138 }
2139 
2140 static int
ssh_session2(struct ssh * ssh,const struct ssh_conn_info * cinfo)2141 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2142 {
2143 	int r, id = -1;
2144 	char *cp, *tun_fwd_ifname = NULL;
2145 
2146 	/* XXX should be pre-session */
2147 	if (!options.control_persist)
2148 		ssh_init_stdio_forwarding(ssh);
2149 
2150 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2151 
2152 	if (options.local_command != NULL) {
2153 		debug3("expanding LocalCommand: %s", options.local_command);
2154 		cp = options.local_command;
2155 		options.local_command = percent_expand(cp,
2156 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2157 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2158 		    (char *)NULL);
2159 		debug3("expanded LocalCommand: %s", options.local_command);
2160 		free(cp);
2161 	}
2162 
2163 	/* Start listening for multiplex clients */
2164 	if (!ssh_packet_get_mux(ssh))
2165 		muxserver_listen(ssh);
2166 
2167 	/*
2168 	 * If we are in control persist mode and have a working mux listen
2169 	 * socket, then prepare to background ourselves and have a foreground
2170 	 * client attach as a control client.
2171 	 * NB. we must save copies of the flags that we override for
2172 	 * the backgrounding, since we defer attachment of the client until
2173 	 * after the connection is fully established (in particular,
2174 	 * async rfwd replies have been received for ExitOnForwardFailure).
2175 	 */
2176 	if (options.control_persist && muxserver_sock != -1) {
2177 		ostdin_null_flag = options.stdin_null;
2178 		osession_type = options.session_type;
2179 		orequest_tty = options.request_tty;
2180 		otty_flag = tty_flag;
2181 		options.stdin_null = 1;
2182 		options.session_type = SESSION_TYPE_NONE;
2183 		tty_flag = 0;
2184 		if (!options.fork_after_authentication &&
2185 		    (osession_type != SESSION_TYPE_NONE ||
2186 		    options.stdio_forward_host != NULL))
2187 			need_controlpersist_detach = 1;
2188 		options.fork_after_authentication = 1;
2189 	}
2190 	/*
2191 	 * ControlPersist mux listen socket setup failed, attempt the
2192 	 * stdio forward setup that we skipped earlier.
2193 	 */
2194 	if (options.control_persist && muxserver_sock == -1)
2195 		ssh_init_stdio_forwarding(ssh);
2196 
2197 	if (options.session_type != SESSION_TYPE_NONE)
2198 		id = ssh_session2_open(ssh);
2199 	else {
2200 		ssh_packet_set_interactive(ssh,
2201 		    options.control_master == SSHCTL_MASTER_NO,
2202 		    options.ip_qos_interactive, options.ip_qos_bulk);
2203 	}
2204 
2205 	/* If we don't expect to open a new session, then disallow it */
2206 	if (options.control_master == SSHCTL_MASTER_NO &&
2207 	    (ssh->compat & SSH_NEW_OPENSSH)) {
2208 		debug("Requesting no-more-sessions@openssh.com");
2209 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2210 		    (r = sshpkt_put_cstring(ssh,
2211 		    "no-more-sessions@openssh.com")) != 0 ||
2212 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2213 		    (r = sshpkt_send(ssh)) != 0)
2214 			fatal_fr(r, "send packet");
2215 	}
2216 
2217 	/* Execute a local command */
2218 	if (options.local_command != NULL &&
2219 	    options.permit_local_command)
2220 		ssh_local_cmd(options.local_command);
2221 
2222 	/*
2223 	 * stdout is now owned by the session channel; clobber it here
2224 	 * so future channel closes are propagated to the local fd.
2225 	 * NB. this can only happen after LocalCommand has completed,
2226 	 * as it may want to write to stdout.
2227 	 */
2228 	if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2229 		error_f("stdfd_devnull failed");
2230 
2231 	/*
2232 	 * If requested and we are not interested in replies to remote
2233 	 * forwarding requests, then let ssh continue in the background.
2234 	 */
2235 	if (options.fork_after_authentication) {
2236 		if (options.exit_on_forward_failure &&
2237 		    options.num_remote_forwards > 0) {
2238 			debug("deferring postauth fork until remote forward "
2239 			    "confirmation received");
2240 		} else
2241 			fork_postauth();
2242 	}
2243 
2244 	return client_loop(ssh, tty_flag, tty_flag ?
2245 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2246 }
2247 
2248 /* Loads all IdentityFile and CertificateFile keys */
2249 static void
load_public_identity_files(const struct ssh_conn_info * cinfo)2250 load_public_identity_files(const struct ssh_conn_info *cinfo)
2251 {
2252 	char *filename, *cp;
2253 	struct sshkey *public;
2254 	int i;
2255 	u_int n_ids, n_certs;
2256 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2257 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2258 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2259 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2260 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2261 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2262 #ifdef ENABLE_PKCS11
2263 	struct sshkey **keys = NULL;
2264 	char **comments = NULL;
2265 	int nkeys;
2266 #endif /* PKCS11 */
2267 
2268 	n_ids = n_certs = 0;
2269 	memset(identity_files, 0, sizeof(identity_files));
2270 	memset(identity_keys, 0, sizeof(identity_keys));
2271 	memset(identity_file_userprovided, 0,
2272 	    sizeof(identity_file_userprovided));
2273 	memset(certificate_files, 0, sizeof(certificate_files));
2274 	memset(certificates, 0, sizeof(certificates));
2275 	memset(certificate_file_userprovided, 0,
2276 	    sizeof(certificate_file_userprovided));
2277 
2278 #ifdef ENABLE_PKCS11
2279 	if (options.pkcs11_provider != NULL &&
2280 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2281 	    (pkcs11_init(!options.batch_mode) == 0) &&
2282 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2283 	    &keys, &comments)) > 0) {
2284 		for (i = 0; i < nkeys; i++) {
2285 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2286 				sshkey_free(keys[i]);
2287 				free(comments[i]);
2288 				continue;
2289 			}
2290 			identity_keys[n_ids] = keys[i];
2291 			identity_files[n_ids] = comments[i]; /* transferred */
2292 			n_ids++;
2293 		}
2294 		free(keys);
2295 		free(comments);
2296 	}
2297 #endif /* ENABLE_PKCS11 */
2298 	for (i = 0; i < options.num_identity_files; i++) {
2299 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2300 		    strcasecmp(options.identity_files[i], "none") == 0) {
2301 			free(options.identity_files[i]);
2302 			options.identity_files[i] = NULL;
2303 			continue;
2304 		}
2305 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2306 		filename = default_client_percent_dollar_expand(cp, cinfo);
2307 		free(cp);
2308 		check_load(sshkey_load_public(filename, &public, NULL),
2309 		    &public, filename, "pubkey");
2310 		debug("identity file %s type %d", filename,
2311 		    public ? public->type : -1);
2312 		free(options.identity_files[i]);
2313 		identity_files[n_ids] = filename;
2314 		identity_keys[n_ids] = public;
2315 		identity_file_userprovided[n_ids] =
2316 		    options.identity_file_userprovided[i];
2317 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2318 			continue;
2319 
2320 		/*
2321 		 * If no certificates have been explicitly listed then try
2322 		 * to add the default certificate variant too.
2323 		 */
2324 		if (options.num_certificate_files != 0)
2325 			continue;
2326 		xasprintf(&cp, "%s-cert", filename);
2327 		check_load(sshkey_load_public(cp, &public, NULL),
2328 		    &public, filename, "pubkey");
2329 		debug("identity file %s type %d", cp,
2330 		    public ? public->type : -1);
2331 		if (public == NULL) {
2332 			free(cp);
2333 			continue;
2334 		}
2335 		if (!sshkey_is_cert(public)) {
2336 			debug_f("key %s type %s is not a certificate",
2337 			    cp, sshkey_type(public));
2338 			sshkey_free(public);
2339 			free(cp);
2340 			continue;
2341 		}
2342 		/* NB. leave filename pointing to private key */
2343 		identity_files[n_ids] = xstrdup(filename);
2344 		identity_keys[n_ids] = public;
2345 		identity_file_userprovided[n_ids] =
2346 		    options.identity_file_userprovided[i];
2347 		n_ids++;
2348 	}
2349 
2350 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2351 		fatal_f("too many certificates");
2352 	for (i = 0; i < options.num_certificate_files; i++) {
2353 		cp = tilde_expand_filename(options.certificate_files[i],
2354 		    getuid());
2355 		filename = default_client_percent_dollar_expand(cp, cinfo);
2356 		free(cp);
2357 
2358 		check_load(sshkey_load_public(filename, &public, NULL),
2359 		    &public, filename, "certificate");
2360 		debug("certificate file %s type %d", filename,
2361 		    public ? public->type : -1);
2362 		free(options.certificate_files[i]);
2363 		options.certificate_files[i] = NULL;
2364 		if (public == NULL) {
2365 			free(filename);
2366 			continue;
2367 		}
2368 		if (!sshkey_is_cert(public)) {
2369 			debug_f("key %s type %s is not a certificate",
2370 			    filename, sshkey_type(public));
2371 			sshkey_free(public);
2372 			free(filename);
2373 			continue;
2374 		}
2375 		certificate_files[n_certs] = filename;
2376 		certificates[n_certs] = public;
2377 		certificate_file_userprovided[n_certs] =
2378 		    options.certificate_file_userprovided[i];
2379 		++n_certs;
2380 	}
2381 
2382 	options.num_identity_files = n_ids;
2383 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2384 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2385 	memcpy(options.identity_file_userprovided,
2386 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2387 
2388 	options.num_certificate_files = n_certs;
2389 	memcpy(options.certificate_files,
2390 	    certificate_files, sizeof(certificate_files));
2391 	memcpy(options.certificates, certificates, sizeof(certificates));
2392 	memcpy(options.certificate_file_userprovided,
2393 	    certificate_file_userprovided,
2394 	    sizeof(certificate_file_userprovided));
2395 }
2396 
2397 static void
main_sigchld_handler(int sig)2398 main_sigchld_handler(int sig)
2399 {
2400 	int save_errno = errno;
2401 	pid_t pid;
2402 	int status;
2403 
2404 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2405 	    (pid == -1 && errno == EINTR))
2406 		;
2407 	errno = save_errno;
2408 }
2409