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