xref: /openssh-portable/ssh.c (revision 793b583d)
1 /* $OpenBSD: ssh.c,v 1.539 2020/10/16 13:26:13 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 	for (j = 0; j < options.num_log_verbose; j++)
1359 		log_verbose_add(options.log_verbose[j]);
1360 
1361 	if (options.request_tty == REQUEST_TTY_YES ||
1362 	    options.request_tty == REQUEST_TTY_FORCE)
1363 		tty_flag = 1;
1364 
1365 	/* Allocate a tty by default if no command specified. */
1366 	if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1367 		tty_flag = options.request_tty != REQUEST_TTY_NO;
1368 
1369 	/* Force no tty */
1370 	if (options.request_tty == REQUEST_TTY_NO ||
1371 	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1372 		tty_flag = 0;
1373 	/* Do not allocate a tty if stdin is not a tty. */
1374 	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1375 	    options.request_tty != REQUEST_TTY_FORCE) {
1376 		if (tty_flag)
1377 			logit("Pseudo-terminal will not be allocated because "
1378 			    "stdin is not a terminal.");
1379 		tty_flag = 0;
1380 	}
1381 
1382 	/* Set up strings used to percent_expand() arguments */
1383 	if (gethostname(thishost, sizeof(thishost)) == -1)
1384 		fatal("gethostname: %s", strerror(errno));
1385 	strlcpy(shorthost, thishost, sizeof(shorthost));
1386 	shorthost[strcspn(thishost, ".")] = '\0';
1387 	snprintf(portstr, sizeof(portstr), "%d", options.port);
1388 	snprintf(uidstr, sizeof(uidstr), "%llu",
1389 	    (unsigned long long)pw->pw_uid);
1390 	keyalias = options.host_key_alias ? options.host_key_alias : host_arg;
1391 
1392 	conn_hash_hex = ssh_connection_hash(thishost, host, portstr,
1393 	    options.user);
1394 
1395 	/*
1396 	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1397 	 * after port-forwarding is set up, so it may pick up any local
1398 	 * tunnel interface name allocated.
1399 	 */
1400 	if (options.remote_command != NULL) {
1401 		debug3("expanding RemoteCommand: %s", options.remote_command);
1402 		cp = options.remote_command;
1403 		options.remote_command = default_client_percent_expand(cp,
1404 		    pw->pw_dir, host, options.user, pw->pw_name);
1405 		debug3("expanded RemoteCommand: %s", options.remote_command);
1406 		free(cp);
1407 		if ((r = sshbuf_put(command, options.remote_command,
1408 		    strlen(options.remote_command))) != 0)
1409 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1410 	}
1411 
1412 	if (options.control_path != NULL) {
1413 		cp = tilde_expand_filename(options.control_path, getuid());
1414 		free(options.control_path);
1415 		options.control_path = default_client_percent_dollar_expand(cp,
1416 		    pw->pw_dir, host, options.user, pw->pw_name);
1417 		free(cp);
1418 	}
1419 
1420 	if (options.identity_agent != NULL) {
1421 		p = tilde_expand_filename(options.identity_agent, getuid());
1422 		cp = default_client_percent_dollar_expand(p,
1423 		    pw->pw_dir, host, options.user, pw->pw_name);
1424 		free(p);
1425 		free(options.identity_agent);
1426 		options.identity_agent = cp;
1427 	}
1428 
1429 	if (options.forward_agent_sock_path != NULL) {
1430 		p = tilde_expand_filename(options.forward_agent_sock_path,
1431 		    getuid());
1432 		cp = default_client_percent_dollar_expand(p,
1433 		    pw->pw_dir, host, options.user, pw->pw_name);
1434 		free(p);
1435 		free(options.forward_agent_sock_path);
1436 		options.forward_agent_sock_path = cp;
1437 	}
1438 
1439 	for (j = 0; j < options.num_user_hostfiles; j++) {
1440 		if (options.user_hostfiles[j] != NULL) {
1441 			cp = tilde_expand_filename(options.user_hostfiles[j],
1442 			    getuid());
1443 			p = default_client_percent_dollar_expand(cp,
1444 			    pw->pw_dir, host, options.user, pw->pw_name);
1445 			if (strcmp(options.user_hostfiles[j], p) != 0)
1446 				debug3("expanded UserKnownHostsFile '%s' -> "
1447 				    "'%s'", options.user_hostfiles[j], p);
1448 			free(options.user_hostfiles[j]);
1449 			free(cp);
1450 			options.user_hostfiles[j] = p;
1451 		}
1452 	}
1453 
1454 	for (i = 0; i < options.num_local_forwards; i++) {
1455 		if (options.local_forwards[i].listen_path != NULL) {
1456 			cp = options.local_forwards[i].listen_path;
1457 			p = options.local_forwards[i].listen_path =
1458 			    default_client_percent_expand(cp,
1459 			    pw->pw_dir, host, options.user, pw->pw_name);
1460 			if (strcmp(cp, p) != 0)
1461 				debug3("expanded LocalForward listen path "
1462 				    "'%s' -> '%s'", cp, p);
1463 			free(cp);
1464 		}
1465 		if (options.local_forwards[i].connect_path != NULL) {
1466 			cp = options.local_forwards[i].connect_path;
1467 			p = options.local_forwards[i].connect_path =
1468 			    default_client_percent_expand(cp,
1469 			    pw->pw_dir, host, options.user, pw->pw_name);
1470 			if (strcmp(cp, p) != 0)
1471 				debug3("expanded LocalForward connect path "
1472 				    "'%s' -> '%s'", cp, p);
1473 			free(cp);
1474 		}
1475 	}
1476 
1477 	for (i = 0; i < options.num_remote_forwards; i++) {
1478 		if (options.remote_forwards[i].listen_path != NULL) {
1479 			cp = options.remote_forwards[i].listen_path;
1480 			p = options.remote_forwards[i].listen_path =
1481 			    default_client_percent_expand(cp,
1482 			    pw->pw_dir, host, options.user, pw->pw_name);
1483 			if (strcmp(cp, p) != 0)
1484 				debug3("expanded RemoteForward listen path "
1485 				    "'%s' -> '%s'", cp, p);
1486 			free(cp);
1487 		}
1488 		if (options.remote_forwards[i].connect_path != NULL) {
1489 			cp = options.remote_forwards[i].connect_path;
1490 			p = options.remote_forwards[i].connect_path =
1491 			    default_client_percent_expand(cp,
1492 			    pw->pw_dir, host, options.user, pw->pw_name);
1493 			if (strcmp(cp, p) != 0)
1494 				debug3("expanded RemoteForward connect path "
1495 				    "'%s' -> '%s'", cp, p);
1496 			free(cp);
1497 		}
1498 	}
1499 
1500 	if (config_test) {
1501 		dump_client_config(&options, host);
1502 		exit(0);
1503 	}
1504 
1505 	/* Expand SecurityKeyProvider if it refers to an environment variable */
1506 	if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1507 	    strlen(options.sk_provider) > 1) {
1508 		if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1509 			debug("Authenticator provider %s did not resolve; "
1510 			    "disabling", options.sk_provider);
1511 			free(options.sk_provider);
1512 			options.sk_provider = NULL;
1513 		} else {
1514 			debug2("resolved SecurityKeyProvider %s => %s",
1515 			    options.sk_provider, cp);
1516 			free(options.sk_provider);
1517 			options.sk_provider = xstrdup(cp);
1518 		}
1519 	}
1520 
1521 	if (muxclient_command != 0 && options.control_path == NULL)
1522 		fatal("No ControlPath specified for \"-O\" command");
1523 	if (options.control_path != NULL) {
1524 		int sock;
1525 		if ((sock = muxclient(options.control_path)) >= 0) {
1526 			ssh_packet_set_connection(ssh, sock, sock);
1527 			ssh_packet_set_mux(ssh);
1528 			goto skip_connect;
1529 		}
1530 	}
1531 
1532 	/*
1533 	 * If hostname canonicalisation was not enabled, then we may not
1534 	 * have yet resolved the hostname. Do so now.
1535 	 */
1536 	if (addrs == NULL && options.proxy_command == NULL) {
1537 		debug2("resolving \"%s\" port %d", host, options.port);
1538 		if ((addrs = resolve_host(host, options.port, 1,
1539 		    cname, sizeof(cname))) == NULL)
1540 			cleanup_exit(255); /* resolve_host logs the error */
1541 	}
1542 
1543 	timeout_ms = options.connection_timeout * 1000;
1544 
1545 	/* Open a connection to the remote host. */
1546 	if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port,
1547 	    options.connection_attempts,
1548 	    &timeout_ms, options.tcp_keep_alive) != 0)
1549  		exit(255);
1550 
1551 	if (addrs != NULL)
1552 		freeaddrinfo(addrs);
1553 
1554 	ssh_packet_set_timeout(ssh, options.server_alive_interval,
1555 	    options.server_alive_count_max);
1556 
1557 	if (timeout_ms > 0)
1558 		debug3("timeout: %d ms remain after connect", timeout_ms);
1559 
1560 	/*
1561 	 * If we successfully made the connection and we have hostbased auth
1562 	 * enabled, load the public keys so we can later use the ssh-keysign
1563 	 * helper to sign challenges.
1564 	 */
1565 	sensitive_data.nkeys = 0;
1566 	sensitive_data.keys = NULL;
1567 	if (options.hostbased_authentication) {
1568 		sensitive_data.nkeys = 10;
1569 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1570 		    sizeof(struct sshkey));
1571 
1572 		/* XXX check errors? */
1573 #define L_PUBKEY(p,o) do { \
1574 	if ((o) >= sensitive_data.nkeys) \
1575 		fatal("%s pubkey out of array bounds", __func__); \
1576 	check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1577 	    p, "pubkey"); \
1578 } while (0)
1579 #define L_CERT(p,o) do { \
1580 	if ((o) >= sensitive_data.nkeys) \
1581 		fatal("%s cert out of array bounds", __func__); \
1582 	check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
1583 } while (0)
1584 
1585 		if (options.hostbased_authentication == 1) {
1586 			L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1587 			L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1588 			L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1589 			L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1590 			L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1591 			L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1592 			L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1593 			L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1594 			L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1595 			L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1596 		}
1597 	}
1598 
1599 	/* load options.identity_files */
1600 	load_public_identity_files(pw);
1601 
1602 	/* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1603 	if (options.identity_agent &&
1604 	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1605 		if (strcmp(options.identity_agent, "none") == 0) {
1606 			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1607 		} else {
1608 			cp = options.identity_agent;
1609 			/* legacy (limited) format */
1610 			if (cp[0] == '$' && cp[1] != '{') {
1611 				if (!valid_env_name(cp + 1)) {
1612 					fatal("Invalid IdentityAgent "
1613 					    "environment variable name %s", cp);
1614 				}
1615 				if ((p = getenv(cp + 1)) == NULL)
1616 					unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1617 				else
1618 					setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1619 			} else {
1620 				/* identity_agent specifies a path directly */
1621 				setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1622 			}
1623 		}
1624 	}
1625 
1626 	if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1627 		cp = options.forward_agent_sock_path;
1628 		if (cp[0] == '$') {
1629 			if (!valid_env_name(cp + 1)) {
1630 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1631 			}
1632 			if ((p = getenv(cp + 1)) != NULL)
1633 				forward_agent_sock_path = p;
1634 			else
1635 				options.forward_agent = 0;
1636 			free(cp);
1637 		} else {
1638 			forward_agent_sock_path = cp;
1639 		}
1640 	}
1641 
1642 	/* Expand ~ in known host file names. */
1643 	tilde_expand_paths(options.system_hostfiles,
1644 	    options.num_system_hostfiles);
1645 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1646 
1647 	ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1648 	ssh_signal(SIGCHLD, main_sigchld_handler);
1649 
1650 	/* Log into the remote system.  Never returns if the login fails. */
1651 	ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1652 	    options.port, pw, timeout_ms);
1653 
1654 	if (ssh_packet_connection_is_on_socket(ssh)) {
1655 		verbose("Authenticated to %s ([%s]:%d).", host,
1656 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1657 	} else {
1658 		verbose("Authenticated to %s (via proxy).", host);
1659 	}
1660 
1661 	/* We no longer need the private host keys.  Clear them now. */
1662 	if (sensitive_data.nkeys != 0) {
1663 		for (i = 0; i < sensitive_data.nkeys; i++) {
1664 			if (sensitive_data.keys[i] != NULL) {
1665 				/* Destroys contents safely */
1666 				debug3("clear hostkey %d", i);
1667 				sshkey_free(sensitive_data.keys[i]);
1668 				sensitive_data.keys[i] = NULL;
1669 			}
1670 		}
1671 		free(sensitive_data.keys);
1672 	}
1673 	for (i = 0; i < options.num_identity_files; i++) {
1674 		free(options.identity_files[i]);
1675 		options.identity_files[i] = NULL;
1676 		if (options.identity_keys[i]) {
1677 			sshkey_free(options.identity_keys[i]);
1678 			options.identity_keys[i] = NULL;
1679 		}
1680 	}
1681 	for (i = 0; i < options.num_certificate_files; i++) {
1682 		free(options.certificate_files[i]);
1683 		options.certificate_files[i] = NULL;
1684 	}
1685 
1686  skip_connect:
1687 	exit_status = ssh_session2(ssh, pw);
1688 	ssh_packet_close(ssh);
1689 
1690 	if (options.control_path != NULL && muxserver_sock != -1)
1691 		unlink(options.control_path);
1692 
1693 	/* Kill ProxyCommand if it is running. */
1694 	ssh_kill_proxy_command();
1695 
1696 	return exit_status;
1697 }
1698 
1699 static void
1700 control_persist_detach(void)
1701 {
1702 	pid_t pid;
1703 
1704 	debug("%s: backgrounding master process", __func__);
1705 
1706 	/*
1707 	 * master (current process) into the background, and make the
1708 	 * foreground process a client of the backgrounded master.
1709 	 */
1710 	switch ((pid = fork())) {
1711 	case -1:
1712 		fatal("%s: fork: %s", __func__, strerror(errno));
1713 	case 0:
1714 		/* Child: master process continues mainloop */
1715 		break;
1716 	default:
1717 		/* Parent: set up mux client to connect to backgrounded master */
1718 		debug2("%s: background process is %ld", __func__, (long)pid);
1719 		stdin_null_flag = ostdin_null_flag;
1720 		options.request_tty = orequest_tty;
1721 		tty_flag = otty_flag;
1722 		close(muxserver_sock);
1723 		muxserver_sock = -1;
1724 		options.control_master = SSHCTL_MASTER_NO;
1725 		muxclient(options.control_path);
1726 		/* muxclient() doesn't return on success. */
1727 		fatal("Failed to connect to new control master");
1728 	}
1729 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1730 		error("%s: stdfd_devnull failed", __func__);
1731 	daemon(1, 1);
1732 	setproctitle("%s [mux]", options.control_path);
1733 }
1734 
1735 /* Do fork() after authentication. Used by "ssh -f" */
1736 static void
1737 fork_postauth(void)
1738 {
1739 	if (need_controlpersist_detach)
1740 		control_persist_detach();
1741 	debug("forking to background");
1742 	fork_after_authentication_flag = 0;
1743 	if (daemon(1, 1) == -1)
1744 		fatal("daemon() failed: %.200s", strerror(errno));
1745 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1746 		error("%s: stdfd_devnull failed", __func__);
1747 }
1748 
1749 static void
1750 forwarding_success(void)
1751 {
1752 	if (forward_confirms_pending == -1)
1753 		return;
1754 	if (--forward_confirms_pending == 0) {
1755 		debug("%s: all expected forwarding replies received", __func__);
1756 		if (fork_after_authentication_flag)
1757 			fork_postauth();
1758 	} else {
1759 		debug2("%s: %d expected forwarding replies remaining",
1760 		    __func__, forward_confirms_pending);
1761 	}
1762 }
1763 
1764 /* Callback for remote forward global requests */
1765 static void
1766 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1767 {
1768 	struct Forward *rfwd = (struct Forward *)ctxt;
1769 	u_int port;
1770 	int r;
1771 
1772 	/* XXX verbose() on failure? */
1773 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1774 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1775 	    rfwd->listen_path ? rfwd->listen_path :
1776 	    rfwd->listen_host ? rfwd->listen_host : "",
1777 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1778 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1779 	    rfwd->connect_host, rfwd->connect_port);
1780 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1781 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1782 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1783 				fatal("%s: %s", __func__, ssh_err(r));
1784 			if (port > 65535) {
1785 				error("Invalid allocated port %u for remote "
1786 				    "forward to %s:%d", port,
1787 				    rfwd->connect_host, rfwd->connect_port);
1788 				/* Ensure failure processing runs below */
1789 				type = SSH2_MSG_REQUEST_FAILURE;
1790 				channel_update_permission(ssh,
1791 				    rfwd->handle, -1);
1792 			} else {
1793 				rfwd->allocated_port = (int)port;
1794 				logit("Allocated port %u for remote "
1795 				    "forward to %s:%d",
1796 				    rfwd->allocated_port, rfwd->connect_host,
1797 				    rfwd->connect_port);
1798 				channel_update_permission(ssh,
1799 				    rfwd->handle, rfwd->allocated_port);
1800 			}
1801 		} else {
1802 			channel_update_permission(ssh, rfwd->handle, -1);
1803 		}
1804 	}
1805 
1806 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1807 		if (options.exit_on_forward_failure) {
1808 			if (rfwd->listen_path != NULL)
1809 				fatal("Error: remote port forwarding failed "
1810 				    "for listen path %s", rfwd->listen_path);
1811 			else
1812 				fatal("Error: remote port forwarding failed "
1813 				    "for listen port %d", rfwd->listen_port);
1814 		} else {
1815 			if (rfwd->listen_path != NULL)
1816 				logit("Warning: remote port forwarding failed "
1817 				    "for listen path %s", rfwd->listen_path);
1818 			else
1819 				logit("Warning: remote port forwarding failed "
1820 				    "for listen port %d", rfwd->listen_port);
1821 		}
1822 	}
1823 	forwarding_success();
1824 }
1825 
1826 static void
1827 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1828 {
1829 	debug("stdio forwarding: done");
1830 	cleanup_exit(0);
1831 }
1832 
1833 static void
1834 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1835 {
1836 	if (!success)
1837 		fatal("stdio forwarding failed");
1838 }
1839 
1840 static void
1841 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1842 {
1843 	if (!success) {
1844 		error("Tunnel forwarding failed");
1845 		if (options.exit_on_forward_failure)
1846 			cleanup_exit(255);
1847 	}
1848 
1849 	debug("%s: tunnel forward established, id=%d", __func__, id);
1850 	forwarding_success();
1851 }
1852 
1853 static void
1854 ssh_init_stdio_forwarding(struct ssh *ssh)
1855 {
1856 	Channel *c;
1857 	int in, out;
1858 
1859 	if (options.stdio_forward_host == NULL)
1860 		return;
1861 
1862 	debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1863 	    options.stdio_forward_port);
1864 
1865 	if ((in = dup(STDIN_FILENO)) == -1 ||
1866 	    (out = dup(STDOUT_FILENO)) == -1)
1867 		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1868 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1869 	    options.stdio_forward_port, in, out)) == NULL)
1870 		fatal("%s: channel_connect_stdio_fwd failed", __func__);
1871 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1872 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1873 }
1874 
1875 static void
1876 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1877 {
1878 	int success = 0;
1879 	int i;
1880 
1881 	if (options.exit_on_forward_failure)
1882 		forward_confirms_pending = 0; /* track pending requests */
1883 	/* Initiate local TCP/IP port forwardings. */
1884 	for (i = 0; i < options.num_local_forwards; i++) {
1885 		debug("Local connections to %.200s:%d forwarded to remote "
1886 		    "address %.200s:%d",
1887 		    (options.local_forwards[i].listen_path != NULL) ?
1888 		    options.local_forwards[i].listen_path :
1889 		    (options.local_forwards[i].listen_host == NULL) ?
1890 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1891 		    options.local_forwards[i].listen_host,
1892 		    options.local_forwards[i].listen_port,
1893 		    (options.local_forwards[i].connect_path != NULL) ?
1894 		    options.local_forwards[i].connect_path :
1895 		    options.local_forwards[i].connect_host,
1896 		    options.local_forwards[i].connect_port);
1897 		success += channel_setup_local_fwd_listener(ssh,
1898 		    &options.local_forwards[i], &options.fwd_opts);
1899 	}
1900 	if (i > 0 && success != i && options.exit_on_forward_failure)
1901 		fatal("Could not request local forwarding.");
1902 	if (i > 0 && success == 0)
1903 		error("Could not request local forwarding.");
1904 
1905 	/* Initiate remote TCP/IP port forwardings. */
1906 	for (i = 0; i < options.num_remote_forwards; i++) {
1907 		debug("Remote connections from %.200s:%d forwarded to "
1908 		    "local address %.200s:%d",
1909 		    (options.remote_forwards[i].listen_path != NULL) ?
1910 		    options.remote_forwards[i].listen_path :
1911 		    (options.remote_forwards[i].listen_host == NULL) ?
1912 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1913 		    options.remote_forwards[i].listen_port,
1914 		    (options.remote_forwards[i].connect_path != NULL) ?
1915 		    options.remote_forwards[i].connect_path :
1916 		    options.remote_forwards[i].connect_host,
1917 		    options.remote_forwards[i].connect_port);
1918 		if ((options.remote_forwards[i].handle =
1919 		    channel_request_remote_forwarding(ssh,
1920 		    &options.remote_forwards[i])) >= 0) {
1921 			client_register_global_confirm(
1922 			    ssh_confirm_remote_forward,
1923 			    &options.remote_forwards[i]);
1924 			forward_confirms_pending++;
1925 		} else if (options.exit_on_forward_failure)
1926 			fatal("Could not request remote forwarding.");
1927 		else
1928 			logit("Warning: Could not request remote forwarding.");
1929 	}
1930 
1931 	/* Initiate tunnel forwarding. */
1932 	if (options.tun_open != SSH_TUNMODE_NO) {
1933 		if ((*ifname = client_request_tun_fwd(ssh,
1934 		    options.tun_open, options.tun_local,
1935 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
1936 			forward_confirms_pending++;
1937 		else if (options.exit_on_forward_failure)
1938 			fatal("Could not request tunnel forwarding.");
1939 		else
1940 			error("Could not request tunnel forwarding.");
1941 	}
1942 	if (forward_confirms_pending > 0) {
1943 		debug("%s: expecting replies for %d forwards", __func__,
1944 		    forward_confirms_pending);
1945 	}
1946 }
1947 
1948 static void
1949 check_agent_present(void)
1950 {
1951 	int r;
1952 
1953 	if (options.forward_agent) {
1954 		/* Clear agent forwarding if we don't have an agent. */
1955 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1956 			options.forward_agent = 0;
1957 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
1958 				debug("ssh_get_authentication_socket: %s",
1959 				    ssh_err(r));
1960 		}
1961 	}
1962 }
1963 
1964 static void
1965 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1966 {
1967 	extern char **environ;
1968 	const char *display;
1969 	int r, interactive = tty_flag;
1970 	char *proto = NULL, *data = NULL;
1971 
1972 	if (!success)
1973 		return; /* No need for error message, channels code sens one */
1974 
1975 	display = getenv("DISPLAY");
1976 	if (display == NULL && options.forward_x11)
1977 		debug("X11 forwarding requested but DISPLAY not set");
1978 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
1979 	    options.xauth_location, options.forward_x11_trusted,
1980 	    options.forward_x11_timeout, &proto, &data) == 0) {
1981 		/* Request forwarding with authentication spoofing. */
1982 		debug("Requesting X11 forwarding with authentication "
1983 		    "spoofing.");
1984 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1985 		    data, 1);
1986 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1987 		/* XXX exit_on_forward_failure */
1988 		interactive = 1;
1989 	}
1990 
1991 	check_agent_present();
1992 	if (options.forward_agent) {
1993 		debug("Requesting authentication agent forwarding.");
1994 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1995 		if ((r = sshpkt_send(ssh)) != 0)
1996 			fatal("%s: %s", __func__, ssh_err(r));
1997 	}
1998 
1999 	/* Tell the packet module whether this is an interactive session. */
2000 	ssh_packet_set_interactive(ssh, interactive,
2001 	    options.ip_qos_interactive, options.ip_qos_bulk);
2002 
2003 	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
2004 	    NULL, fileno(stdin), command, environ);
2005 }
2006 
2007 /* open new channel for a session */
2008 static int
2009 ssh_session2_open(struct ssh *ssh)
2010 {
2011 	Channel *c;
2012 	int window, packetmax, in, out, err;
2013 
2014 	if (stdin_null_flag) {
2015 		in = open(_PATH_DEVNULL, O_RDONLY);
2016 	} else {
2017 		in = dup(STDIN_FILENO);
2018 	}
2019 	out = dup(STDOUT_FILENO);
2020 	err = dup(STDERR_FILENO);
2021 
2022 	if (in == -1 || out == -1 || err == -1)
2023 		fatal("dup() in/out/err failed");
2024 
2025 	/* enable nonblocking unless tty */
2026 	if (!isatty(in))
2027 		set_nonblock(in);
2028 	if (!isatty(out))
2029 		set_nonblock(out);
2030 	if (!isatty(err))
2031 		set_nonblock(err);
2032 
2033 	window = CHAN_SES_WINDOW_DEFAULT;
2034 	packetmax = CHAN_SES_PACKET_DEFAULT;
2035 	if (tty_flag) {
2036 		window >>= 1;
2037 		packetmax >>= 1;
2038 	}
2039 	c = channel_new(ssh,
2040 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2041 	    window, packetmax, CHAN_EXTENDED_WRITE,
2042 	    "client-session", /*nonblock*/0);
2043 
2044 	debug3("%s: channel_new: %d", __func__, c->self);
2045 
2046 	channel_send_open(ssh, c->self);
2047 	if (!no_shell_flag)
2048 		channel_register_open_confirm(ssh, c->self,
2049 		    ssh_session2_setup, NULL);
2050 
2051 	return c->self;
2052 }
2053 
2054 static int
2055 ssh_session2(struct ssh *ssh, struct passwd *pw)
2056 {
2057 	int r, id = -1;
2058 	char *cp, *tun_fwd_ifname = NULL;
2059 
2060 	/* XXX should be pre-session */
2061 	if (!options.control_persist)
2062 		ssh_init_stdio_forwarding(ssh);
2063 
2064 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2065 
2066 	if (options.local_command != NULL) {
2067 		debug3("expanding LocalCommand: %s", options.local_command);
2068 		cp = options.local_command;
2069 		options.local_command = percent_expand(cp,
2070 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS,
2071 		    "d", pw->pw_dir,
2072 		    "h", host,
2073 		    "r", options.user,
2074 		    "u", pw->pw_name,
2075 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2076 		    (char *)NULL);
2077 		debug3("expanded LocalCommand: %s", options.local_command);
2078 		free(cp);
2079 	}
2080 
2081 	/* Start listening for multiplex clients */
2082 	if (!ssh_packet_get_mux(ssh))
2083 		muxserver_listen(ssh);
2084 
2085 	/*
2086 	 * If we are in control persist mode and have a working mux listen
2087 	 * socket, then prepare to background ourselves and have a foreground
2088 	 * client attach as a control client.
2089 	 * NB. we must save copies of the flags that we override for
2090 	 * the backgrounding, since we defer attachment of the client until
2091 	 * after the connection is fully established (in particular,
2092 	 * async rfwd replies have been received for ExitOnForwardFailure).
2093 	 */
2094 	if (options.control_persist && muxserver_sock != -1) {
2095 		ostdin_null_flag = stdin_null_flag;
2096 		ono_shell_flag = no_shell_flag;
2097 		orequest_tty = options.request_tty;
2098 		otty_flag = tty_flag;
2099 		stdin_null_flag = 1;
2100 		no_shell_flag = 1;
2101 		tty_flag = 0;
2102 		if (!fork_after_authentication_flag)
2103 			need_controlpersist_detach = 1;
2104 		fork_after_authentication_flag = 1;
2105 	}
2106 	/*
2107 	 * ControlPersist mux listen socket setup failed, attempt the
2108 	 * stdio forward setup that we skipped earlier.
2109 	 */
2110 	if (options.control_persist && muxserver_sock == -1)
2111 		ssh_init_stdio_forwarding(ssh);
2112 
2113 	if (!no_shell_flag)
2114 		id = ssh_session2_open(ssh);
2115 	else {
2116 		ssh_packet_set_interactive(ssh,
2117 		    options.control_master == SSHCTL_MASTER_NO,
2118 		    options.ip_qos_interactive, options.ip_qos_bulk);
2119 	}
2120 
2121 	/* If we don't expect to open a new session, then disallow it */
2122 	if (options.control_master == SSHCTL_MASTER_NO &&
2123 	    (datafellows & SSH_NEW_OPENSSH)) {
2124 		debug("Requesting no-more-sessions@openssh.com");
2125 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2126 		    (r = sshpkt_put_cstring(ssh,
2127 		    "no-more-sessions@openssh.com")) != 0 ||
2128 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2129 		    (r = sshpkt_send(ssh)) != 0)
2130 			fatal("%s: %s", __func__, ssh_err(r));
2131 	}
2132 
2133 	/* Execute a local command */
2134 	if (options.local_command != NULL &&
2135 	    options.permit_local_command)
2136 		ssh_local_cmd(options.local_command);
2137 
2138 	/*
2139 	 * stdout is now owned by the session channel; clobber it here
2140 	 * so future channel closes are propagated to the local fd.
2141 	 * NB. this can only happen after LocalCommand has completed,
2142 	 * as it may want to write to stdout.
2143 	 */
2144 	if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2145 		error("%s: stdfd_devnull failed", __func__);
2146 
2147 	/*
2148 	 * If requested and we are not interested in replies to remote
2149 	 * forwarding requests, then let ssh continue in the background.
2150 	 */
2151 	if (fork_after_authentication_flag) {
2152 		if (options.exit_on_forward_failure &&
2153 		    options.num_remote_forwards > 0) {
2154 			debug("deferring postauth fork until remote forward "
2155 			    "confirmation received");
2156 		} else
2157 			fork_postauth();
2158 	}
2159 
2160 	return client_loop(ssh, tty_flag, tty_flag ?
2161 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2162 }
2163 
2164 /* Loads all IdentityFile and CertificateFile keys */
2165 static void
2166 load_public_identity_files(struct passwd *pw)
2167 {
2168 	char *filename, *cp;
2169 	struct sshkey *public;
2170 	int i;
2171 	u_int n_ids, n_certs;
2172 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2173 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2174 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2175 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2176 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2177 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2178 #ifdef ENABLE_PKCS11
2179 	struct sshkey **keys = NULL;
2180 	char **comments = NULL;
2181 	int nkeys;
2182 #endif /* PKCS11 */
2183 
2184 	n_ids = n_certs = 0;
2185 	memset(identity_files, 0, sizeof(identity_files));
2186 	memset(identity_keys, 0, sizeof(identity_keys));
2187 	memset(identity_file_userprovided, 0,
2188 	    sizeof(identity_file_userprovided));
2189 	memset(certificate_files, 0, sizeof(certificate_files));
2190 	memset(certificates, 0, sizeof(certificates));
2191 	memset(certificate_file_userprovided, 0,
2192 	    sizeof(certificate_file_userprovided));
2193 
2194 #ifdef ENABLE_PKCS11
2195 	if (options.pkcs11_provider != NULL &&
2196 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2197 	    (pkcs11_init(!options.batch_mode) == 0) &&
2198 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2199 	    &keys, &comments)) > 0) {
2200 		for (i = 0; i < nkeys; i++) {
2201 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2202 				sshkey_free(keys[i]);
2203 				free(comments[i]);
2204 				continue;
2205 			}
2206 			identity_keys[n_ids] = keys[i];
2207 			identity_files[n_ids] = comments[i]; /* transferred */
2208 			n_ids++;
2209 		}
2210 		free(keys);
2211 		free(comments);
2212 	}
2213 #endif /* ENABLE_PKCS11 */
2214 	for (i = 0; i < options.num_identity_files; i++) {
2215 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2216 		    strcasecmp(options.identity_files[i], "none") == 0) {
2217 			free(options.identity_files[i]);
2218 			options.identity_files[i] = NULL;
2219 			continue;
2220 		}
2221 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2222 		filename = default_client_percent_dollar_expand(cp,
2223 		    pw->pw_dir, host, options.user, pw->pw_name);
2224 		free(cp);
2225 		check_load(sshkey_load_public(filename, &public, NULL),
2226 		    filename, "pubkey");
2227 		debug("identity file %s type %d", filename,
2228 		    public ? public->type : -1);
2229 		free(options.identity_files[i]);
2230 		identity_files[n_ids] = filename;
2231 		identity_keys[n_ids] = public;
2232 		identity_file_userprovided[n_ids] =
2233 		    options.identity_file_userprovided[i];
2234 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2235 			continue;
2236 
2237 		/*
2238 		 * If no certificates have been explicitly listed then try
2239 		 * to add the default certificate variant too.
2240 		 */
2241 		if (options.num_certificate_files != 0)
2242 			continue;
2243 		xasprintf(&cp, "%s-cert", filename);
2244 		check_load(sshkey_load_public(cp, &public, NULL),
2245 		    filename, "pubkey");
2246 		debug("identity file %s type %d", cp,
2247 		    public ? public->type : -1);
2248 		if (public == NULL) {
2249 			free(cp);
2250 			continue;
2251 		}
2252 		if (!sshkey_is_cert(public)) {
2253 			debug("%s: key %s type %s is not a certificate",
2254 			    __func__, cp, sshkey_type(public));
2255 			sshkey_free(public);
2256 			free(cp);
2257 			continue;
2258 		}
2259 		/* NB. leave filename pointing to private key */
2260 		identity_files[n_ids] = xstrdup(filename);
2261 		identity_keys[n_ids] = public;
2262 		identity_file_userprovided[n_ids] =
2263 		    options.identity_file_userprovided[i];
2264 		n_ids++;
2265 	}
2266 
2267 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2268 		fatal("%s: too many certificates", __func__);
2269 	for (i = 0; i < options.num_certificate_files; i++) {
2270 		cp = tilde_expand_filename(options.certificate_files[i],
2271 		    getuid());
2272 		filename = default_client_percent_dollar_expand(cp,
2273 		    pw->pw_dir, host, options.user, pw->pw_name);
2274 		free(cp);
2275 
2276 		check_load(sshkey_load_public(filename, &public, NULL),
2277 		    filename, "certificate");
2278 		debug("certificate file %s type %d", filename,
2279 		    public ? public->type : -1);
2280 		free(options.certificate_files[i]);
2281 		options.certificate_files[i] = NULL;
2282 		if (public == NULL) {
2283 			free(filename);
2284 			continue;
2285 		}
2286 		if (!sshkey_is_cert(public)) {
2287 			debug("%s: key %s type %s is not a certificate",
2288 			    __func__, filename, sshkey_type(public));
2289 			sshkey_free(public);
2290 			free(filename);
2291 			continue;
2292 		}
2293 		certificate_files[n_certs] = filename;
2294 		certificates[n_certs] = public;
2295 		certificate_file_userprovided[n_certs] =
2296 		    options.certificate_file_userprovided[i];
2297 		++n_certs;
2298 	}
2299 
2300 	options.num_identity_files = n_ids;
2301 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2302 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2303 	memcpy(options.identity_file_userprovided,
2304 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2305 
2306 	options.num_certificate_files = n_certs;
2307 	memcpy(options.certificate_files,
2308 	    certificate_files, sizeof(certificate_files));
2309 	memcpy(options.certificates, certificates, sizeof(certificates));
2310 	memcpy(options.certificate_file_userprovided,
2311 	    certificate_file_userprovided,
2312 	    sizeof(certificate_file_userprovided));
2313 }
2314 
2315 static void
2316 main_sigchld_handler(int sig)
2317 {
2318 	int save_errno = errno;
2319 	pid_t pid;
2320 	int status;
2321 
2322 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2323 	    (pid == -1 && errno == EINTR))
2324 		;
2325 	errno = save_errno;
2326 }
2327