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