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