xref: /openbsd-src/usr.bin/ssh/ssh.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /* $OpenBSD: ssh.c,v 1.546 2020/12/20 23:40:19 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 
636 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
637 	sanitise_stdfd();
638 
639 	/*
640 	 * Discard other fds that are hanging around. These can cause problem
641 	 * with backgrounded ssh processes started by ControlPersist.
642 	 */
643 	closefrom(STDERR_FILENO + 1);
644 
645 	if (getuid() != geteuid())
646 		fatal("ssh setuid not supported.");
647 	if (getgid() != getegid())
648 		fatal("ssh setgid not supported.");
649 
650 	/* Get user data. */
651 	pw = getpwuid(getuid());
652 	if (!pw) {
653 		logit("No user exists for uid %lu", (u_long)getuid());
654 		exit(255);
655 	}
656 	/* Take a copy of the returned structure. */
657 	pw = pwcopy(pw);
658 
659 	/*
660 	 * Set our umask to something reasonable, as some files are created
661 	 * with the default umask.  This will make them world-readable but
662 	 * writable only by the owner, which is ok for all files for which we
663 	 * don't set the modes explicitly.
664 	 */
665 	umask(022);
666 
667 	setlocale(LC_CTYPE, "");
668 
669 	/*
670 	 * Initialize option structure to indicate that no values have been
671 	 * set.
672 	 */
673 	initialize_options(&options);
674 
675 	/*
676 	 * Prepare main ssh transport/connection structures
677 	 */
678 	if ((ssh = ssh_alloc_session_state()) == NULL)
679 		fatal("Couldn't allocate session state");
680 	channel_init_channels(ssh);
681 
682 	/* Parse command-line arguments. */
683 	host = NULL;
684 	use_syslog = 0;
685 	logfile = NULL;
686 	argv0 = av[0];
687 
688  again:
689 	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
690 	    "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
691 		switch (opt) {
692 		case '1':
693 			fatal("SSH protocol v.1 is no longer supported");
694 			break;
695 		case '2':
696 			/* Ignored */
697 			break;
698 		case '4':
699 			options.address_family = AF_INET;
700 			break;
701 		case '6':
702 			options.address_family = AF_INET6;
703 			break;
704 		case 'n':
705 			stdin_null_flag = 1;
706 			break;
707 		case 'f':
708 			fork_after_authentication_flag = 1;
709 			stdin_null_flag = 1;
710 			break;
711 		case 'x':
712 			options.forward_x11 = 0;
713 			break;
714 		case 'X':
715 			options.forward_x11 = 1;
716 			break;
717 		case 'y':
718 			use_syslog = 1;
719 			break;
720 		case 'E':
721 			logfile = optarg;
722 			break;
723 		case 'G':
724 			config_test = 1;
725 			break;
726 		case 'Y':
727 			options.forward_x11 = 1;
728 			options.forward_x11_trusted = 1;
729 			break;
730 		case 'g':
731 			options.fwd_opts.gateway_ports = 1;
732 			break;
733 		case 'O':
734 			if (options.stdio_forward_host != NULL)
735 				fatal("Cannot specify multiplexing "
736 				    "command with -W");
737 			else if (muxclient_command != 0)
738 				fatal("Multiplexing command already specified");
739 			if (strcmp(optarg, "check") == 0)
740 				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
741 			else if (strcmp(optarg, "forward") == 0)
742 				muxclient_command = SSHMUX_COMMAND_FORWARD;
743 			else if (strcmp(optarg, "exit") == 0)
744 				muxclient_command = SSHMUX_COMMAND_TERMINATE;
745 			else if (strcmp(optarg, "stop") == 0)
746 				muxclient_command = SSHMUX_COMMAND_STOP;
747 			else if (strcmp(optarg, "cancel") == 0)
748 				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
749 			else if (strcmp(optarg, "proxy") == 0)
750 				muxclient_command = SSHMUX_COMMAND_PROXY;
751 			else
752 				fatal("Invalid multiplex command.");
753 			break;
754 		case 'P':	/* deprecated */
755 			break;
756 		case 'Q':
757 			cp = NULL;
758 			if (strcmp(optarg, "cipher") == 0 ||
759 			    strcasecmp(optarg, "Ciphers") == 0)
760 				cp = cipher_alg_list('\n', 0);
761 			else if (strcmp(optarg, "cipher-auth") == 0)
762 				cp = cipher_alg_list('\n', 1);
763 			else if (strcmp(optarg, "mac") == 0 ||
764 			    strcasecmp(optarg, "MACs") == 0)
765 				cp = mac_alg_list('\n');
766 			else if (strcmp(optarg, "kex") == 0 ||
767 			    strcasecmp(optarg, "KexAlgorithms") == 0)
768 				cp = kex_alg_list('\n');
769 			else if (strcmp(optarg, "key") == 0)
770 				cp = sshkey_alg_list(0, 0, 0, '\n');
771 			else if (strcmp(optarg, "key-cert") == 0)
772 				cp = sshkey_alg_list(1, 0, 0, '\n');
773 			else if (strcmp(optarg, "key-plain") == 0)
774 				cp = sshkey_alg_list(0, 1, 0, '\n');
775 			else if (strcmp(optarg, "key-sig") == 0 ||
776 			    strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 ||
777 			    strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
778 			    strcasecmp(optarg, "HostbasedKeyTypes") == 0 ||
779 			    strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0)
780 				cp = sshkey_alg_list(0, 0, 1, '\n');
781 			else if (strcmp(optarg, "sig") == 0)
782 				cp = sshkey_alg_list(0, 1, 1, '\n');
783 			else if (strcmp(optarg, "protocol-version") == 0)
784 				cp = xstrdup("2");
785 			else if (strcmp(optarg, "compression") == 0) {
786 				cp = xstrdup(compression_alg_list(0));
787 				len = strlen(cp);
788 				for (n = 0; n < len; n++)
789 					if (cp[n] == ',')
790 						cp[n] = '\n';
791 			} else if (strcmp(optarg, "help") == 0) {
792 				cp = xstrdup(
793 				    "cipher\ncipher-auth\ncompression\nkex\n"
794 				    "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
795 				    "protocol-version\nsig");
796 			}
797 			if (cp == NULL)
798 				fatal("Unsupported query \"%s\"", optarg);
799 			printf("%s\n", cp);
800 			free(cp);
801 			exit(0);
802 			break;
803 		case 'a':
804 			options.forward_agent = 0;
805 			break;
806 		case 'A':
807 			options.forward_agent = 1;
808 			break;
809 		case 'k':
810 			options.gss_deleg_creds = 0;
811 			break;
812 		case 'K':
813 			options.gss_authentication = 1;
814 			options.gss_deleg_creds = 1;
815 			break;
816 		case 'i':
817 			p = tilde_expand_filename(optarg, getuid());
818 			if (stat(p, &st) == -1)
819 				fprintf(stderr, "Warning: Identity file %s "
820 				    "not accessible: %s.\n", p,
821 				    strerror(errno));
822 			else
823 				add_identity_file(&options, NULL, p, 1);
824 			free(p);
825 			break;
826 		case 'I':
827 #ifdef ENABLE_PKCS11
828 			free(options.pkcs11_provider);
829 			options.pkcs11_provider = xstrdup(optarg);
830 #else
831 			fprintf(stderr, "no support for PKCS#11.\n");
832 #endif
833 			break;
834 		case 'J':
835 			if (options.jump_host != NULL) {
836 				fatal("Only a single -J option is permitted "
837 				    "(use commas to separate multiple "
838 				    "jump hops)");
839 			}
840 			if (options.proxy_command != NULL)
841 				fatal("Cannot specify -J with ProxyCommand");
842 			if (parse_jump(optarg, &options, 1) == -1)
843 				fatal("Invalid -J argument");
844 			options.proxy_command = xstrdup("none");
845 			break;
846 		case 't':
847 			if (options.request_tty == REQUEST_TTY_YES)
848 				options.request_tty = REQUEST_TTY_FORCE;
849 			else
850 				options.request_tty = REQUEST_TTY_YES;
851 			break;
852 		case 'v':
853 			if (debug_flag == 0) {
854 				debug_flag = 1;
855 				options.log_level = SYSLOG_LEVEL_DEBUG1;
856 			} else {
857 				if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
858 					debug_flag++;
859 					options.log_level++;
860 				}
861 			}
862 			break;
863 		case 'V':
864 			fprintf(stderr, "%s, %s\n",
865 			    SSH_VERSION, SSH_OPENSSL_VERSION);
866 			if (opt == 'V')
867 				exit(0);
868 			break;
869 		case 'w':
870 			if (options.tun_open == -1)
871 				options.tun_open = SSH_TUNMODE_DEFAULT;
872 			options.tun_local = a2tun(optarg, &options.tun_remote);
873 			if (options.tun_local == SSH_TUNID_ERR) {
874 				fprintf(stderr,
875 				    "Bad tun device '%s'\n", optarg);
876 				exit(255);
877 			}
878 			break;
879 		case 'W':
880 			if (options.stdio_forward_host != NULL)
881 				fatal("stdio forward already specified");
882 			if (muxclient_command != 0)
883 				fatal("Cannot specify stdio forward with -O");
884 			if (parse_forward(&fwd, optarg, 1, 0)) {
885 				options.stdio_forward_host = fwd.listen_host;
886 				options.stdio_forward_port = fwd.listen_port;
887 				free(fwd.connect_host);
888 			} else {
889 				fprintf(stderr,
890 				    "Bad stdio forwarding specification '%s'\n",
891 				    optarg);
892 				exit(255);
893 			}
894 			options.request_tty = REQUEST_TTY_NO;
895 			no_shell_flag = 1;
896 			break;
897 		case 'q':
898 			options.log_level = SYSLOG_LEVEL_QUIET;
899 			break;
900 		case 'e':
901 			if (optarg[0] == '^' && optarg[2] == 0 &&
902 			    (u_char) optarg[1] >= 64 &&
903 			    (u_char) optarg[1] < 128)
904 				options.escape_char = (u_char) optarg[1] & 31;
905 			else if (strlen(optarg) == 1)
906 				options.escape_char = (u_char) optarg[0];
907 			else if (strcmp(optarg, "none") == 0)
908 				options.escape_char = SSH_ESCAPECHAR_NONE;
909 			else {
910 				fprintf(stderr, "Bad escape character '%s'.\n",
911 				    optarg);
912 				exit(255);
913 			}
914 			break;
915 		case 'c':
916 			if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
917 			    optarg + 1 : optarg)) {
918 				fprintf(stderr, "Unknown cipher type '%s'\n",
919 				    optarg);
920 				exit(255);
921 			}
922 			free(options.ciphers);
923 			options.ciphers = xstrdup(optarg);
924 			break;
925 		case 'm':
926 			if (mac_valid(optarg)) {
927 				free(options.macs);
928 				options.macs = xstrdup(optarg);
929 			} else {
930 				fprintf(stderr, "Unknown mac type '%s'\n",
931 				    optarg);
932 				exit(255);
933 			}
934 			break;
935 		case 'M':
936 			if (options.control_master == SSHCTL_MASTER_YES)
937 				options.control_master = SSHCTL_MASTER_ASK;
938 			else
939 				options.control_master = SSHCTL_MASTER_YES;
940 			break;
941 		case 'p':
942 			if (options.port == -1) {
943 				options.port = a2port(optarg);
944 				if (options.port <= 0) {
945 					fprintf(stderr, "Bad port '%s'\n",
946 					    optarg);
947 					exit(255);
948 				}
949 			}
950 			break;
951 		case 'l':
952 			if (options.user == NULL)
953 				options.user = optarg;
954 			break;
955 
956 		case 'L':
957 			if (parse_forward(&fwd, optarg, 0, 0))
958 				add_local_forward(&options, &fwd);
959 			else {
960 				fprintf(stderr,
961 				    "Bad local forwarding specification '%s'\n",
962 				    optarg);
963 				exit(255);
964 			}
965 			break;
966 
967 		case 'R':
968 			if (parse_forward(&fwd, optarg, 0, 1) ||
969 			    parse_forward(&fwd, optarg, 1, 1)) {
970 				add_remote_forward(&options, &fwd);
971 			} else {
972 				fprintf(stderr,
973 				    "Bad remote forwarding specification "
974 				    "'%s'\n", optarg);
975 				exit(255);
976 			}
977 			break;
978 
979 		case 'D':
980 			if (parse_forward(&fwd, optarg, 1, 0)) {
981 				add_local_forward(&options, &fwd);
982 			} else {
983 				fprintf(stderr,
984 				    "Bad dynamic forwarding specification "
985 				    "'%s'\n", optarg);
986 				exit(255);
987 			}
988 			break;
989 
990 		case 'C':
991 #ifdef WITH_ZLIB
992 			options.compression = 1;
993 #else
994 			error("Compression not supported, disabling.");
995 #endif
996 			break;
997 		case 'N':
998 			no_shell_flag = 1;
999 			options.request_tty = REQUEST_TTY_NO;
1000 			break;
1001 		case 'T':
1002 			options.request_tty = REQUEST_TTY_NO;
1003 			break;
1004 		case 'o':
1005 			line = xstrdup(optarg);
1006 			if (process_config_line(&options, pw,
1007 			    host ? host : "", host ? host : "", line,
1008 			    "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1009 				exit(255);
1010 			free(line);
1011 			break;
1012 		case 's':
1013 			subsystem_flag = 1;
1014 			break;
1015 		case 'S':
1016 			free(options.control_path);
1017 			options.control_path = xstrdup(optarg);
1018 			break;
1019 		case 'b':
1020 			options.bind_address = optarg;
1021 			break;
1022 		case 'B':
1023 			options.bind_interface = optarg;
1024 			break;
1025 		case 'F':
1026 			config = optarg;
1027 			break;
1028 		default:
1029 			usage();
1030 		}
1031 	}
1032 
1033 	if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1034 		opt_terminated = 1;
1035 
1036 	ac -= optind;
1037 	av += optind;
1038 
1039 	if (ac > 0 && !host) {
1040 		int tport;
1041 		char *tuser;
1042 		switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1043 		case -1:
1044 			usage();
1045 			break;
1046 		case 0:
1047 			if (options.user == NULL) {
1048 				options.user = tuser;
1049 				tuser = NULL;
1050 			}
1051 			free(tuser);
1052 			if (options.port == -1 && tport != -1)
1053 				options.port = tport;
1054 			break;
1055 		default:
1056 			p = xstrdup(*av);
1057 			cp = strrchr(p, '@');
1058 			if (cp != NULL) {
1059 				if (cp == p)
1060 					usage();
1061 				if (options.user == NULL) {
1062 					options.user = p;
1063 					p = NULL;
1064 				}
1065 				*cp++ = '\0';
1066 				host = xstrdup(cp);
1067 				free(p);
1068 			} else
1069 				host = p;
1070 			break;
1071 		}
1072 		if (ac > 1 && !opt_terminated) {
1073 			optind = optreset = 1;
1074 			goto again;
1075 		}
1076 		ac--, av++;
1077 	}
1078 
1079 	/* Check that we got a host name. */
1080 	if (!host)
1081 		usage();
1082 
1083 	host_arg = xstrdup(host);
1084 
1085 #ifdef WITH_OPENSSL
1086 	OpenSSL_add_all_algorithms();
1087 	ERR_load_crypto_strings();
1088 #endif
1089 
1090 	/* Initialize the command to execute on remote host. */
1091 	if ((command = sshbuf_new()) == NULL)
1092 		fatal("sshbuf_new failed");
1093 
1094 	/*
1095 	 * Save the command to execute on the remote host in a buffer. There
1096 	 * is no limit on the length of the command, except by the maximum
1097 	 * packet size.  Also sets the tty flag if there is no command.
1098 	 */
1099 	if (!ac) {
1100 		/* No command specified - execute shell on a tty. */
1101 		if (subsystem_flag) {
1102 			fprintf(stderr,
1103 			    "You must specify a subsystem to invoke.\n");
1104 			usage();
1105 		}
1106 	} else {
1107 		/* A command has been specified.  Store it into the buffer. */
1108 		for (i = 0; i < ac; i++) {
1109 			if ((r = sshbuf_putf(command, "%s%s",
1110 			    i ? " " : "", av[i])) != 0)
1111 				fatal_fr(r, "buffer error");
1112 		}
1113 	}
1114 
1115 	/*
1116 	 * Initialize "log" output.  Since we are the client all output
1117 	 * goes to stderr unless otherwise specified by -y or -E.
1118 	 */
1119 	if (use_syslog && logfile != NULL)
1120 		fatal("Can't specify both -y and -E");
1121 	if (logfile != NULL)
1122 		log_redirect_stderr_to(logfile);
1123 	log_init(argv0,
1124 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1125 	    SYSLOG_LEVEL_INFO : options.log_level,
1126 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1127 	    SYSLOG_FACILITY_USER : options.log_facility,
1128 	    !use_syslog);
1129 
1130 	if (debug_flag)
1131 		logit("%s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1132 
1133 	/* Parse the configuration files */
1134 	process_config_files(host_arg, pw, 0, &want_final_pass);
1135 	if (want_final_pass)
1136 		debug("configuration requests final Match pass");
1137 
1138 	/* Hostname canonicalisation needs a few options filled. */
1139 	fill_default_options_for_canonicalization(&options);
1140 
1141 	/* If the user has replaced the hostname then take it into use now */
1142 	if (options.hostname != NULL) {
1143 		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
1144 		cp = percent_expand(options.hostname,
1145 		    "h", host, (char *)NULL);
1146 		free(host);
1147 		host = cp;
1148 		free(options.hostname);
1149 		options.hostname = xstrdup(host);
1150 	}
1151 
1152 	/* Don't lowercase addresses, they will be explicitly canonicalised */
1153 	if ((was_addr = is_addr(host)) == 0)
1154 		lowercase(host);
1155 
1156 	/*
1157 	 * Try to canonicalize if requested by configuration or the
1158 	 * hostname is an address.
1159 	 */
1160 	if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1161 		addrs = resolve_canonicalize(&host, options.port);
1162 
1163 	/*
1164 	 * If CanonicalizePermittedCNAMEs have been specified but
1165 	 * other canonicalization did not happen (by not being requested
1166 	 * or by failing with fallback) then the hostname may still be changed
1167 	 * as a result of CNAME following.
1168 	 *
1169 	 * Try to resolve the bare hostname name using the system resolver's
1170 	 * usual search rules and then apply the CNAME follow rules.
1171 	 *
1172 	 * Skip the lookup if a ProxyCommand is being used unless the user
1173 	 * has specifically requested canonicalisation for this case via
1174 	 * CanonicalizeHostname=always
1175 	 */
1176 	direct = option_clear_or_none(options.proxy_command) &&
1177 	    options.jump_host == NULL;
1178 	if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1179 	    options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1180 		if ((addrs = resolve_host(host, options.port,
1181 		    direct, cname, sizeof(cname))) == NULL) {
1182 			/* Don't fatal proxied host names not in the DNS */
1183 			if (direct)
1184 				cleanup_exit(255); /* logged in resolve_host */
1185 		} else
1186 			check_follow_cname(direct, &host, cname);
1187 	}
1188 
1189 	/*
1190 	 * If canonicalisation is enabled then re-parse the configuration
1191 	 * files as new stanzas may match.
1192 	 */
1193 	if (options.canonicalize_hostname != 0 && !want_final_pass) {
1194 		debug("hostname canonicalisation enabled, "
1195 		    "will re-parse configuration");
1196 		want_final_pass = 1;
1197 	}
1198 
1199 	if (want_final_pass) {
1200 		debug("re-parsing configuration");
1201 		free(options.hostname);
1202 		options.hostname = xstrdup(host);
1203 		process_config_files(host_arg, pw, 1, NULL);
1204 		/*
1205 		 * Address resolution happens early with canonicalisation
1206 		 * enabled and the port number may have changed since, so
1207 		 * reset it in address list
1208 		 */
1209 		if (addrs != NULL && options.port > 0)
1210 			set_addrinfo_port(addrs, options.port);
1211 	}
1212 
1213 	/* Fill configuration defaults. */
1214 	if (fill_default_options(&options) != 0)
1215 		cleanup_exit(255);
1216 
1217 	if (options.user == NULL)
1218 		options.user = xstrdup(pw->pw_name);
1219 
1220 	/*
1221 	 * If ProxyJump option specified, then construct a ProxyCommand now.
1222 	 */
1223 	if (options.jump_host != NULL) {
1224 		char port_s[8];
1225 		const char *jumpuser = options.jump_user, *sshbin = argv0;
1226 		int port = options.port, jumpport = options.jump_port;
1227 
1228 		if (port <= 0)
1229 			port = default_ssh_port();
1230 		if (jumpport <= 0)
1231 			jumpport = default_ssh_port();
1232 		if (jumpuser == NULL)
1233 			jumpuser = options.user;
1234 		if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1235 		    strcmp(options.user, jumpuser) == 0)
1236 			fatal("jumphost loop via %s", options.jump_host);
1237 
1238 		/*
1239 		 * Try to use SSH indicated by argv[0], but fall back to
1240 		 * "ssh" if it appears unavailable.
1241 		 */
1242 		if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1243 			sshbin = "ssh";
1244 
1245 		/* Consistency check */
1246 		if (options.proxy_command != NULL)
1247 			fatal("inconsistent options: ProxyCommand+ProxyJump");
1248 		/* Never use FD passing for ProxyJump */
1249 		options.proxy_use_fdpass = 0;
1250 		snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1251 		xasprintf(&options.proxy_command,
1252 		    "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1253 		    sshbin,
1254 		    /* Optional "-l user" argument if jump_user set */
1255 		    options.jump_user == NULL ? "" : " -l ",
1256 		    options.jump_user == NULL ? "" : options.jump_user,
1257 		    /* Optional "-p port" argument if jump_port set */
1258 		    options.jump_port <= 0 ? "" : " -p ",
1259 		    options.jump_port <= 0 ? "" : port_s,
1260 		    /* Optional additional jump hosts ",..." */
1261 		    options.jump_extra == NULL ? "" : " -J ",
1262 		    options.jump_extra == NULL ? "" : options.jump_extra,
1263 		    /* Optional "-F" argumment if -F specified */
1264 		    config == NULL ? "" : " -F ",
1265 		    config == NULL ? "" : config,
1266 		    /* Optional "-v" arguments if -v set */
1267 		    debug_flag ? " -" : "",
1268 		    debug_flag, "vvv",
1269 		    /* Mandatory hostname */
1270 		    options.jump_host);
1271 		debug("Setting implicit ProxyCommand from ProxyJump: %s",
1272 		    options.proxy_command);
1273 	}
1274 
1275 	if (options.port == 0)
1276 		options.port = default_ssh_port();
1277 	channel_set_af(ssh, options.address_family);
1278 
1279 	/* Tidy and check options */
1280 	if (options.host_key_alias != NULL)
1281 		lowercase(options.host_key_alias);
1282 	if (options.proxy_command != NULL &&
1283 	    strcmp(options.proxy_command, "-") == 0 &&
1284 	    options.proxy_use_fdpass)
1285 		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1286 	if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1287 		if (options.control_persist && options.control_path != NULL) {
1288 			debug("UpdateHostKeys=ask is incompatible with "
1289 			    "ControlPersist; disabling");
1290 			options.update_hostkeys = 0;
1291 		} else if (sshbuf_len(command) != 0 ||
1292 		    options.remote_command != NULL ||
1293 		    options.request_tty == REQUEST_TTY_NO) {
1294 			debug("UpdateHostKeys=ask is incompatible with "
1295 			    "remote command execution; disabling");
1296 			options.update_hostkeys = 0;
1297 		} else if (options.log_level < SYSLOG_LEVEL_INFO) {
1298 			/* no point logging anything; user won't see it */
1299 			options.update_hostkeys = 0;
1300 		}
1301 	}
1302 	if (options.connection_attempts <= 0)
1303 		fatal("Invalid number of ConnectionAttempts");
1304 
1305 	if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1306 		fatal("Cannot execute command-line and remote command.");
1307 
1308 	/* Cannot fork to background if no command. */
1309 	if (fork_after_authentication_flag && sshbuf_len(command) == 0 &&
1310 	    options.remote_command == NULL && !no_shell_flag)
1311 		fatal("Cannot fork into background without a command "
1312 		    "to execute.");
1313 
1314 	/* reinit */
1315 	log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1316 	for (j = 0; j < options.num_log_verbose; j++)
1317 		log_verbose_add(options.log_verbose[j]);
1318 
1319 	if (options.request_tty == REQUEST_TTY_YES ||
1320 	    options.request_tty == REQUEST_TTY_FORCE)
1321 		tty_flag = 1;
1322 
1323 	/* Allocate a tty by default if no command specified. */
1324 	if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1325 		tty_flag = options.request_tty != REQUEST_TTY_NO;
1326 
1327 	/* Force no tty */
1328 	if (options.request_tty == REQUEST_TTY_NO ||
1329 	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1330 		tty_flag = 0;
1331 	/* Do not allocate a tty if stdin is not a tty. */
1332 	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1333 	    options.request_tty != REQUEST_TTY_FORCE) {
1334 		if (tty_flag)
1335 			logit("Pseudo-terminal will not be allocated because "
1336 			    "stdin is not a terminal.");
1337 		tty_flag = 0;
1338 	}
1339 
1340 	/* Set up strings used to percent_expand() arguments */
1341 	cinfo = xcalloc(1, sizeof(*cinfo));
1342 	if (gethostname(thishost, sizeof(thishost)) == -1)
1343 		fatal("gethostname: %s", strerror(errno));
1344 	cinfo->thishost = xstrdup(thishost);
1345 	thishost[strcspn(thishost, ".")] = '\0';
1346 	cinfo->shorthost = xstrdup(thishost);
1347 	xasprintf(&cinfo->portstr, "%d", options.port);
1348 	xasprintf(&cinfo->uidstr, "%llu",
1349 	    (unsigned long long)pw->pw_uid);
1350 	cinfo->keyalias = xstrdup(options.host_key_alias ?
1351 	    options.host_key_alias : host_arg);
1352 	cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
1353 	    cinfo->portstr, options.user);
1354 	cinfo->host_arg = xstrdup(host_arg);
1355 	cinfo->remhost = xstrdup(host);
1356 	cinfo->remuser = xstrdup(options.user);
1357 	cinfo->homedir = xstrdup(pw->pw_dir);
1358 	cinfo->locuser = xstrdup(pw->pw_name);
1359 
1360 	/*
1361 	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1362 	 * after port-forwarding is set up, so it may pick up any local
1363 	 * tunnel interface name allocated.
1364 	 */
1365 	if (options.remote_command != NULL) {
1366 		debug3("expanding RemoteCommand: %s", options.remote_command);
1367 		cp = options.remote_command;
1368 		options.remote_command = default_client_percent_expand(cp,
1369 		    cinfo);
1370 		debug3("expanded RemoteCommand: %s", options.remote_command);
1371 		free(cp);
1372 		if ((r = sshbuf_put(command, options.remote_command,
1373 		    strlen(options.remote_command))) != 0)
1374 			fatal_fr(r, "buffer error");
1375 	}
1376 
1377 	if (options.control_path != NULL) {
1378 		cp = tilde_expand_filename(options.control_path, getuid());
1379 		free(options.control_path);
1380 		options.control_path = default_client_percent_dollar_expand(cp,
1381 		    cinfo);
1382 		free(cp);
1383 	}
1384 
1385 	if (options.identity_agent != NULL) {
1386 		p = tilde_expand_filename(options.identity_agent, getuid());
1387 		cp = default_client_percent_dollar_expand(p, cinfo);
1388 		free(p);
1389 		free(options.identity_agent);
1390 		options.identity_agent = cp;
1391 	}
1392 
1393 	if (options.forward_agent_sock_path != NULL) {
1394 		p = tilde_expand_filename(options.forward_agent_sock_path,
1395 		    getuid());
1396 		cp = default_client_percent_dollar_expand(p, cinfo);
1397 		free(p);
1398 		free(options.forward_agent_sock_path);
1399 		options.forward_agent_sock_path = cp;
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 	if (ssh_packet_connection_is_on_socket(ssh)) {
1634 		verbose("Authenticated to %s ([%s]:%d).", host,
1635 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1636 	} else {
1637 		verbose("Authenticated to %s (via proxy).", host);
1638 	}
1639 
1640 	/* We no longer need the private host keys.  Clear them now. */
1641 	if (sensitive_data.nkeys != 0) {
1642 		for (i = 0; i < sensitive_data.nkeys; i++) {
1643 			if (sensitive_data.keys[i] != NULL) {
1644 				/* Destroys contents safely */
1645 				debug3("clear hostkey %d", i);
1646 				sshkey_free(sensitive_data.keys[i]);
1647 				sensitive_data.keys[i] = NULL;
1648 			}
1649 		}
1650 		free(sensitive_data.keys);
1651 	}
1652 	for (i = 0; i < options.num_identity_files; i++) {
1653 		free(options.identity_files[i]);
1654 		options.identity_files[i] = NULL;
1655 		if (options.identity_keys[i]) {
1656 			sshkey_free(options.identity_keys[i]);
1657 			options.identity_keys[i] = NULL;
1658 		}
1659 	}
1660 	for (i = 0; i < options.num_certificate_files; i++) {
1661 		free(options.certificate_files[i]);
1662 		options.certificate_files[i] = NULL;
1663 	}
1664 
1665  skip_connect:
1666 	exit_status = ssh_session2(ssh, cinfo);
1667 	ssh_conn_info_free(cinfo);
1668 	ssh_packet_close(ssh);
1669 
1670 	if (options.control_path != NULL && muxserver_sock != -1)
1671 		unlink(options.control_path);
1672 
1673 	/* Kill ProxyCommand if it is running. */
1674 	ssh_kill_proxy_command();
1675 
1676 	return exit_status;
1677 }
1678 
1679 static void
1680 control_persist_detach(void)
1681 {
1682 	pid_t pid;
1683 
1684 	debug_f("backgrounding master process");
1685 
1686 	/*
1687 	 * master (current process) into the background, and make the
1688 	 * foreground process a client of the backgrounded master.
1689 	 */
1690 	switch ((pid = fork())) {
1691 	case -1:
1692 		fatal_f("fork: %s", strerror(errno));
1693 	case 0:
1694 		/* Child: master process continues mainloop */
1695 		break;
1696 	default:
1697 		/* Parent: set up mux client to connect to backgrounded master */
1698 		debug2_f("background process is %ld", (long)pid);
1699 		stdin_null_flag = ostdin_null_flag;
1700 		options.request_tty = orequest_tty;
1701 		tty_flag = otty_flag;
1702 		close(muxserver_sock);
1703 		muxserver_sock = -1;
1704 		options.control_master = SSHCTL_MASTER_NO;
1705 		muxclient(options.control_path);
1706 		/* muxclient() doesn't return on success. */
1707 		fatal("Failed to connect to new control master");
1708 	}
1709 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1710 		error_f("stdfd_devnull failed");
1711 	daemon(1, 1);
1712 	setproctitle("%s [mux]", options.control_path);
1713 }
1714 
1715 /* Do fork() after authentication. Used by "ssh -f" */
1716 static void
1717 fork_postauth(void)
1718 {
1719 	if (need_controlpersist_detach)
1720 		control_persist_detach();
1721 	debug("forking to background");
1722 	fork_after_authentication_flag = 0;
1723 	if (daemon(1, 1) == -1)
1724 		fatal("daemon() failed: %.200s", strerror(errno));
1725 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1726 		error_f("stdfd_devnull failed");
1727 }
1728 
1729 static void
1730 forwarding_success(void)
1731 {
1732 	if (forward_confirms_pending == -1)
1733 		return;
1734 	if (--forward_confirms_pending == 0) {
1735 		debug_f("all expected forwarding replies received");
1736 		if (fork_after_authentication_flag)
1737 			fork_postauth();
1738 	} else {
1739 		debug2_f("%d expected forwarding replies remaining",
1740 		    forward_confirms_pending);
1741 	}
1742 }
1743 
1744 /* Callback for remote forward global requests */
1745 static void
1746 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1747 {
1748 	struct Forward *rfwd = (struct Forward *)ctxt;
1749 	u_int port;
1750 	int r;
1751 
1752 	/* XXX verbose() on failure? */
1753 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1754 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1755 	    rfwd->listen_path ? rfwd->listen_path :
1756 	    rfwd->listen_host ? rfwd->listen_host : "",
1757 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1758 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1759 	    rfwd->connect_host, rfwd->connect_port);
1760 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1761 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1762 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1763 				fatal_fr(r, "parse packet");
1764 			if (port > 65535) {
1765 				error("Invalid allocated port %u for remote "
1766 				    "forward to %s:%d", port,
1767 				    rfwd->connect_host, rfwd->connect_port);
1768 				/* Ensure failure processing runs below */
1769 				type = SSH2_MSG_REQUEST_FAILURE;
1770 				channel_update_permission(ssh,
1771 				    rfwd->handle, -1);
1772 			} else {
1773 				rfwd->allocated_port = (int)port;
1774 				logit("Allocated port %u for remote "
1775 				    "forward to %s:%d",
1776 				    rfwd->allocated_port, rfwd->connect_host,
1777 				    rfwd->connect_port);
1778 				channel_update_permission(ssh,
1779 				    rfwd->handle, rfwd->allocated_port);
1780 			}
1781 		} else {
1782 			channel_update_permission(ssh, rfwd->handle, -1);
1783 		}
1784 	}
1785 
1786 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1787 		if (options.exit_on_forward_failure) {
1788 			if (rfwd->listen_path != NULL)
1789 				fatal("Error: remote port forwarding failed "
1790 				    "for listen path %s", rfwd->listen_path);
1791 			else
1792 				fatal("Error: remote port forwarding failed "
1793 				    "for listen port %d", rfwd->listen_port);
1794 		} else {
1795 			if (rfwd->listen_path != NULL)
1796 				logit("Warning: remote port forwarding failed "
1797 				    "for listen path %s", rfwd->listen_path);
1798 			else
1799 				logit("Warning: remote port forwarding failed "
1800 				    "for listen port %d", rfwd->listen_port);
1801 		}
1802 	}
1803 	forwarding_success();
1804 }
1805 
1806 static void
1807 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1808 {
1809 	debug("stdio forwarding: done");
1810 	cleanup_exit(0);
1811 }
1812 
1813 static void
1814 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1815 {
1816 	if (!success)
1817 		fatal("stdio forwarding failed");
1818 }
1819 
1820 static void
1821 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1822 {
1823 	if (!success) {
1824 		error("Tunnel forwarding failed");
1825 		if (options.exit_on_forward_failure)
1826 			cleanup_exit(255);
1827 	}
1828 
1829 	debug_f("tunnel forward established, id=%d", id);
1830 	forwarding_success();
1831 }
1832 
1833 static void
1834 ssh_init_stdio_forwarding(struct ssh *ssh)
1835 {
1836 	Channel *c;
1837 	int in, out;
1838 
1839 	if (options.stdio_forward_host == NULL)
1840 		return;
1841 
1842 	debug3_f("%s:%d", options.stdio_forward_host,
1843 	    options.stdio_forward_port);
1844 
1845 	if ((in = dup(STDIN_FILENO)) == -1 ||
1846 	    (out = dup(STDOUT_FILENO)) == -1)
1847 		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1848 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1849 	    options.stdio_forward_port, in, out)) == NULL)
1850 		fatal_f("channel_connect_stdio_fwd failed");
1851 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1852 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1853 }
1854 
1855 static void
1856 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1857 {
1858 	int success = 0;
1859 	int i;
1860 
1861 	if (options.exit_on_forward_failure)
1862 		forward_confirms_pending = 0; /* track pending requests */
1863 	/* Initiate local TCP/IP port forwardings. */
1864 	for (i = 0; i < options.num_local_forwards; i++) {
1865 		debug("Local connections to %.200s:%d forwarded to remote "
1866 		    "address %.200s:%d",
1867 		    (options.local_forwards[i].listen_path != NULL) ?
1868 		    options.local_forwards[i].listen_path :
1869 		    (options.local_forwards[i].listen_host == NULL) ?
1870 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1871 		    options.local_forwards[i].listen_host,
1872 		    options.local_forwards[i].listen_port,
1873 		    (options.local_forwards[i].connect_path != NULL) ?
1874 		    options.local_forwards[i].connect_path :
1875 		    options.local_forwards[i].connect_host,
1876 		    options.local_forwards[i].connect_port);
1877 		success += channel_setup_local_fwd_listener(ssh,
1878 		    &options.local_forwards[i], &options.fwd_opts);
1879 	}
1880 	if (i > 0 && success != i && options.exit_on_forward_failure)
1881 		fatal("Could not request local forwarding.");
1882 	if (i > 0 && success == 0)
1883 		error("Could not request local forwarding.");
1884 
1885 	/* Initiate remote TCP/IP port forwardings. */
1886 	for (i = 0; i < options.num_remote_forwards; i++) {
1887 		debug("Remote connections from %.200s:%d forwarded to "
1888 		    "local address %.200s:%d",
1889 		    (options.remote_forwards[i].listen_path != NULL) ?
1890 		    options.remote_forwards[i].listen_path :
1891 		    (options.remote_forwards[i].listen_host == NULL) ?
1892 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1893 		    options.remote_forwards[i].listen_port,
1894 		    (options.remote_forwards[i].connect_path != NULL) ?
1895 		    options.remote_forwards[i].connect_path :
1896 		    options.remote_forwards[i].connect_host,
1897 		    options.remote_forwards[i].connect_port);
1898 		if ((options.remote_forwards[i].handle =
1899 		    channel_request_remote_forwarding(ssh,
1900 		    &options.remote_forwards[i])) >= 0) {
1901 			client_register_global_confirm(
1902 			    ssh_confirm_remote_forward,
1903 			    &options.remote_forwards[i]);
1904 			forward_confirms_pending++;
1905 		} else if (options.exit_on_forward_failure)
1906 			fatal("Could not request remote forwarding.");
1907 		else
1908 			logit("Warning: Could not request remote forwarding.");
1909 	}
1910 
1911 	/* Initiate tunnel forwarding. */
1912 	if (options.tun_open != SSH_TUNMODE_NO) {
1913 		if ((*ifname = client_request_tun_fwd(ssh,
1914 		    options.tun_open, options.tun_local,
1915 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
1916 			forward_confirms_pending++;
1917 		else if (options.exit_on_forward_failure)
1918 			fatal("Could not request tunnel forwarding.");
1919 		else
1920 			error("Could not request tunnel forwarding.");
1921 	}
1922 	if (forward_confirms_pending > 0) {
1923 		debug_f("expecting replies for %d forwards",
1924 		    forward_confirms_pending);
1925 	}
1926 }
1927 
1928 static void
1929 check_agent_present(void)
1930 {
1931 	int r;
1932 
1933 	if (options.forward_agent) {
1934 		/* Clear agent forwarding if we don't have an agent. */
1935 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1936 			options.forward_agent = 0;
1937 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
1938 				debug_r(r, "ssh_get_authentication_socket");
1939 		}
1940 	}
1941 }
1942 
1943 static void
1944 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1945 {
1946 	extern char **environ;
1947 	const char *display;
1948 	int r, interactive = tty_flag;
1949 	char *proto = NULL, *data = NULL;
1950 
1951 	if (!success)
1952 		return; /* No need for error message, channels code sens one */
1953 
1954 	display = getenv("DISPLAY");
1955 	if (display == NULL && options.forward_x11)
1956 		debug("X11 forwarding requested but DISPLAY not set");
1957 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
1958 	    options.xauth_location, options.forward_x11_trusted,
1959 	    options.forward_x11_timeout, &proto, &data) == 0) {
1960 		/* Request forwarding with authentication spoofing. */
1961 		debug("Requesting X11 forwarding with authentication "
1962 		    "spoofing.");
1963 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1964 		    data, 1);
1965 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1966 		/* XXX exit_on_forward_failure */
1967 		interactive = 1;
1968 	}
1969 
1970 	check_agent_present();
1971 	if (options.forward_agent) {
1972 		debug("Requesting authentication agent forwarding.");
1973 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1974 		if ((r = sshpkt_send(ssh)) != 0)
1975 			fatal_fr(r, "send packet");
1976 	}
1977 
1978 	/* Tell the packet module whether this is an interactive session. */
1979 	ssh_packet_set_interactive(ssh, interactive,
1980 	    options.ip_qos_interactive, options.ip_qos_bulk);
1981 
1982 	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
1983 	    NULL, fileno(stdin), command, environ);
1984 }
1985 
1986 /* open new channel for a session */
1987 static int
1988 ssh_session2_open(struct ssh *ssh)
1989 {
1990 	Channel *c;
1991 	int window, packetmax, in, out, err;
1992 
1993 	if (stdin_null_flag) {
1994 		in = open(_PATH_DEVNULL, O_RDONLY);
1995 	} else {
1996 		in = dup(STDIN_FILENO);
1997 	}
1998 	out = dup(STDOUT_FILENO);
1999 	err = dup(STDERR_FILENO);
2000 
2001 	if (in == -1 || out == -1 || err == -1)
2002 		fatal("dup() in/out/err failed");
2003 
2004 	/* enable nonblocking unless tty */
2005 	if (!isatty(in))
2006 		set_nonblock(in);
2007 	if (!isatty(out))
2008 		set_nonblock(out);
2009 	if (!isatty(err))
2010 		set_nonblock(err);
2011 
2012 	window = CHAN_SES_WINDOW_DEFAULT;
2013 	packetmax = CHAN_SES_PACKET_DEFAULT;
2014 	if (tty_flag) {
2015 		window >>= 1;
2016 		packetmax >>= 1;
2017 	}
2018 	c = channel_new(ssh,
2019 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2020 	    window, packetmax, CHAN_EXTENDED_WRITE,
2021 	    "client-session", /*nonblock*/0);
2022 
2023 	debug3_f("channel_new: %d", c->self);
2024 
2025 	channel_send_open(ssh, c->self);
2026 	if (!no_shell_flag)
2027 		channel_register_open_confirm(ssh, c->self,
2028 		    ssh_session2_setup, NULL);
2029 
2030 	return c->self;
2031 }
2032 
2033 static int
2034 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2035 {
2036 	int r, id = -1;
2037 	char *cp, *tun_fwd_ifname = NULL;
2038 
2039 	/* XXX should be pre-session */
2040 	if (!options.control_persist)
2041 		ssh_init_stdio_forwarding(ssh);
2042 
2043 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2044 
2045 	if (options.local_command != NULL) {
2046 		debug3("expanding LocalCommand: %s", options.local_command);
2047 		cp = options.local_command;
2048 		options.local_command = percent_expand(cp,
2049 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2050 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2051 		    (char *)NULL);
2052 		debug3("expanded LocalCommand: %s", options.local_command);
2053 		free(cp);
2054 	}
2055 
2056 	/* Start listening for multiplex clients */
2057 	if (!ssh_packet_get_mux(ssh))
2058 		muxserver_listen(ssh);
2059 
2060 	/*
2061 	 * If we are in control persist mode and have a working mux listen
2062 	 * socket, then prepare to background ourselves and have a foreground
2063 	 * client attach as a control client.
2064 	 * NB. we must save copies of the flags that we override for
2065 	 * the backgrounding, since we defer attachment of the client until
2066 	 * after the connection is fully established (in particular,
2067 	 * async rfwd replies have been received for ExitOnForwardFailure).
2068 	 */
2069 	if (options.control_persist && muxserver_sock != -1) {
2070 		ostdin_null_flag = stdin_null_flag;
2071 		ono_shell_flag = no_shell_flag;
2072 		orequest_tty = options.request_tty;
2073 		otty_flag = tty_flag;
2074 		stdin_null_flag = 1;
2075 		no_shell_flag = 1;
2076 		tty_flag = 0;
2077 		if (!fork_after_authentication_flag)
2078 			need_controlpersist_detach = 1;
2079 		fork_after_authentication_flag = 1;
2080 	}
2081 	/*
2082 	 * ControlPersist mux listen socket setup failed, attempt the
2083 	 * stdio forward setup that we skipped earlier.
2084 	 */
2085 	if (options.control_persist && muxserver_sock == -1)
2086 		ssh_init_stdio_forwarding(ssh);
2087 
2088 	if (!no_shell_flag)
2089 		id = ssh_session2_open(ssh);
2090 	else {
2091 		ssh_packet_set_interactive(ssh,
2092 		    options.control_master == SSHCTL_MASTER_NO,
2093 		    options.ip_qos_interactive, options.ip_qos_bulk);
2094 	}
2095 
2096 	/* If we don't expect to open a new session, then disallow it */
2097 	if (options.control_master == SSHCTL_MASTER_NO &&
2098 	    (datafellows & SSH_NEW_OPENSSH)) {
2099 		debug("Requesting no-more-sessions@openssh.com");
2100 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2101 		    (r = sshpkt_put_cstring(ssh,
2102 		    "no-more-sessions@openssh.com")) != 0 ||
2103 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2104 		    (r = sshpkt_send(ssh)) != 0)
2105 			fatal_fr(r, "send packet");
2106 	}
2107 
2108 	/* Execute a local command */
2109 	if (options.local_command != NULL &&
2110 	    options.permit_local_command)
2111 		ssh_local_cmd(options.local_command);
2112 
2113 	/*
2114 	 * stdout is now owned by the session channel; clobber it here
2115 	 * so future channel closes are propagated to the local fd.
2116 	 * NB. this can only happen after LocalCommand has completed,
2117 	 * as it may want to write to stdout.
2118 	 */
2119 	if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2120 		error_f("stdfd_devnull failed");
2121 
2122 	/*
2123 	 * If requested and we are not interested in replies to remote
2124 	 * forwarding requests, then let ssh continue in the background.
2125 	 */
2126 	if (fork_after_authentication_flag) {
2127 		if (options.exit_on_forward_failure &&
2128 		    options.num_remote_forwards > 0) {
2129 			debug("deferring postauth fork until remote forward "
2130 			    "confirmation received");
2131 		} else
2132 			fork_postauth();
2133 	}
2134 
2135 	return client_loop(ssh, tty_flag, tty_flag ?
2136 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2137 }
2138 
2139 /* Loads all IdentityFile and CertificateFile keys */
2140 static void
2141 load_public_identity_files(const struct ssh_conn_info *cinfo)
2142 {
2143 	char *filename, *cp;
2144 	struct sshkey *public;
2145 	int i;
2146 	u_int n_ids, n_certs;
2147 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2148 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2149 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2150 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2151 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2152 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2153 #ifdef ENABLE_PKCS11
2154 	struct sshkey **keys = NULL;
2155 	char **comments = NULL;
2156 	int nkeys;
2157 #endif /* PKCS11 */
2158 
2159 	n_ids = n_certs = 0;
2160 	memset(identity_files, 0, sizeof(identity_files));
2161 	memset(identity_keys, 0, sizeof(identity_keys));
2162 	memset(identity_file_userprovided, 0,
2163 	    sizeof(identity_file_userprovided));
2164 	memset(certificate_files, 0, sizeof(certificate_files));
2165 	memset(certificates, 0, sizeof(certificates));
2166 	memset(certificate_file_userprovided, 0,
2167 	    sizeof(certificate_file_userprovided));
2168 
2169 #ifdef ENABLE_PKCS11
2170 	if (options.pkcs11_provider != NULL &&
2171 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2172 	    (pkcs11_init(!options.batch_mode) == 0) &&
2173 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2174 	    &keys, &comments)) > 0) {
2175 		for (i = 0; i < nkeys; i++) {
2176 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2177 				sshkey_free(keys[i]);
2178 				free(comments[i]);
2179 				continue;
2180 			}
2181 			identity_keys[n_ids] = keys[i];
2182 			identity_files[n_ids] = comments[i]; /* transferred */
2183 			n_ids++;
2184 		}
2185 		free(keys);
2186 		free(comments);
2187 	}
2188 #endif /* ENABLE_PKCS11 */
2189 	for (i = 0; i < options.num_identity_files; i++) {
2190 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2191 		    strcasecmp(options.identity_files[i], "none") == 0) {
2192 			free(options.identity_files[i]);
2193 			options.identity_files[i] = NULL;
2194 			continue;
2195 		}
2196 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2197 		filename = default_client_percent_dollar_expand(cp, cinfo);
2198 		free(cp);
2199 		check_load(sshkey_load_public(filename, &public, NULL),
2200 		    filename, "pubkey");
2201 		debug("identity file %s type %d", filename,
2202 		    public ? public->type : -1);
2203 		free(options.identity_files[i]);
2204 		identity_files[n_ids] = filename;
2205 		identity_keys[n_ids] = public;
2206 		identity_file_userprovided[n_ids] =
2207 		    options.identity_file_userprovided[i];
2208 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2209 			continue;
2210 
2211 		/*
2212 		 * If no certificates have been explicitly listed then try
2213 		 * to add the default certificate variant too.
2214 		 */
2215 		if (options.num_certificate_files != 0)
2216 			continue;
2217 		xasprintf(&cp, "%s-cert", filename);
2218 		check_load(sshkey_load_public(cp, &public, NULL),
2219 		    filename, "pubkey");
2220 		debug("identity file %s type %d", cp,
2221 		    public ? public->type : -1);
2222 		if (public == NULL) {
2223 			free(cp);
2224 			continue;
2225 		}
2226 		if (!sshkey_is_cert(public)) {
2227 			debug_f("key %s type %s is not a certificate",
2228 			    cp, sshkey_type(public));
2229 			sshkey_free(public);
2230 			free(cp);
2231 			continue;
2232 		}
2233 		/* NB. leave filename pointing to private key */
2234 		identity_files[n_ids] = xstrdup(filename);
2235 		identity_keys[n_ids] = public;
2236 		identity_file_userprovided[n_ids] =
2237 		    options.identity_file_userprovided[i];
2238 		n_ids++;
2239 	}
2240 
2241 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2242 		fatal_f("too many certificates");
2243 	for (i = 0; i < options.num_certificate_files; i++) {
2244 		cp = tilde_expand_filename(options.certificate_files[i],
2245 		    getuid());
2246 		filename = default_client_percent_dollar_expand(cp, cinfo);
2247 		free(cp);
2248 
2249 		check_load(sshkey_load_public(filename, &public, NULL),
2250 		    filename, "certificate");
2251 		debug("certificate file %s type %d", filename,
2252 		    public ? public->type : -1);
2253 		free(options.certificate_files[i]);
2254 		options.certificate_files[i] = NULL;
2255 		if (public == NULL) {
2256 			free(filename);
2257 			continue;
2258 		}
2259 		if (!sshkey_is_cert(public)) {
2260 			debug_f("key %s type %s is not a certificate",
2261 			    filename, sshkey_type(public));
2262 			sshkey_free(public);
2263 			free(filename);
2264 			continue;
2265 		}
2266 		certificate_files[n_certs] = filename;
2267 		certificates[n_certs] = public;
2268 		certificate_file_userprovided[n_certs] =
2269 		    options.certificate_file_userprovided[i];
2270 		++n_certs;
2271 	}
2272 
2273 	options.num_identity_files = n_ids;
2274 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2275 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2276 	memcpy(options.identity_file_userprovided,
2277 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2278 
2279 	options.num_certificate_files = n_certs;
2280 	memcpy(options.certificate_files,
2281 	    certificate_files, sizeof(certificate_files));
2282 	memcpy(options.certificates, certificates, sizeof(certificates));
2283 	memcpy(options.certificate_file_userprovided,
2284 	    certificate_file_userprovided,
2285 	    sizeof(certificate_file_userprovided));
2286 }
2287 
2288 static void
2289 main_sigchld_handler(int sig)
2290 {
2291 	int save_errno = errno;
2292 	pid_t pid;
2293 	int status;
2294 
2295 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2296 	    (pid == -1 && errno == EINTR))
2297 		;
2298 	errno = save_errno;
2299 }
2300