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