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