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