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