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