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