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