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