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