xref: /openssh-portable/ssh.c (revision 74344c3c)
1 /* $OpenBSD: ssh.c,v 1.530 2020/06/26 05:02:03 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 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, *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 	/* load options.identity_files */
1576 	load_public_identity_files(pw);
1577 
1578 	/* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1579 	if (options.identity_agent &&
1580 	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1581 		if (strcmp(options.identity_agent, "none") == 0) {
1582 			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1583 		} else {
1584 			cp = options.identity_agent;
1585 			/* legacy (limited) format */
1586 			if (cp[0] == '$' && cp[1] != '{') {
1587 				if (!valid_env_name(cp + 1)) {
1588 					fatal("Invalid IdentityAgent "
1589 					    "environment variable name %s", cp);
1590 				}
1591 				if ((p = getenv(cp + 1)) == NULL)
1592 					unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1593 				else
1594 					setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1595 			} else {
1596 				/* identity_agent specifies a path directly */
1597 				setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1598 			}
1599 		}
1600 	}
1601 
1602 	if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1603 		cp = options.forward_agent_sock_path;
1604 		if (cp[0] == '$') {
1605 			if (!valid_env_name(cp + 1)) {
1606 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1607 			}
1608 			if ((p = getenv(cp + 1)) != NULL)
1609 				forward_agent_sock_path = p;
1610 			else
1611 				options.forward_agent = 0;
1612 			free(cp);
1613 		} else {
1614 			forward_agent_sock_path = cp;
1615 		}
1616 	}
1617 
1618 	/* Expand ~ in known host file names. */
1619 	tilde_expand_paths(options.system_hostfiles,
1620 	    options.num_system_hostfiles);
1621 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1622 
1623 	ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1624 	ssh_signal(SIGCHLD, main_sigchld_handler);
1625 
1626 	/* Log into the remote system.  Never returns if the login fails. */
1627 	ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1628 	    options.port, pw, timeout_ms);
1629 
1630 	if (ssh_packet_connection_is_on_socket(ssh)) {
1631 		verbose("Authenticated to %s ([%s]:%d).", host,
1632 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1633 	} else {
1634 		verbose("Authenticated to %s (via proxy).", host);
1635 	}
1636 
1637 	/* We no longer need the private host keys.  Clear them now. */
1638 	if (sensitive_data.nkeys != 0) {
1639 		for (i = 0; i < sensitive_data.nkeys; i++) {
1640 			if (sensitive_data.keys[i] != NULL) {
1641 				/* Destroys contents safely */
1642 				debug3("clear hostkey %d", i);
1643 				sshkey_free(sensitive_data.keys[i]);
1644 				sensitive_data.keys[i] = NULL;
1645 			}
1646 		}
1647 		free(sensitive_data.keys);
1648 	}
1649 	for (i = 0; i < options.num_identity_files; i++) {
1650 		free(options.identity_files[i]);
1651 		options.identity_files[i] = NULL;
1652 		if (options.identity_keys[i]) {
1653 			sshkey_free(options.identity_keys[i]);
1654 			options.identity_keys[i] = NULL;
1655 		}
1656 	}
1657 	for (i = 0; i < options.num_certificate_files; i++) {
1658 		free(options.certificate_files[i]);
1659 		options.certificate_files[i] = NULL;
1660 	}
1661 
1662  skip_connect:
1663 	exit_status = ssh_session2(ssh, pw);
1664 	ssh_packet_close(ssh);
1665 
1666 	if (options.control_path != NULL && muxserver_sock != -1)
1667 		unlink(options.control_path);
1668 
1669 	/* Kill ProxyCommand if it is running. */
1670 	ssh_kill_proxy_command();
1671 
1672 	return exit_status;
1673 }
1674 
1675 static void
1676 control_persist_detach(void)
1677 {
1678 	pid_t pid;
1679 	int devnull, keep_stderr;
1680 
1681 	debug("%s: backgrounding master process", __func__);
1682 
1683 	/*
1684 	 * master (current process) into the background, and make the
1685 	 * foreground process a client of the backgrounded master.
1686 	 */
1687 	switch ((pid = fork())) {
1688 	case -1:
1689 		fatal("%s: fork: %s", __func__, strerror(errno));
1690 	case 0:
1691 		/* Child: master process continues mainloop */
1692 		break;
1693 	default:
1694 		/* Parent: set up mux slave to connect to backgrounded master */
1695 		debug2("%s: background process is %ld", __func__, (long)pid);
1696 		stdin_null_flag = ostdin_null_flag;
1697 		options.request_tty = orequest_tty;
1698 		tty_flag = otty_flag;
1699 		close(muxserver_sock);
1700 		muxserver_sock = -1;
1701 		options.control_master = SSHCTL_MASTER_NO;
1702 		muxclient(options.control_path);
1703 		/* muxclient() doesn't return on success. */
1704 		fatal("Failed to connect to new control master");
1705 	}
1706 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1707 		error("%s: open(\"/dev/null\"): %s", __func__,
1708 		    strerror(errno));
1709 	} else {
1710 		keep_stderr = log_is_on_stderr() && debug_flag;
1711 		if (dup2(devnull, STDIN_FILENO) == -1 ||
1712 		    dup2(devnull, STDOUT_FILENO) == -1 ||
1713 		    (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1714 			error("%s: dup2: %s", __func__, strerror(errno));
1715 		if (devnull > STDERR_FILENO)
1716 			close(devnull);
1717 	}
1718 	daemon(1, 1);
1719 	setproctitle("%s [mux]", options.control_path);
1720 }
1721 
1722 /* Do fork() after authentication. Used by "ssh -f" */
1723 static void
1724 fork_postauth(void)
1725 {
1726 	if (need_controlpersist_detach)
1727 		control_persist_detach();
1728 	debug("forking to background");
1729 	fork_after_authentication_flag = 0;
1730 	if (daemon(1, 1) == -1)
1731 		fatal("daemon() failed: %.200s", strerror(errno));
1732 }
1733 
1734 static void
1735 forwarding_success(void)
1736 {
1737 	if (forward_confirms_pending == -1)
1738 		return;
1739 	if (--forward_confirms_pending == 0) {
1740 		debug("%s: all expected forwarding replies received", __func__);
1741 		if (fork_after_authentication_flag)
1742 			fork_postauth();
1743 	} else {
1744 		debug2("%s: %d expected forwarding replies remaining",
1745 		    __func__, forward_confirms_pending);
1746 	}
1747 }
1748 
1749 /* Callback for remote forward global requests */
1750 static void
1751 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1752 {
1753 	struct Forward *rfwd = (struct Forward *)ctxt;
1754 	u_int port;
1755 	int r;
1756 
1757 	/* XXX verbose() on failure? */
1758 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1759 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1760 	    rfwd->listen_path ? rfwd->listen_path :
1761 	    rfwd->listen_host ? rfwd->listen_host : "",
1762 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1763 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1764 	    rfwd->connect_host, rfwd->connect_port);
1765 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1766 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1767 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1768 				fatal("%s: %s", __func__, ssh_err(r));
1769 			if (port > 65535) {
1770 				error("Invalid allocated port %u for remote "
1771 				    "forward to %s:%d", port,
1772 				    rfwd->connect_host, rfwd->connect_port);
1773 				/* Ensure failure processing runs below */
1774 				type = SSH2_MSG_REQUEST_FAILURE;
1775 				channel_update_permission(ssh,
1776 				    rfwd->handle, -1);
1777 			} else {
1778 				rfwd->allocated_port = (int)port;
1779 				logit("Allocated port %u for remote "
1780 				    "forward to %s:%d",
1781 				    rfwd->allocated_port, rfwd->connect_host,
1782 				    rfwd->connect_port);
1783 				channel_update_permission(ssh,
1784 				    rfwd->handle, rfwd->allocated_port);
1785 			}
1786 		} else {
1787 			channel_update_permission(ssh, rfwd->handle, -1);
1788 		}
1789 	}
1790 
1791 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1792 		if (options.exit_on_forward_failure) {
1793 			if (rfwd->listen_path != NULL)
1794 				fatal("Error: remote port forwarding failed "
1795 				    "for listen path %s", rfwd->listen_path);
1796 			else
1797 				fatal("Error: remote port forwarding failed "
1798 				    "for listen port %d", rfwd->listen_port);
1799 		} else {
1800 			if (rfwd->listen_path != NULL)
1801 				logit("Warning: remote port forwarding failed "
1802 				    "for listen path %s", rfwd->listen_path);
1803 			else
1804 				logit("Warning: remote port forwarding failed "
1805 				    "for listen port %d", rfwd->listen_port);
1806 		}
1807 	}
1808 	forwarding_success();
1809 }
1810 
1811 static void
1812 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1813 {
1814 	debug("stdio forwarding: done");
1815 	cleanup_exit(0);
1816 }
1817 
1818 static void
1819 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1820 {
1821 	if (!success)
1822 		fatal("stdio forwarding failed");
1823 }
1824 
1825 static void
1826 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1827 {
1828 	if (!success) {
1829 		error("Tunnel forwarding failed");
1830 		if (options.exit_on_forward_failure)
1831 			cleanup_exit(255);
1832 	}
1833 
1834 	debug("%s: tunnel forward established, id=%d", __func__, id);
1835 	forwarding_success();
1836 }
1837 
1838 static void
1839 ssh_init_stdio_forwarding(struct ssh *ssh)
1840 {
1841 	Channel *c;
1842 	int in, out;
1843 
1844 	if (options.stdio_forward_host == NULL)
1845 		return;
1846 
1847 	debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1848 	    options.stdio_forward_port);
1849 
1850 	if ((in = dup(STDIN_FILENO)) == -1 ||
1851 	    (out = dup(STDOUT_FILENO)) == -1)
1852 		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1853 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1854 	    options.stdio_forward_port, in, out)) == NULL)
1855 		fatal("%s: channel_connect_stdio_fwd failed", __func__);
1856 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1857 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1858 }
1859 
1860 static void
1861 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1862 {
1863 	int success = 0;
1864 	int i;
1865 
1866 	if (options.exit_on_forward_failure)
1867 		forward_confirms_pending = 0; /* track pending requests */
1868 	/* Initiate local TCP/IP port forwardings. */
1869 	for (i = 0; i < options.num_local_forwards; i++) {
1870 		debug("Local connections to %.200s:%d forwarded to remote "
1871 		    "address %.200s:%d",
1872 		    (options.local_forwards[i].listen_path != NULL) ?
1873 		    options.local_forwards[i].listen_path :
1874 		    (options.local_forwards[i].listen_host == NULL) ?
1875 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1876 		    options.local_forwards[i].listen_host,
1877 		    options.local_forwards[i].listen_port,
1878 		    (options.local_forwards[i].connect_path != NULL) ?
1879 		    options.local_forwards[i].connect_path :
1880 		    options.local_forwards[i].connect_host,
1881 		    options.local_forwards[i].connect_port);
1882 		success += channel_setup_local_fwd_listener(ssh,
1883 		    &options.local_forwards[i], &options.fwd_opts);
1884 	}
1885 	if (i > 0 && success != i && options.exit_on_forward_failure)
1886 		fatal("Could not request local forwarding.");
1887 	if (i > 0 && success == 0)
1888 		error("Could not request local forwarding.");
1889 
1890 	/* Initiate remote TCP/IP port forwardings. */
1891 	for (i = 0; i < options.num_remote_forwards; i++) {
1892 		debug("Remote connections from %.200s:%d forwarded to "
1893 		    "local address %.200s:%d",
1894 		    (options.remote_forwards[i].listen_path != NULL) ?
1895 		    options.remote_forwards[i].listen_path :
1896 		    (options.remote_forwards[i].listen_host == NULL) ?
1897 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1898 		    options.remote_forwards[i].listen_port,
1899 		    (options.remote_forwards[i].connect_path != NULL) ?
1900 		    options.remote_forwards[i].connect_path :
1901 		    options.remote_forwards[i].connect_host,
1902 		    options.remote_forwards[i].connect_port);
1903 		if ((options.remote_forwards[i].handle =
1904 		    channel_request_remote_forwarding(ssh,
1905 		    &options.remote_forwards[i])) >= 0) {
1906 			client_register_global_confirm(
1907 			    ssh_confirm_remote_forward,
1908 			    &options.remote_forwards[i]);
1909 			forward_confirms_pending++;
1910 		} else if (options.exit_on_forward_failure)
1911 			fatal("Could not request remote forwarding.");
1912 		else
1913 			logit("Warning: Could not request remote forwarding.");
1914 	}
1915 
1916 	/* Initiate tunnel forwarding. */
1917 	if (options.tun_open != SSH_TUNMODE_NO) {
1918 		if ((*ifname = client_request_tun_fwd(ssh,
1919 		    options.tun_open, options.tun_local,
1920 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
1921 			forward_confirms_pending++;
1922 		else if (options.exit_on_forward_failure)
1923 			fatal("Could not request tunnel forwarding.");
1924 		else
1925 			error("Could not request tunnel forwarding.");
1926 	}
1927 	if (forward_confirms_pending > 0) {
1928 		debug("%s: expecting replies for %d forwards", __func__,
1929 		    forward_confirms_pending);
1930 	}
1931 }
1932 
1933 static void
1934 check_agent_present(void)
1935 {
1936 	int r;
1937 
1938 	if (options.forward_agent) {
1939 		/* Clear agent forwarding if we don't have an agent. */
1940 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1941 			options.forward_agent = 0;
1942 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
1943 				debug("ssh_get_authentication_socket: %s",
1944 				    ssh_err(r));
1945 		}
1946 	}
1947 }
1948 
1949 static void
1950 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1951 {
1952 	extern char **environ;
1953 	const char *display;
1954 	int r, interactive = tty_flag;
1955 	char *proto = NULL, *data = NULL;
1956 
1957 	if (!success)
1958 		return; /* No need for error message, channels code sens one */
1959 
1960 	display = getenv("DISPLAY");
1961 	if (display == NULL && options.forward_x11)
1962 		debug("X11 forwarding requested but DISPLAY not set");
1963 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
1964 	    options.xauth_location, options.forward_x11_trusted,
1965 	    options.forward_x11_timeout, &proto, &data) == 0) {
1966 		/* Request forwarding with authentication spoofing. */
1967 		debug("Requesting X11 forwarding with authentication "
1968 		    "spoofing.");
1969 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1970 		    data, 1);
1971 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1972 		/* XXX exit_on_forward_failure */
1973 		interactive = 1;
1974 	}
1975 
1976 	check_agent_present();
1977 	if (options.forward_agent) {
1978 		debug("Requesting authentication agent forwarding.");
1979 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1980 		if ((r = sshpkt_send(ssh)) != 0)
1981 			fatal("%s: %s", __func__, ssh_err(r));
1982 	}
1983 
1984 	/* Tell the packet module whether this is an interactive session. */
1985 	ssh_packet_set_interactive(ssh, interactive,
1986 	    options.ip_qos_interactive, options.ip_qos_bulk);
1987 
1988 	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
1989 	    NULL, fileno(stdin), command, environ);
1990 }
1991 
1992 /* open new channel for a session */
1993 static int
1994 ssh_session2_open(struct ssh *ssh)
1995 {
1996 	Channel *c;
1997 	int window, packetmax, in, out, err;
1998 
1999 	if (stdin_null_flag) {
2000 		in = open(_PATH_DEVNULL, O_RDONLY);
2001 	} else {
2002 		in = dup(STDIN_FILENO);
2003 	}
2004 	out = dup(STDOUT_FILENO);
2005 	err = dup(STDERR_FILENO);
2006 
2007 	if (in == -1 || out == -1 || err == -1)
2008 		fatal("dup() in/out/err failed");
2009 
2010 	/* enable nonblocking unless tty */
2011 	if (!isatty(in))
2012 		set_nonblock(in);
2013 	if (!isatty(out))
2014 		set_nonblock(out);
2015 	if (!isatty(err))
2016 		set_nonblock(err);
2017 
2018 	window = CHAN_SES_WINDOW_DEFAULT;
2019 	packetmax = CHAN_SES_PACKET_DEFAULT;
2020 	if (tty_flag) {
2021 		window >>= 1;
2022 		packetmax >>= 1;
2023 	}
2024 	c = channel_new(ssh,
2025 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2026 	    window, packetmax, CHAN_EXTENDED_WRITE,
2027 	    "client-session", /*nonblock*/0);
2028 
2029 	debug3("%s: channel_new: %d", __func__, c->self);
2030 
2031 	channel_send_open(ssh, c->self);
2032 	if (!no_shell_flag)
2033 		channel_register_open_confirm(ssh, c->self,
2034 		    ssh_session2_setup, NULL);
2035 
2036 	return c->self;
2037 }
2038 
2039 static int
2040 ssh_session2(struct ssh *ssh, struct passwd *pw)
2041 {
2042 	int r, devnull, id = -1;
2043 	char *cp, *tun_fwd_ifname = NULL;
2044 
2045 	/* XXX should be pre-session */
2046 	if (!options.control_persist)
2047 		ssh_init_stdio_forwarding(ssh);
2048 
2049 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2050 
2051 	if (options.local_command != NULL) {
2052 		debug3("expanding LocalCommand: %s", options.local_command);
2053 		cp = options.local_command;
2054 		options.local_command = percent_expand(cp,
2055 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS,
2056 		    "d", pw->pw_dir,
2057 		    "h", host,
2058 		    "r", options.user,
2059 		    "u", pw->pw_name,
2060 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2061 		    (char *)NULL);
2062 		debug3("expanded LocalCommand: %s", options.local_command);
2063 		free(cp);
2064 	}
2065 
2066 	/* Start listening for multiplex clients */
2067 	if (!ssh_packet_get_mux(ssh))
2068 		muxserver_listen(ssh);
2069 
2070 	/*
2071 	 * If we are in control persist mode and have a working mux listen
2072 	 * socket, then prepare to background ourselves and have a foreground
2073 	 * client attach as a control slave.
2074 	 * NB. we must save copies of the flags that we override for
2075 	 * the backgrounding, since we defer attachment of the slave until
2076 	 * after the connection is fully established (in particular,
2077 	 * async rfwd replies have been received for ExitOnForwardFailure).
2078 	 */
2079 	if (options.control_persist && muxserver_sock != -1) {
2080 		ostdin_null_flag = stdin_null_flag;
2081 		ono_shell_flag = no_shell_flag;
2082 		orequest_tty = options.request_tty;
2083 		otty_flag = tty_flag;
2084 		stdin_null_flag = 1;
2085 		no_shell_flag = 1;
2086 		tty_flag = 0;
2087 		if (!fork_after_authentication_flag)
2088 			need_controlpersist_detach = 1;
2089 		fork_after_authentication_flag = 1;
2090 	}
2091 	/*
2092 	 * ControlPersist mux listen socket setup failed, attempt the
2093 	 * stdio forward setup that we skipped earlier.
2094 	 */
2095 	if (options.control_persist && muxserver_sock == -1)
2096 		ssh_init_stdio_forwarding(ssh);
2097 
2098 	if (!no_shell_flag)
2099 		id = ssh_session2_open(ssh);
2100 	else {
2101 		ssh_packet_set_interactive(ssh,
2102 		    options.control_master == SSHCTL_MASTER_NO,
2103 		    options.ip_qos_interactive, options.ip_qos_bulk);
2104 	}
2105 
2106 	/* If we don't expect to open a new session, then disallow it */
2107 	if (options.control_master == SSHCTL_MASTER_NO &&
2108 	    (datafellows & SSH_NEW_OPENSSH)) {
2109 		debug("Requesting no-more-sessions@openssh.com");
2110 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2111 		    (r = sshpkt_put_cstring(ssh,
2112 		    "no-more-sessions@openssh.com")) != 0 ||
2113 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2114 		    (r = sshpkt_send(ssh)) != 0)
2115 			fatal("%s: %s", __func__, ssh_err(r));
2116 	}
2117 
2118 	/* Execute a local command */
2119 	if (options.local_command != NULL &&
2120 	    options.permit_local_command)
2121 		ssh_local_cmd(options.local_command);
2122 
2123 	/*
2124 	 * stdout is now owned by the session channel; clobber it here
2125 	 * so future channel closes are propagated to the local fd.
2126 	 * NB. this can only happen after LocalCommand has completed,
2127 	 * as it may want to write to stdout.
2128 	 */
2129 	if (!need_controlpersist_detach) {
2130 		if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1)
2131 			error("%s: open %s: %s", __func__,
2132 			    _PATH_DEVNULL, strerror(errno));
2133 		if (dup2(devnull, STDOUT_FILENO) == -1)
2134 			fatal("%s: dup2() stdout failed", __func__);
2135 		if (devnull > STDERR_FILENO)
2136 			close(devnull);
2137 	}
2138 
2139 	/*
2140 	 * If requested and we are not interested in replies to remote
2141 	 * forwarding requests, then let ssh continue in the background.
2142 	 */
2143 	if (fork_after_authentication_flag) {
2144 		if (options.exit_on_forward_failure &&
2145 		    options.num_remote_forwards > 0) {
2146 			debug("deferring postauth fork until remote forward "
2147 			    "confirmation received");
2148 		} else
2149 			fork_postauth();
2150 	}
2151 
2152 	return client_loop(ssh, tty_flag, tty_flag ?
2153 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2154 }
2155 
2156 /* Loads all IdentityFile and CertificateFile keys */
2157 static void
2158 load_public_identity_files(struct passwd *pw)
2159 {
2160 	char *filename, *cp;
2161 	struct sshkey *public;
2162 	int i;
2163 	u_int n_ids, n_certs;
2164 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2165 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2166 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2167 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2168 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2169 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2170 #ifdef ENABLE_PKCS11
2171 	struct sshkey **keys = NULL;
2172 	char **comments = NULL;
2173 	int nkeys;
2174 #endif /* PKCS11 */
2175 
2176 	n_ids = n_certs = 0;
2177 	memset(identity_files, 0, sizeof(identity_files));
2178 	memset(identity_keys, 0, sizeof(identity_keys));
2179 	memset(identity_file_userprovided, 0,
2180 	    sizeof(identity_file_userprovided));
2181 	memset(certificate_files, 0, sizeof(certificate_files));
2182 	memset(certificates, 0, sizeof(certificates));
2183 	memset(certificate_file_userprovided, 0,
2184 	    sizeof(certificate_file_userprovided));
2185 
2186 #ifdef ENABLE_PKCS11
2187 	if (options.pkcs11_provider != NULL &&
2188 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2189 	    (pkcs11_init(!options.batch_mode) == 0) &&
2190 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2191 	    &keys, &comments)) > 0) {
2192 		for (i = 0; i < nkeys; i++) {
2193 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2194 				sshkey_free(keys[i]);
2195 				free(comments[i]);
2196 				continue;
2197 			}
2198 			identity_keys[n_ids] = keys[i];
2199 			identity_files[n_ids] = comments[i]; /* transferred */
2200 			n_ids++;
2201 		}
2202 		free(keys);
2203 		free(comments);
2204 	}
2205 #endif /* ENABLE_PKCS11 */
2206 	for (i = 0; i < options.num_identity_files; i++) {
2207 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2208 		    strcasecmp(options.identity_files[i], "none") == 0) {
2209 			free(options.identity_files[i]);
2210 			options.identity_files[i] = NULL;
2211 			continue;
2212 		}
2213 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2214 		filename = default_client_percent_dollar_expand(cp,
2215 		    pw->pw_dir, host, options.user, pw->pw_name);
2216 		free(cp);
2217 		check_load(sshkey_load_public(filename, &public, NULL),
2218 		    filename, "pubkey");
2219 		debug("identity file %s type %d", filename,
2220 		    public ? public->type : -1);
2221 		free(options.identity_files[i]);
2222 		identity_files[n_ids] = filename;
2223 		identity_keys[n_ids] = public;
2224 		identity_file_userprovided[n_ids] =
2225 		    options.identity_file_userprovided[i];
2226 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2227 			continue;
2228 
2229 		/*
2230 		 * If no certificates have been explicitly listed then try
2231 		 * to add the default certificate variant too.
2232 		 */
2233 		if (options.num_certificate_files != 0)
2234 			continue;
2235 		xasprintf(&cp, "%s-cert", filename);
2236 		check_load(sshkey_load_public(cp, &public, NULL),
2237 		    filename, "pubkey");
2238 		debug("identity file %s type %d", cp,
2239 		    public ? public->type : -1);
2240 		if (public == NULL) {
2241 			free(cp);
2242 			continue;
2243 		}
2244 		if (!sshkey_is_cert(public)) {
2245 			debug("%s: key %s type %s is not a certificate",
2246 			    __func__, cp, sshkey_type(public));
2247 			sshkey_free(public);
2248 			free(cp);
2249 			continue;
2250 		}
2251 		/* NB. leave filename pointing to private key */
2252 		identity_files[n_ids] = xstrdup(filename);
2253 		identity_keys[n_ids] = public;
2254 		identity_file_userprovided[n_ids] =
2255 		    options.identity_file_userprovided[i];
2256 		n_ids++;
2257 	}
2258 
2259 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2260 		fatal("%s: too many certificates", __func__);
2261 	for (i = 0; i < options.num_certificate_files; i++) {
2262 		cp = tilde_expand_filename(options.certificate_files[i],
2263 		    getuid());
2264 		filename = default_client_percent_dollar_expand(cp,
2265 		    pw->pw_dir, host, options.user, pw->pw_name);
2266 		free(cp);
2267 
2268 		check_load(sshkey_load_public(filename, &public, NULL),
2269 		    filename, "certificate");
2270 		debug("certificate file %s type %d", filename,
2271 		    public ? public->type : -1);
2272 		free(options.certificate_files[i]);
2273 		options.certificate_files[i] = NULL;
2274 		if (public == NULL) {
2275 			free(filename);
2276 			continue;
2277 		}
2278 		if (!sshkey_is_cert(public)) {
2279 			debug("%s: key %s type %s is not a certificate",
2280 			    __func__, filename, sshkey_type(public));
2281 			sshkey_free(public);
2282 			free(filename);
2283 			continue;
2284 		}
2285 		certificate_files[n_certs] = filename;
2286 		certificates[n_certs] = public;
2287 		certificate_file_userprovided[n_certs] =
2288 		    options.certificate_file_userprovided[i];
2289 		++n_certs;
2290 	}
2291 
2292 	options.num_identity_files = n_ids;
2293 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2294 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2295 	memcpy(options.identity_file_userprovided,
2296 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2297 
2298 	options.num_certificate_files = n_certs;
2299 	memcpy(options.certificate_files,
2300 	    certificate_files, sizeof(certificate_files));
2301 	memcpy(options.certificates, certificates, sizeof(certificates));
2302 	memcpy(options.certificate_file_userprovided,
2303 	    certificate_file_userprovided,
2304 	    sizeof(certificate_file_userprovided));
2305 }
2306 
2307 static void
2308 main_sigchld_handler(int sig)
2309 {
2310 	int save_errno = errno;
2311 	pid_t pid;
2312 	int status;
2313 
2314 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2315 	    (pid == -1 && errno == EINTR))
2316 		;
2317 	errno = save_errno;
2318 }
2319