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