xref: /openssh-portable/ssh.c (revision 4a1b46e6)
1 /* $OpenBSD: ssh.c,v 1.528 2020/05/29 04:25:40 dtucker Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Ssh client program.  This program can be used to log into a remote machine.
7  * The software supports strong authentication, encryption, and forwarding
8  * of X11, TCP/IP, and authentication connections.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18  *
19  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20  * in Canada (German citizen).
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the above copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41  */
42 
43 #include "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 slave launched in the foreground for ControlPersist.
141  */
142 int need_controlpersist_detach = 0;
143 
144 /* Copies of flags for ControlPersist foreground slave */
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, buf[PATH_MAX], *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 
658 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
659 	sanitise_stdfd();
660 
661 	__progname = ssh_get_progname(av[0]);
662 
663 #ifndef HAVE_SETPROCTITLE
664 	/* Prepare for later setproctitle emulation */
665 	/* Save argv so it isn't clobbered by setproctitle() emulation */
666 	saved_av = xcalloc(ac + 1, sizeof(*saved_av));
667 	for (i = 0; i < ac; i++)
668 		saved_av[i] = xstrdup(av[i]);
669 	saved_av[i] = NULL;
670 	compat_init_setproctitle(ac, av);
671 	av = saved_av;
672 #endif
673 
674 	seed_rng();
675 
676 	/*
677 	 * Discard other fds that are hanging around. These can cause problem
678 	 * with backgrounded ssh processes started by ControlPersist.
679 	 */
680 	closefrom(STDERR_FILENO + 1);
681 
682 	/* Get user data. */
683 	pw = getpwuid(getuid());
684 	if (!pw) {
685 		logit("No user exists for uid %lu", (u_long)getuid());
686 		exit(255);
687 	}
688 	/* Take a copy of the returned structure. */
689 	pw = pwcopy(pw);
690 
691 	/*
692 	 * Set our umask to something reasonable, as some files are created
693 	 * with the default umask.  This will make them world-readable but
694 	 * writable only by the owner, which is ok for all files for which we
695 	 * don't set the modes explicitly.
696 	 */
697 	umask(022);
698 
699 	msetlocale();
700 
701 	/*
702 	 * Initialize option structure to indicate that no values have been
703 	 * set.
704 	 */
705 	initialize_options(&options);
706 
707 	/*
708 	 * Prepare main ssh transport/connection structures
709 	 */
710 	if ((ssh = ssh_alloc_session_state()) == NULL)
711 		fatal("Couldn't allocate session state");
712 	channel_init_channels(ssh);
713 
714 	/* Parse command-line arguments. */
715 	host = NULL;
716 	use_syslog = 0;
717 	logfile = NULL;
718 	argv0 = av[0];
719 
720  again:
721 	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
722 	    "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
723 		switch (opt) {
724 		case '1':
725 			fatal("SSH protocol v.1 is no longer supported");
726 			break;
727 		case '2':
728 			/* Ignored */
729 			break;
730 		case '4':
731 			options.address_family = AF_INET;
732 			break;
733 		case '6':
734 			options.address_family = AF_INET6;
735 			break;
736 		case 'n':
737 			stdin_null_flag = 1;
738 			break;
739 		case 'f':
740 			fork_after_authentication_flag = 1;
741 			stdin_null_flag = 1;
742 			break;
743 		case 'x':
744 			options.forward_x11 = 0;
745 			break;
746 		case 'X':
747 			options.forward_x11 = 1;
748 			break;
749 		case 'y':
750 			use_syslog = 1;
751 			break;
752 		case 'E':
753 			logfile = optarg;
754 			break;
755 		case 'G':
756 			config_test = 1;
757 			break;
758 		case 'Y':
759 			options.forward_x11 = 1;
760 			options.forward_x11_trusted = 1;
761 			break;
762 		case 'g':
763 			options.fwd_opts.gateway_ports = 1;
764 			break;
765 		case 'O':
766 			if (options.stdio_forward_host != NULL)
767 				fatal("Cannot specify multiplexing "
768 				    "command with -W");
769 			else if (muxclient_command != 0)
770 				fatal("Multiplexing command already specified");
771 			if (strcmp(optarg, "check") == 0)
772 				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
773 			else if (strcmp(optarg, "forward") == 0)
774 				muxclient_command = SSHMUX_COMMAND_FORWARD;
775 			else if (strcmp(optarg, "exit") == 0)
776 				muxclient_command = SSHMUX_COMMAND_TERMINATE;
777 			else if (strcmp(optarg, "stop") == 0)
778 				muxclient_command = SSHMUX_COMMAND_STOP;
779 			else if (strcmp(optarg, "cancel") == 0)
780 				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
781 			else if (strcmp(optarg, "proxy") == 0)
782 				muxclient_command = SSHMUX_COMMAND_PROXY;
783 			else
784 				fatal("Invalid multiplex command.");
785 			break;
786 		case 'P':	/* deprecated */
787 			break;
788 		case 'Q':
789 			cp = NULL;
790 			if (strcmp(optarg, "cipher") == 0 ||
791 			    strcasecmp(optarg, "Ciphers") == 0)
792 				cp = cipher_alg_list('\n', 0);
793 			else if (strcmp(optarg, "cipher-auth") == 0)
794 				cp = cipher_alg_list('\n', 1);
795 			else if (strcmp(optarg, "mac") == 0 ||
796 			    strcasecmp(optarg, "MACs") == 0)
797 				cp = mac_alg_list('\n');
798 			else if (strcmp(optarg, "kex") == 0 ||
799 			    strcasecmp(optarg, "KexAlgorithms") == 0)
800 				cp = kex_alg_list('\n');
801 			else if (strcmp(optarg, "key") == 0)
802 				cp = sshkey_alg_list(0, 0, 0, '\n');
803 			else if (strcmp(optarg, "key-cert") == 0)
804 				cp = sshkey_alg_list(1, 0, 0, '\n');
805 			else if (strcmp(optarg, "key-plain") == 0)
806 				cp = sshkey_alg_list(0, 1, 0, '\n');
807 			else if (strcmp(optarg, "key-sig") == 0 ||
808 			    strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 ||
809 			    strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
810 			    strcasecmp(optarg, "HostbasedKeyTypes") == 0 ||
811 			    strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0)
812 				cp = sshkey_alg_list(0, 0, 1, '\n');
813 			else if (strcmp(optarg, "sig") == 0)
814 				cp = sshkey_alg_list(0, 1, 1, '\n');
815 			else if (strcmp(optarg, "protocol-version") == 0)
816 				cp = xstrdup("2");
817 			else if (strcmp(optarg, "compression") == 0) {
818 				cp = xstrdup(compression_alg_list(0));
819 				len = strlen(cp);
820 				for (n = 0; n < len; n++)
821 					if (cp[n] == ',')
822 						cp[n] = '\n';
823 			} else if (strcmp(optarg, "help") == 0) {
824 				cp = xstrdup(
825 				    "cipher\ncipher-auth\ncompression\nkex\n"
826 				    "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
827 				    "protocol-version\nsig");
828 			}
829 			if (cp == NULL)
830 				fatal("Unsupported query \"%s\"", optarg);
831 			printf("%s\n", cp);
832 			free(cp);
833 			exit(0);
834 			break;
835 		case 'a':
836 			options.forward_agent = 0;
837 			break;
838 		case 'A':
839 			options.forward_agent = 1;
840 			break;
841 		case 'k':
842 			options.gss_deleg_creds = 0;
843 			break;
844 		case 'K':
845 			options.gss_authentication = 1;
846 			options.gss_deleg_creds = 1;
847 			break;
848 		case 'i':
849 			p = tilde_expand_filename(optarg, getuid());
850 			if (stat(p, &st) == -1)
851 				fprintf(stderr, "Warning: Identity file %s "
852 				    "not accessible: %s.\n", p,
853 				    strerror(errno));
854 			else
855 				add_identity_file(&options, NULL, p, 1);
856 			free(p);
857 			break;
858 		case 'I':
859 #ifdef ENABLE_PKCS11
860 			free(options.pkcs11_provider);
861 			options.pkcs11_provider = xstrdup(optarg);
862 #else
863 			fprintf(stderr, "no support for PKCS#11.\n");
864 #endif
865 			break;
866 		case 'J':
867 			if (options.jump_host != NULL) {
868 				fatal("Only a single -J option is permitted "
869 				    "(use commas to separate multiple "
870 				    "jump hops)");
871 			}
872 			if (options.proxy_command != NULL)
873 				fatal("Cannot specify -J with ProxyCommand");
874 			if (parse_jump(optarg, &options, 1) == -1)
875 				fatal("Invalid -J argument");
876 			options.proxy_command = xstrdup("none");
877 			break;
878 		case 't':
879 			if (options.request_tty == REQUEST_TTY_YES)
880 				options.request_tty = REQUEST_TTY_FORCE;
881 			else
882 				options.request_tty = REQUEST_TTY_YES;
883 			break;
884 		case 'v':
885 			if (debug_flag == 0) {
886 				debug_flag = 1;
887 				options.log_level = SYSLOG_LEVEL_DEBUG1;
888 			} else {
889 				if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
890 					debug_flag++;
891 					options.log_level++;
892 				}
893 			}
894 			break;
895 		case 'V':
896 			fprintf(stderr, "%s, %s\n",
897 			    SSH_RELEASE,
898 #ifdef WITH_OPENSSL
899 			    OpenSSL_version(OPENSSL_VERSION)
900 #else
901 			    "without OpenSSL"
902 #endif
903 			);
904 			if (opt == 'V')
905 				exit(0);
906 			break;
907 		case 'w':
908 			if (options.tun_open == -1)
909 				options.tun_open = SSH_TUNMODE_DEFAULT;
910 			options.tun_local = a2tun(optarg, &options.tun_remote);
911 			if (options.tun_local == SSH_TUNID_ERR) {
912 				fprintf(stderr,
913 				    "Bad tun device '%s'\n", optarg);
914 				exit(255);
915 			}
916 			break;
917 		case 'W':
918 			if (options.stdio_forward_host != NULL)
919 				fatal("stdio forward already specified");
920 			if (muxclient_command != 0)
921 				fatal("Cannot specify stdio forward with -O");
922 			if (parse_forward(&fwd, optarg, 1, 0)) {
923 				options.stdio_forward_host = fwd.listen_host;
924 				options.stdio_forward_port = fwd.listen_port;
925 				free(fwd.connect_host);
926 			} else {
927 				fprintf(stderr,
928 				    "Bad stdio forwarding specification '%s'\n",
929 				    optarg);
930 				exit(255);
931 			}
932 			options.request_tty = REQUEST_TTY_NO;
933 			no_shell_flag = 1;
934 			break;
935 		case 'q':
936 			options.log_level = SYSLOG_LEVEL_QUIET;
937 			break;
938 		case 'e':
939 			if (optarg[0] == '^' && optarg[2] == 0 &&
940 			    (u_char) optarg[1] >= 64 &&
941 			    (u_char) optarg[1] < 128)
942 				options.escape_char = (u_char) optarg[1] & 31;
943 			else if (strlen(optarg) == 1)
944 				options.escape_char = (u_char) optarg[0];
945 			else if (strcmp(optarg, "none") == 0)
946 				options.escape_char = SSH_ESCAPECHAR_NONE;
947 			else {
948 				fprintf(stderr, "Bad escape character '%s'.\n",
949 				    optarg);
950 				exit(255);
951 			}
952 			break;
953 		case 'c':
954 			if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
955 			    optarg + 1 : optarg)) {
956 				fprintf(stderr, "Unknown cipher type '%s'\n",
957 				    optarg);
958 				exit(255);
959 			}
960 			free(options.ciphers);
961 			options.ciphers = xstrdup(optarg);
962 			break;
963 		case 'm':
964 			if (mac_valid(optarg)) {
965 				free(options.macs);
966 				options.macs = xstrdup(optarg);
967 			} else {
968 				fprintf(stderr, "Unknown mac type '%s'\n",
969 				    optarg);
970 				exit(255);
971 			}
972 			break;
973 		case 'M':
974 			if (options.control_master == SSHCTL_MASTER_YES)
975 				options.control_master = SSHCTL_MASTER_ASK;
976 			else
977 				options.control_master = SSHCTL_MASTER_YES;
978 			break;
979 		case 'p':
980 			if (options.port == -1) {
981 				options.port = a2port(optarg);
982 				if (options.port <= 0) {
983 					fprintf(stderr, "Bad port '%s'\n",
984 					    optarg);
985 					exit(255);
986 				}
987 			}
988 			break;
989 		case 'l':
990 			if (options.user == NULL)
991 				options.user = optarg;
992 			break;
993 
994 		case 'L':
995 			if (parse_forward(&fwd, optarg, 0, 0))
996 				add_local_forward(&options, &fwd);
997 			else {
998 				fprintf(stderr,
999 				    "Bad local forwarding specification '%s'\n",
1000 				    optarg);
1001 				exit(255);
1002 			}
1003 			break;
1004 
1005 		case 'R':
1006 			if (parse_forward(&fwd, optarg, 0, 1) ||
1007 			    parse_forward(&fwd, optarg, 1, 1)) {
1008 				add_remote_forward(&options, &fwd);
1009 			} else {
1010 				fprintf(stderr,
1011 				    "Bad remote forwarding specification "
1012 				    "'%s'\n", optarg);
1013 				exit(255);
1014 			}
1015 			break;
1016 
1017 		case 'D':
1018 			if (parse_forward(&fwd, optarg, 1, 0)) {
1019 				add_local_forward(&options, &fwd);
1020 			} else {
1021 				fprintf(stderr,
1022 				    "Bad dynamic forwarding specification "
1023 				    "'%s'\n", optarg);
1024 				exit(255);
1025 			}
1026 			break;
1027 
1028 		case 'C':
1029 #ifdef WITH_ZLIB
1030 			options.compression = 1;
1031 #else
1032 			error("Compression not supported, disabling.");
1033 #endif
1034 			break;
1035 		case 'N':
1036 			no_shell_flag = 1;
1037 			options.request_tty = REQUEST_TTY_NO;
1038 			break;
1039 		case 'T':
1040 			options.request_tty = REQUEST_TTY_NO;
1041 			break;
1042 		case 'o':
1043 			line = xstrdup(optarg);
1044 			if (process_config_line(&options, pw,
1045 			    host ? host : "", host ? host : "", line,
1046 			    "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1047 				exit(255);
1048 			free(line);
1049 			break;
1050 		case 's':
1051 			subsystem_flag = 1;
1052 			break;
1053 		case 'S':
1054 			free(options.control_path);
1055 			options.control_path = xstrdup(optarg);
1056 			break;
1057 		case 'b':
1058 			options.bind_address = optarg;
1059 			break;
1060 		case 'B':
1061 			options.bind_interface = optarg;
1062 			break;
1063 		case 'F':
1064 			config = optarg;
1065 			break;
1066 		default:
1067 			usage();
1068 		}
1069 	}
1070 
1071 	if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1072 		opt_terminated = 1;
1073 
1074 	ac -= optind;
1075 	av += optind;
1076 
1077 	if (ac > 0 && !host) {
1078 		int tport;
1079 		char *tuser;
1080 		switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1081 		case -1:
1082 			usage();
1083 			break;
1084 		case 0:
1085 			if (options.user == NULL) {
1086 				options.user = tuser;
1087 				tuser = NULL;
1088 			}
1089 			free(tuser);
1090 			if (options.port == -1 && tport != -1)
1091 				options.port = tport;
1092 			break;
1093 		default:
1094 			p = xstrdup(*av);
1095 			cp = strrchr(p, '@');
1096 			if (cp != NULL) {
1097 				if (cp == p)
1098 					usage();
1099 				if (options.user == NULL) {
1100 					options.user = p;
1101 					p = NULL;
1102 				}
1103 				*cp++ = '\0';
1104 				host = xstrdup(cp);
1105 				free(p);
1106 			} else
1107 				host = p;
1108 			break;
1109 		}
1110 		if (ac > 1 && !opt_terminated) {
1111 			optind = optreset = 1;
1112 			goto again;
1113 		}
1114 		ac--, av++;
1115 	}
1116 
1117 	/* Check that we got a host name. */
1118 	if (!host)
1119 		usage();
1120 
1121 	host_arg = xstrdup(host);
1122 
1123 	/* Initialize the command to execute on remote host. */
1124 	if ((command = sshbuf_new()) == NULL)
1125 		fatal("sshbuf_new failed");
1126 
1127 	/*
1128 	 * Save the command to execute on the remote host in a buffer. There
1129 	 * is no limit on the length of the command, except by the maximum
1130 	 * packet size.  Also sets the tty flag if there is no command.
1131 	 */
1132 	if (!ac) {
1133 		/* No command specified - execute shell on a tty. */
1134 		if (subsystem_flag) {
1135 			fprintf(stderr,
1136 			    "You must specify a subsystem to invoke.\n");
1137 			usage();
1138 		}
1139 	} else {
1140 		/* A command has been specified.  Store it into the buffer. */
1141 		for (i = 0; i < ac; i++) {
1142 			if ((r = sshbuf_putf(command, "%s%s",
1143 			    i ? " " : "", av[i])) != 0)
1144 				fatal("%s: buffer error: %s",
1145 				    __func__, ssh_err(r));
1146 		}
1147 	}
1148 
1149 	/*
1150 	 * Initialize "log" output.  Since we are the client all output
1151 	 * goes to stderr unless otherwise specified by -y or -E.
1152 	 */
1153 	if (use_syslog && logfile != NULL)
1154 		fatal("Can't specify both -y and -E");
1155 	if (logfile != NULL)
1156 		log_redirect_stderr_to(logfile);
1157 	log_init(argv0,
1158 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1159 	    SYSLOG_LEVEL_INFO : options.log_level,
1160 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1161 	    SYSLOG_FACILITY_USER : options.log_facility,
1162 	    !use_syslog);
1163 
1164 	if (debug_flag)
1165 		logit("%s, %s", SSH_RELEASE,
1166 #ifdef WITH_OPENSSL
1167 		    OpenSSL_version(OPENSSL_VERSION)
1168 #else
1169 		    "without OpenSSL"
1170 #endif
1171 		);
1172 
1173 	/* Parse the configuration files */
1174 	process_config_files(host_arg, pw, 0, &want_final_pass);
1175 	if (want_final_pass)
1176 		debug("configuration requests final Match pass");
1177 
1178 	/* Hostname canonicalisation needs a few options filled. */
1179 	fill_default_options_for_canonicalization(&options);
1180 
1181 	/* If the user has replaced the hostname then take it into use now */
1182 	if (options.hostname != NULL) {
1183 		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
1184 		cp = percent_expand(options.hostname,
1185 		    "h", host, (char *)NULL);
1186 		free(host);
1187 		host = cp;
1188 		free(options.hostname);
1189 		options.hostname = xstrdup(host);
1190 	}
1191 
1192 	/* Don't lowercase addresses, they will be explicitly canonicalised */
1193 	if ((was_addr = is_addr(host)) == 0)
1194 		lowercase(host);
1195 
1196 	/*
1197 	 * Try to canonicalize if requested by configuration or the
1198 	 * hostname is an address.
1199 	 */
1200 	if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1201 		addrs = resolve_canonicalize(&host, options.port);
1202 
1203 	/*
1204 	 * If CanonicalizePermittedCNAMEs have been specified but
1205 	 * other canonicalization did not happen (by not being requested
1206 	 * or by failing with fallback) then the hostname may still be changed
1207 	 * as a result of CNAME following.
1208 	 *
1209 	 * Try to resolve the bare hostname name using the system resolver's
1210 	 * usual search rules and then apply the CNAME follow rules.
1211 	 *
1212 	 * Skip the lookup if a ProxyCommand is being used unless the user
1213 	 * has specifically requested canonicalisation for this case via
1214 	 * CanonicalizeHostname=always
1215 	 */
1216 	direct = option_clear_or_none(options.proxy_command) &&
1217 	    options.jump_host == NULL;
1218 	if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1219 	    options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1220 		if ((addrs = resolve_host(host, options.port,
1221 		    direct, cname, sizeof(cname))) == NULL) {
1222 			/* Don't fatal proxied host names not in the DNS */
1223 			if (direct)
1224 				cleanup_exit(255); /* logged in resolve_host */
1225 		} else
1226 			check_follow_cname(direct, &host, cname);
1227 	}
1228 
1229 	/*
1230 	 * If canonicalisation is enabled then re-parse the configuration
1231 	 * files as new stanzas may match.
1232 	 */
1233 	if (options.canonicalize_hostname != 0 && !want_final_pass) {
1234 		debug("hostname canonicalisation enabled, "
1235 		    "will re-parse configuration");
1236 		want_final_pass = 1;
1237 	}
1238 
1239 	if (want_final_pass) {
1240 		debug("re-parsing configuration");
1241 		free(options.hostname);
1242 		options.hostname = xstrdup(host);
1243 		process_config_files(host_arg, pw, 1, NULL);
1244 		/*
1245 		 * Address resolution happens early with canonicalisation
1246 		 * enabled and the port number may have changed since, so
1247 		 * reset it in address list
1248 		 */
1249 		if (addrs != NULL && options.port > 0)
1250 			set_addrinfo_port(addrs, options.port);
1251 	}
1252 
1253 	/* Fill configuration defaults. */
1254 	fill_default_options(&options);
1255 
1256 	/*
1257 	 * If ProxyJump option specified, then construct a ProxyCommand now.
1258 	 */
1259 	if (options.jump_host != NULL) {
1260 		char port_s[8];
1261 		const char *sshbin = argv0;
1262 		int port = options.port, jumpport = options.jump_port;
1263 
1264 		if (port <= 0)
1265 			port = default_ssh_port();
1266 		if (jumpport <= 0)
1267 			jumpport = default_ssh_port();
1268 		if (strcmp(options.jump_host, host) == 0 && port == jumpport)
1269 			fatal("jumphost loop via %s", options.jump_host);
1270 
1271 		/*
1272 		 * Try to use SSH indicated by argv[0], but fall back to
1273 		 * "ssh" if it appears unavailable.
1274 		 */
1275 		if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1276 			sshbin = "ssh";
1277 
1278 		/* Consistency check */
1279 		if (options.proxy_command != NULL)
1280 			fatal("inconsistent options: ProxyCommand+ProxyJump");
1281 		/* Never use FD passing for ProxyJump */
1282 		options.proxy_use_fdpass = 0;
1283 		snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1284 		xasprintf(&options.proxy_command,
1285 		    "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1286 		    sshbin,
1287 		    /* Optional "-l user" argument if jump_user set */
1288 		    options.jump_user == NULL ? "" : " -l ",
1289 		    options.jump_user == NULL ? "" : options.jump_user,
1290 		    /* Optional "-p port" argument if jump_port set */
1291 		    options.jump_port <= 0 ? "" : " -p ",
1292 		    options.jump_port <= 0 ? "" : port_s,
1293 		    /* Optional additional jump hosts ",..." */
1294 		    options.jump_extra == NULL ? "" : " -J ",
1295 		    options.jump_extra == NULL ? "" : options.jump_extra,
1296 		    /* Optional "-F" argumment if -F specified */
1297 		    config == NULL ? "" : " -F ",
1298 		    config == NULL ? "" : config,
1299 		    /* Optional "-v" arguments if -v set */
1300 		    debug_flag ? " -" : "",
1301 		    debug_flag, "vvv",
1302 		    /* Mandatory hostname */
1303 		    options.jump_host);
1304 		debug("Setting implicit ProxyCommand from ProxyJump: %s",
1305 		    options.proxy_command);
1306 	}
1307 
1308 	if (options.port == 0)
1309 		options.port = default_ssh_port();
1310 	channel_set_af(ssh, options.address_family);
1311 
1312 	/* Tidy and check options */
1313 	if (options.host_key_alias != NULL)
1314 		lowercase(options.host_key_alias);
1315 	if (options.proxy_command != NULL &&
1316 	    strcmp(options.proxy_command, "-") == 0 &&
1317 	    options.proxy_use_fdpass)
1318 		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1319 	if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1320 		if (options.control_persist && options.control_path != NULL) {
1321 			debug("UpdateHostKeys=ask is incompatible with "
1322 			    "ControlPersist; disabling");
1323 			options.update_hostkeys = 0;
1324 		} else if (sshbuf_len(command) != 0 ||
1325 		    options.remote_command != NULL ||
1326 		    options.request_tty == REQUEST_TTY_NO) {
1327 			debug("UpdateHostKeys=ask is incompatible with "
1328 			    "remote command execution; disabling");
1329 			options.update_hostkeys = 0;
1330 		} else if (options.log_level < SYSLOG_LEVEL_INFO) {
1331 			/* no point logging anything; user won't see it */
1332 			options.update_hostkeys = 0;
1333 		}
1334 	}
1335 	if (options.connection_attempts <= 0)
1336 		fatal("Invalid number of ConnectionAttempts");
1337 
1338 	if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1339 		fatal("Cannot execute command-line and remote command.");
1340 
1341 	/* Cannot fork to background if no command. */
1342 	if (fork_after_authentication_flag && sshbuf_len(command) == 0 &&
1343 	    options.remote_command == NULL && !no_shell_flag)
1344 		fatal("Cannot fork into background without a command "
1345 		    "to execute.");
1346 
1347 	/* reinit */
1348 	log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1349 
1350 	if (options.request_tty == REQUEST_TTY_YES ||
1351 	    options.request_tty == REQUEST_TTY_FORCE)
1352 		tty_flag = 1;
1353 
1354 	/* Allocate a tty by default if no command specified. */
1355 	if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1356 		tty_flag = options.request_tty != REQUEST_TTY_NO;
1357 
1358 	/* Force no tty */
1359 	if (options.request_tty == REQUEST_TTY_NO ||
1360 	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1361 		tty_flag = 0;
1362 	/* Do not allocate a tty if stdin is not a tty. */
1363 	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1364 	    options.request_tty != REQUEST_TTY_FORCE) {
1365 		if (tty_flag)
1366 			logit("Pseudo-terminal will not be allocated because "
1367 			    "stdin is not a terminal.");
1368 		tty_flag = 0;
1369 	}
1370 
1371 	if (options.user == NULL)
1372 		options.user = xstrdup(pw->pw_name);
1373 
1374 	/* Set up strings used to percent_expand() arguments */
1375 	if (gethostname(thishost, sizeof(thishost)) == -1)
1376 		fatal("gethostname: %s", strerror(errno));
1377 	strlcpy(shorthost, thishost, sizeof(shorthost));
1378 	shorthost[strcspn(thishost, ".")] = '\0';
1379 	snprintf(portstr, sizeof(portstr), "%d", options.port);
1380 	snprintf(uidstr, sizeof(uidstr), "%llu",
1381 	    (unsigned long long)pw->pw_uid);
1382 
1383 	conn_hash_hex = ssh_connection_hash(thishost, host, portstr,
1384 	    options.user);
1385 
1386 	/*
1387 	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1388 	 * after port-forwarding is set up, so it may pick up any local
1389 	 * tunnel interface name allocated.
1390 	 */
1391 	if (options.remote_command != NULL) {
1392 		debug3("expanding RemoteCommand: %s", options.remote_command);
1393 		cp = options.remote_command;
1394 		options.remote_command = default_client_percent_expand(cp,
1395 		    pw->pw_dir, host, options.user, pw->pw_name);
1396 		debug3("expanded RemoteCommand: %s", options.remote_command);
1397 		free(cp);
1398 		if ((r = sshbuf_put(command, options.remote_command,
1399 		    strlen(options.remote_command))) != 0)
1400 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1401 	}
1402 
1403 	if (options.control_path != NULL) {
1404 		cp = tilde_expand_filename(options.control_path, getuid());
1405 		free(options.control_path);
1406 		options.control_path = default_client_percent_dollar_expand(cp,
1407 		    pw->pw_dir, host, options.user, pw->pw_name);
1408 		free(cp);
1409 	}
1410 
1411 	if (options.identity_agent != NULL) {
1412 		p = tilde_expand_filename(options.identity_agent, getuid());
1413 		cp = default_client_percent_dollar_expand(p,
1414 		    pw->pw_dir, host, options.user, pw->pw_name);
1415 		free(p);
1416 		free(options.identity_agent);
1417 		options.identity_agent = cp;
1418 	}
1419 
1420 	if (options.forward_agent_sock_path != NULL) {
1421 		p = tilde_expand_filename(options.forward_agent_sock_path,
1422 		    getuid());
1423 		cp = default_client_percent_dollar_expand(p,
1424 		    pw->pw_dir, host, options.user, pw->pw_name);
1425 		free(p);
1426 		free(options.forward_agent_sock_path);
1427 		options.forward_agent_sock_path = cp;
1428 	}
1429 
1430 	for (i = 0; i < options.num_local_forwards; i++) {
1431 		if (options.local_forwards[i].listen_path != NULL) {
1432 			cp = options.local_forwards[i].listen_path;
1433 			p = options.local_forwards[i].listen_path =
1434 			    default_client_percent_expand(cp,
1435 			    pw->pw_dir, host, options.user, pw->pw_name);
1436 			if (strcmp(cp, p) != 0)
1437 				debug3("expanded LocalForward listen path "
1438 				    "'%s' -> '%s'", cp, p);
1439 			free(cp);
1440 		}
1441 		if (options.local_forwards[i].connect_path != NULL) {
1442 			cp = options.local_forwards[i].connect_path;
1443 			p = options.local_forwards[i].connect_path =
1444 			    default_client_percent_expand(cp,
1445 			    pw->pw_dir, host, options.user, pw->pw_name);
1446 			if (strcmp(cp, p) != 0)
1447 				debug3("expanded LocalForward connect path "
1448 				    "'%s' -> '%s'", cp, p);
1449 			free(cp);
1450 		}
1451 	}
1452 
1453 	for (i = 0; i < options.num_remote_forwards; i++) {
1454 		if (options.remote_forwards[i].listen_path != NULL) {
1455 			cp = options.remote_forwards[i].listen_path;
1456 			p = options.remote_forwards[i].listen_path =
1457 			    default_client_percent_expand(cp,
1458 			    pw->pw_dir, host, options.user, pw->pw_name);
1459 			if (strcmp(cp, p) != 0)
1460 				debug3("expanded RemoteForward listen path "
1461 				    "'%s' -> '%s'", cp, p);
1462 			free(cp);
1463 		}
1464 		if (options.remote_forwards[i].connect_path != NULL) {
1465 			cp = options.remote_forwards[i].connect_path;
1466 			p = options.remote_forwards[i].connect_path =
1467 			    default_client_percent_expand(cp,
1468 			    pw->pw_dir, host, options.user, pw->pw_name);
1469 			if (strcmp(cp, p) != 0)
1470 				debug3("expanded RemoteForward connect path "
1471 				    "'%s' -> '%s'", cp, p);
1472 			free(cp);
1473 		}
1474 	}
1475 
1476 	if (config_test) {
1477 		dump_client_config(&options, host);
1478 		exit(0);
1479 	}
1480 
1481 	/* Expand SecurityKeyProvider if it refers to an environment variable */
1482 	if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1483 	    strlen(options.sk_provider) > 1) {
1484 		if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1485 			debug("Authenticator provider %s did not resolve; "
1486 			    "disabling", options.sk_provider);
1487 			free(options.sk_provider);
1488 			options.sk_provider = NULL;
1489 		} else {
1490 			debug2("resolved SecurityKeyProvider %s => %s",
1491 			    options.sk_provider, cp);
1492 			free(options.sk_provider);
1493 			options.sk_provider = xstrdup(cp);
1494 		}
1495 	}
1496 
1497 	if (muxclient_command != 0 && options.control_path == NULL)
1498 		fatal("No ControlPath specified for \"-O\" command");
1499 	if (options.control_path != NULL) {
1500 		int sock;
1501 		if ((sock = muxclient(options.control_path)) >= 0) {
1502 			ssh_packet_set_connection(ssh, sock, sock);
1503 			ssh_packet_set_mux(ssh);
1504 			goto skip_connect;
1505 		}
1506 	}
1507 
1508 	/*
1509 	 * If hostname canonicalisation was not enabled, then we may not
1510 	 * have yet resolved the hostname. Do so now.
1511 	 */
1512 	if (addrs == NULL && options.proxy_command == NULL) {
1513 		debug2("resolving \"%s\" port %d", host, options.port);
1514 		if ((addrs = resolve_host(host, options.port, 1,
1515 		    cname, sizeof(cname))) == NULL)
1516 			cleanup_exit(255); /* resolve_host logs the error */
1517 	}
1518 
1519 	timeout_ms = options.connection_timeout * 1000;
1520 
1521 	/* Open a connection to the remote host. */
1522 	if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port,
1523 	    options.address_family, options.connection_attempts,
1524 	    &timeout_ms, options.tcp_keep_alive) != 0)
1525  		exit(255);
1526 
1527 	if (addrs != NULL)
1528 		freeaddrinfo(addrs);
1529 
1530 	ssh_packet_set_timeout(ssh, options.server_alive_interval,
1531 	    options.server_alive_count_max);
1532 
1533 	if (timeout_ms > 0)
1534 		debug3("timeout: %d ms remain after connect", timeout_ms);
1535 
1536 	/*
1537 	 * If we successfully made the connection and we have hostbased auth
1538 	 * enabled, load the public keys so we can later use the ssh-keysign
1539 	 * helper to sign challenges.
1540 	 */
1541 	sensitive_data.nkeys = 0;
1542 	sensitive_data.keys = NULL;
1543 	if (options.hostbased_authentication) {
1544 		sensitive_data.nkeys = 10;
1545 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1546 		    sizeof(struct sshkey));
1547 
1548 		/* XXX check errors? */
1549 #define L_PUBKEY(p,o) do { \
1550 	if ((o) >= sensitive_data.nkeys) \
1551 		fatal("%s pubkey out of array bounds", __func__); \
1552 	check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1553 	    p, "pubkey"); \
1554 } while (0)
1555 #define L_CERT(p,o) do { \
1556 	if ((o) >= sensitive_data.nkeys) \
1557 		fatal("%s cert out of array bounds", __func__); \
1558 	check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
1559 } while (0)
1560 
1561 		if (options.hostbased_authentication == 1) {
1562 			L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1563 			L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1564 			L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1565 			L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1566 			L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1567 			L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1568 			L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1569 			L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1570 			L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1571 			L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1572 		}
1573 	}
1574 
1575 	/* Create ~/.ssh * directory if it doesn't already exist. */
1576 	if (config == NULL) {
1577 		r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1578 		    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1579 		if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) == -1) {
1580 #ifdef WITH_SELINUX
1581 			ssh_selinux_setfscreatecon(buf);
1582 #endif
1583 			if (mkdir(buf, 0700) < 0)
1584 				error("Could not create directory '%.200s'.",
1585 				    buf);
1586 #ifdef WITH_SELINUX
1587 			ssh_selinux_setfscreatecon(NULL);
1588 #endif
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 slave 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 slave.
2090 	 * NB. we must save copies of the flags that we override for
2091 	 * the backgrounding, since we defer attachment of the slave 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