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