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