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