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