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