xref: /openssh-portable/ssh.c (revision 4ca6a1fa)
1 /* $OpenBSD: ssh.c,v 1.549 2021/01/27 09:26:54 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 
652 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
653 	sanitise_stdfd();
654 
655 	__progname = ssh_get_progname(av[0]);
656 
657 #ifndef HAVE_SETPROCTITLE
658 	/* Prepare for later setproctitle emulation */
659 	/* Save argv so it isn't clobbered by setproctitle() emulation */
660 	saved_av = xcalloc(ac + 1, sizeof(*saved_av));
661 	for (i = 0; i < ac; i++)
662 		saved_av[i] = xstrdup(av[i]);
663 	saved_av[i] = NULL;
664 	compat_init_setproctitle(ac, av);
665 	av = saved_av;
666 #endif
667 
668 	seed_rng();
669 
670 	/*
671 	 * Discard other fds that are hanging around. These can cause problem
672 	 * with backgrounded ssh processes started by ControlPersist.
673 	 */
674 	closefrom(STDERR_FILENO + 1);
675 
676 	/* Get user data. */
677 	pw = getpwuid(getuid());
678 	if (!pw) {
679 		logit("No user exists for uid %lu", (u_long)getuid());
680 		exit(255);
681 	}
682 	/* Take a copy of the returned structure. */
683 	pw = pwcopy(pw);
684 
685 	/*
686 	 * Set our umask to something reasonable, as some files are created
687 	 * with the default umask.  This will make them world-readable but
688 	 * writable only by the owner, which is ok for all files for which we
689 	 * don't set the modes explicitly.
690 	 */
691 	umask(022);
692 
693 	msetlocale();
694 
695 	/*
696 	 * Initialize option structure to indicate that no values have been
697 	 * set.
698 	 */
699 	initialize_options(&options);
700 
701 	/*
702 	 * Prepare main ssh transport/connection structures
703 	 */
704 	if ((ssh = ssh_alloc_session_state()) == NULL)
705 		fatal("Couldn't allocate session state");
706 	channel_init_channels(ssh);
707 
708 	/* Parse command-line arguments. */
709 	host = NULL;
710 	use_syslog = 0;
711 	logfile = NULL;
712 	argv0 = av[0];
713 
714  again:
715 	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
716 	    "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
717 		switch (opt) {
718 		case '1':
719 			fatal("SSH protocol v.1 is no longer supported");
720 			break;
721 		case '2':
722 			/* Ignored */
723 			break;
724 		case '4':
725 			options.address_family = AF_INET;
726 			break;
727 		case '6':
728 			options.address_family = AF_INET6;
729 			break;
730 		case 'n':
731 			stdin_null_flag = 1;
732 			break;
733 		case 'f':
734 			fork_after_authentication_flag = 1;
735 			stdin_null_flag = 1;
736 			break;
737 		case 'x':
738 			options.forward_x11 = 0;
739 			break;
740 		case 'X':
741 			options.forward_x11 = 1;
742 			break;
743 		case 'y':
744 			use_syslog = 1;
745 			break;
746 		case 'E':
747 			logfile = optarg;
748 			break;
749 		case 'G':
750 			config_test = 1;
751 			break;
752 		case 'Y':
753 			options.forward_x11 = 1;
754 			options.forward_x11_trusted = 1;
755 			break;
756 		case 'g':
757 			options.fwd_opts.gateway_ports = 1;
758 			break;
759 		case 'O':
760 			if (options.stdio_forward_host != NULL)
761 				fatal("Cannot specify multiplexing "
762 				    "command with -W");
763 			else if (muxclient_command != 0)
764 				fatal("Multiplexing command already specified");
765 			if (strcmp(optarg, "check") == 0)
766 				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
767 			else if (strcmp(optarg, "forward") == 0)
768 				muxclient_command = SSHMUX_COMMAND_FORWARD;
769 			else if (strcmp(optarg, "exit") == 0)
770 				muxclient_command = SSHMUX_COMMAND_TERMINATE;
771 			else if (strcmp(optarg, "stop") == 0)
772 				muxclient_command = SSHMUX_COMMAND_STOP;
773 			else if (strcmp(optarg, "cancel") == 0)
774 				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
775 			else if (strcmp(optarg, "proxy") == 0)
776 				muxclient_command = SSHMUX_COMMAND_PROXY;
777 			else
778 				fatal("Invalid multiplex command.");
779 			break;
780 		case 'P':	/* deprecated */
781 			break;
782 		case 'Q':
783 			cp = NULL;
784 			if (strcmp(optarg, "cipher") == 0 ||
785 			    strcasecmp(optarg, "Ciphers") == 0)
786 				cp = cipher_alg_list('\n', 0);
787 			else if (strcmp(optarg, "cipher-auth") == 0)
788 				cp = cipher_alg_list('\n', 1);
789 			else if (strcmp(optarg, "mac") == 0 ||
790 			    strcasecmp(optarg, "MACs") == 0)
791 				cp = mac_alg_list('\n');
792 			else if (strcmp(optarg, "kex") == 0 ||
793 			    strcasecmp(optarg, "KexAlgorithms") == 0)
794 				cp = kex_alg_list('\n');
795 			else if (strcmp(optarg, "key") == 0)
796 				cp = sshkey_alg_list(0, 0, 0, '\n');
797 			else if (strcmp(optarg, "key-cert") == 0)
798 				cp = sshkey_alg_list(1, 0, 0, '\n');
799 			else if (strcmp(optarg, "key-plain") == 0)
800 				cp = sshkey_alg_list(0, 1, 0, '\n');
801 			else if (strcmp(optarg, "key-sig") == 0 ||
802 			    strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
803 			    strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
804 			    strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
805 			    strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
806 			    strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
807 			    strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
808 				cp = sshkey_alg_list(0, 0, 1, '\n');
809 			else if (strcmp(optarg, "sig") == 0)
810 				cp = sshkey_alg_list(0, 1, 1, '\n');
811 			else if (strcmp(optarg, "protocol-version") == 0)
812 				cp = xstrdup("2");
813 			else if (strcmp(optarg, "compression") == 0) {
814 				cp = xstrdup(compression_alg_list(0));
815 				len = strlen(cp);
816 				for (n = 0; n < len; n++)
817 					if (cp[n] == ',')
818 						cp[n] = '\n';
819 			} else if (strcmp(optarg, "help") == 0) {
820 				cp = xstrdup(
821 				    "cipher\ncipher-auth\ncompression\nkex\n"
822 				    "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
823 				    "protocol-version\nsig");
824 			}
825 			if (cp == NULL)
826 				fatal("Unsupported query \"%s\"", optarg);
827 			printf("%s\n", cp);
828 			free(cp);
829 			exit(0);
830 			break;
831 		case 'a':
832 			options.forward_agent = 0;
833 			break;
834 		case 'A':
835 			options.forward_agent = 1;
836 			break;
837 		case 'k':
838 			options.gss_deleg_creds = 0;
839 			break;
840 		case 'K':
841 			options.gss_authentication = 1;
842 			options.gss_deleg_creds = 1;
843 			break;
844 		case 'i':
845 			p = tilde_expand_filename(optarg, getuid());
846 			if (stat(p, &st) == -1)
847 				fprintf(stderr, "Warning: Identity file %s "
848 				    "not accessible: %s.\n", p,
849 				    strerror(errno));
850 			else
851 				add_identity_file(&options, NULL, p, 1);
852 			free(p);
853 			break;
854 		case 'I':
855 #ifdef ENABLE_PKCS11
856 			free(options.pkcs11_provider);
857 			options.pkcs11_provider = xstrdup(optarg);
858 #else
859 			fprintf(stderr, "no support for PKCS#11.\n");
860 #endif
861 			break;
862 		case 'J':
863 			if (options.jump_host != NULL) {
864 				fatal("Only a single -J option is permitted "
865 				    "(use commas to separate multiple "
866 				    "jump hops)");
867 			}
868 			if (options.proxy_command != NULL)
869 				fatal("Cannot specify -J with ProxyCommand");
870 			if (parse_jump(optarg, &options, 1) == -1)
871 				fatal("Invalid -J argument");
872 			options.proxy_command = xstrdup("none");
873 			break;
874 		case 't':
875 			if (options.request_tty == REQUEST_TTY_YES)
876 				options.request_tty = REQUEST_TTY_FORCE;
877 			else
878 				options.request_tty = REQUEST_TTY_YES;
879 			break;
880 		case 'v':
881 			if (debug_flag == 0) {
882 				debug_flag = 1;
883 				options.log_level = SYSLOG_LEVEL_DEBUG1;
884 			} else {
885 				if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
886 					debug_flag++;
887 					options.log_level++;
888 				}
889 			}
890 			break;
891 		case 'V':
892 			fprintf(stderr, "%s, %s\n",
893 			    SSH_RELEASE, SSH_OPENSSL_VERSION);
894 			if (opt == 'V')
895 				exit(0);
896 			break;
897 		case 'w':
898 			if (options.tun_open == -1)
899 				options.tun_open = SSH_TUNMODE_DEFAULT;
900 			options.tun_local = a2tun(optarg, &options.tun_remote);
901 			if (options.tun_local == SSH_TUNID_ERR) {
902 				fprintf(stderr,
903 				    "Bad tun device '%s'\n", optarg);
904 				exit(255);
905 			}
906 			break;
907 		case 'W':
908 			if (options.stdio_forward_host != NULL)
909 				fatal("stdio forward already specified");
910 			if (muxclient_command != 0)
911 				fatal("Cannot specify stdio forward with -O");
912 			if (parse_forward(&fwd, optarg, 1, 0)) {
913 				options.stdio_forward_host = fwd.listen_host;
914 				options.stdio_forward_port = fwd.listen_port;
915 				free(fwd.connect_host);
916 			} else {
917 				fprintf(stderr,
918 				    "Bad stdio forwarding specification '%s'\n",
919 				    optarg);
920 				exit(255);
921 			}
922 			options.request_tty = REQUEST_TTY_NO;
923 			no_shell_flag = 1;
924 			break;
925 		case 'q':
926 			options.log_level = SYSLOG_LEVEL_QUIET;
927 			break;
928 		case 'e':
929 			if (optarg[0] == '^' && optarg[2] == 0 &&
930 			    (u_char) optarg[1] >= 64 &&
931 			    (u_char) optarg[1] < 128)
932 				options.escape_char = (u_char) optarg[1] & 31;
933 			else if (strlen(optarg) == 1)
934 				options.escape_char = (u_char) optarg[0];
935 			else if (strcmp(optarg, "none") == 0)
936 				options.escape_char = SSH_ESCAPECHAR_NONE;
937 			else {
938 				fprintf(stderr, "Bad escape character '%s'.\n",
939 				    optarg);
940 				exit(255);
941 			}
942 			break;
943 		case 'c':
944 			if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
945 			    optarg + 1 : optarg)) {
946 				fprintf(stderr, "Unknown cipher type '%s'\n",
947 				    optarg);
948 				exit(255);
949 			}
950 			free(options.ciphers);
951 			options.ciphers = xstrdup(optarg);
952 			break;
953 		case 'm':
954 			if (mac_valid(optarg)) {
955 				free(options.macs);
956 				options.macs = xstrdup(optarg);
957 			} else {
958 				fprintf(stderr, "Unknown mac type '%s'\n",
959 				    optarg);
960 				exit(255);
961 			}
962 			break;
963 		case 'M':
964 			if (options.control_master == SSHCTL_MASTER_YES)
965 				options.control_master = SSHCTL_MASTER_ASK;
966 			else
967 				options.control_master = SSHCTL_MASTER_YES;
968 			break;
969 		case 'p':
970 			if (options.port == -1) {
971 				options.port = a2port(optarg);
972 				if (options.port <= 0) {
973 					fprintf(stderr, "Bad port '%s'\n",
974 					    optarg);
975 					exit(255);
976 				}
977 			}
978 			break;
979 		case 'l':
980 			if (options.user == NULL)
981 				options.user = optarg;
982 			break;
983 
984 		case 'L':
985 			if (parse_forward(&fwd, optarg, 0, 0))
986 				add_local_forward(&options, &fwd);
987 			else {
988 				fprintf(stderr,
989 				    "Bad local forwarding specification '%s'\n",
990 				    optarg);
991 				exit(255);
992 			}
993 			break;
994 
995 		case 'R':
996 			if (parse_forward(&fwd, optarg, 0, 1) ||
997 			    parse_forward(&fwd, optarg, 1, 1)) {
998 				add_remote_forward(&options, &fwd);
999 			} else {
1000 				fprintf(stderr,
1001 				    "Bad remote forwarding specification "
1002 				    "'%s'\n", optarg);
1003 				exit(255);
1004 			}
1005 			break;
1006 
1007 		case 'D':
1008 			if (parse_forward(&fwd, optarg, 1, 0)) {
1009 				add_local_forward(&options, &fwd);
1010 			} else {
1011 				fprintf(stderr,
1012 				    "Bad dynamic forwarding specification "
1013 				    "'%s'\n", optarg);
1014 				exit(255);
1015 			}
1016 			break;
1017 
1018 		case 'C':
1019 #ifdef WITH_ZLIB
1020 			options.compression = 1;
1021 #else
1022 			error("Compression not supported, disabling.");
1023 #endif
1024 			break;
1025 		case 'N':
1026 			no_shell_flag = 1;
1027 			options.request_tty = REQUEST_TTY_NO;
1028 			break;
1029 		case 'T':
1030 			options.request_tty = REQUEST_TTY_NO;
1031 			break;
1032 		case 'o':
1033 			line = xstrdup(optarg);
1034 			if (process_config_line(&options, pw,
1035 			    host ? host : "", host ? host : "", line,
1036 			    "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1037 				exit(255);
1038 			free(line);
1039 			break;
1040 		case 's':
1041 			subsystem_flag = 1;
1042 			break;
1043 		case 'S':
1044 			free(options.control_path);
1045 			options.control_path = xstrdup(optarg);
1046 			break;
1047 		case 'b':
1048 			options.bind_address = optarg;
1049 			break;
1050 		case 'B':
1051 			options.bind_interface = optarg;
1052 			break;
1053 		case 'F':
1054 			config = optarg;
1055 			break;
1056 		default:
1057 			usage();
1058 		}
1059 	}
1060 
1061 	if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1062 		opt_terminated = 1;
1063 
1064 	ac -= optind;
1065 	av += optind;
1066 
1067 	if (ac > 0 && !host) {
1068 		int tport;
1069 		char *tuser;
1070 		switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1071 		case -1:
1072 			usage();
1073 			break;
1074 		case 0:
1075 			if (options.user == NULL) {
1076 				options.user = tuser;
1077 				tuser = NULL;
1078 			}
1079 			free(tuser);
1080 			if (options.port == -1 && tport != -1)
1081 				options.port = tport;
1082 			break;
1083 		default:
1084 			p = xstrdup(*av);
1085 			cp = strrchr(p, '@');
1086 			if (cp != NULL) {
1087 				if (cp == p)
1088 					usage();
1089 				if (options.user == NULL) {
1090 					options.user = p;
1091 					p = NULL;
1092 				}
1093 				*cp++ = '\0';
1094 				host = xstrdup(cp);
1095 				free(p);
1096 			} else
1097 				host = p;
1098 			break;
1099 		}
1100 		if (ac > 1 && !opt_terminated) {
1101 			optind = optreset = 1;
1102 			goto again;
1103 		}
1104 		ac--, av++;
1105 	}
1106 
1107 	/* Check that we got a host name. */
1108 	if (!host)
1109 		usage();
1110 
1111 	host_arg = xstrdup(host);
1112 
1113 	/* Initialize the command to execute on remote host. */
1114 	if ((command = sshbuf_new()) == NULL)
1115 		fatal("sshbuf_new failed");
1116 
1117 	/*
1118 	 * Save the command to execute on the remote host in a buffer. There
1119 	 * is no limit on the length of the command, except by the maximum
1120 	 * packet size.  Also sets the tty flag if there is no command.
1121 	 */
1122 	if (!ac) {
1123 		/* No command specified - execute shell on a tty. */
1124 		if (subsystem_flag) {
1125 			fprintf(stderr,
1126 			    "You must specify a subsystem to invoke.\n");
1127 			usage();
1128 		}
1129 	} else {
1130 		/* A command has been specified.  Store it into the buffer. */
1131 		for (i = 0; i < ac; i++) {
1132 			if ((r = sshbuf_putf(command, "%s%s",
1133 			    i ? " " : "", av[i])) != 0)
1134 				fatal_fr(r, "buffer error");
1135 		}
1136 	}
1137 
1138 	/*
1139 	 * Initialize "log" output.  Since we are the client all output
1140 	 * goes to stderr unless otherwise specified by -y or -E.
1141 	 */
1142 	if (use_syslog && logfile != NULL)
1143 		fatal("Can't specify both -y and -E");
1144 	if (logfile != NULL)
1145 		log_redirect_stderr_to(logfile);
1146 	log_init(argv0,
1147 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1148 	    SYSLOG_LEVEL_INFO : options.log_level,
1149 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1150 	    SYSLOG_FACILITY_USER : options.log_facility,
1151 	    !use_syslog);
1152 
1153 	if (debug_flag)
1154 		logit("%s, %s", SSH_RELEASE, SSH_OPENSSL_VERSION);
1155 
1156 	/* Parse the configuration files */
1157 	process_config_files(host_arg, pw, 0, &want_final_pass);
1158 	if (want_final_pass)
1159 		debug("configuration requests final Match pass");
1160 
1161 	/* Hostname canonicalisation needs a few options filled. */
1162 	fill_default_options_for_canonicalization(&options);
1163 
1164 	/* If the user has replaced the hostname then take it into use now */
1165 	if (options.hostname != NULL) {
1166 		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
1167 		cp = percent_expand(options.hostname,
1168 		    "h", host, (char *)NULL);
1169 		free(host);
1170 		host = cp;
1171 		free(options.hostname);
1172 		options.hostname = xstrdup(host);
1173 	}
1174 
1175 	/* Don't lowercase addresses, they will be explicitly canonicalised */
1176 	if ((was_addr = is_addr(host)) == 0)
1177 		lowercase(host);
1178 
1179 	/*
1180 	 * Try to canonicalize if requested by configuration or the
1181 	 * hostname is an address.
1182 	 */
1183 	if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1184 		addrs = resolve_canonicalize(&host, options.port);
1185 
1186 	/*
1187 	 * If CanonicalizePermittedCNAMEs have been specified but
1188 	 * other canonicalization did not happen (by not being requested
1189 	 * or by failing with fallback) then the hostname may still be changed
1190 	 * as a result of CNAME following.
1191 	 *
1192 	 * Try to resolve the bare hostname name using the system resolver's
1193 	 * usual search rules and then apply the CNAME follow rules.
1194 	 *
1195 	 * Skip the lookup if a ProxyCommand is being used unless the user
1196 	 * has specifically requested canonicalisation for this case via
1197 	 * CanonicalizeHostname=always
1198 	 */
1199 	direct = option_clear_or_none(options.proxy_command) &&
1200 	    options.jump_host == NULL;
1201 	if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1202 	    options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1203 		if ((addrs = resolve_host(host, options.port,
1204 		    direct, cname, sizeof(cname))) == NULL) {
1205 			/* Don't fatal proxied host names not in the DNS */
1206 			if (direct)
1207 				cleanup_exit(255); /* logged in resolve_host */
1208 		} else
1209 			check_follow_cname(direct, &host, cname);
1210 	}
1211 
1212 	/*
1213 	 * If canonicalisation is enabled then re-parse the configuration
1214 	 * files as new stanzas may match.
1215 	 */
1216 	if (options.canonicalize_hostname != 0 && !want_final_pass) {
1217 		debug("hostname canonicalisation enabled, "
1218 		    "will re-parse configuration");
1219 		want_final_pass = 1;
1220 	}
1221 
1222 	if (want_final_pass) {
1223 		debug("re-parsing configuration");
1224 		free(options.hostname);
1225 		options.hostname = xstrdup(host);
1226 		process_config_files(host_arg, pw, 1, NULL);
1227 		/*
1228 		 * Address resolution happens early with canonicalisation
1229 		 * enabled and the port number may have changed since, so
1230 		 * reset it in address list
1231 		 */
1232 		if (addrs != NULL && options.port > 0)
1233 			set_addrinfo_port(addrs, options.port);
1234 	}
1235 
1236 	/* Fill configuration defaults. */
1237 	if (fill_default_options(&options) != 0)
1238 		cleanup_exit(255);
1239 
1240 	if (options.user == NULL)
1241 		options.user = xstrdup(pw->pw_name);
1242 
1243 	/*
1244 	 * If ProxyJump option specified, then construct a ProxyCommand now.
1245 	 */
1246 	if (options.jump_host != NULL) {
1247 		char port_s[8];
1248 		const char *jumpuser = options.jump_user, *sshbin = argv0;
1249 		int port = options.port, jumpport = options.jump_port;
1250 
1251 		if (port <= 0)
1252 			port = default_ssh_port();
1253 		if (jumpport <= 0)
1254 			jumpport = default_ssh_port();
1255 		if (jumpuser == NULL)
1256 			jumpuser = options.user;
1257 		if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1258 		    strcmp(options.user, jumpuser) == 0)
1259 			fatal("jumphost loop via %s", options.jump_host);
1260 
1261 		/*
1262 		 * Try to use SSH indicated by argv[0], but fall back to
1263 		 * "ssh" if it appears unavailable.
1264 		 */
1265 		if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1266 			sshbin = "ssh";
1267 
1268 		/* Consistency check */
1269 		if (options.proxy_command != NULL)
1270 			fatal("inconsistent options: ProxyCommand+ProxyJump");
1271 		/* Never use FD passing for ProxyJump */
1272 		options.proxy_use_fdpass = 0;
1273 		snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1274 		xasprintf(&options.proxy_command,
1275 		    "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1276 		    sshbin,
1277 		    /* Optional "-l user" argument if jump_user set */
1278 		    options.jump_user == NULL ? "" : " -l ",
1279 		    options.jump_user == NULL ? "" : options.jump_user,
1280 		    /* Optional "-p port" argument if jump_port set */
1281 		    options.jump_port <= 0 ? "" : " -p ",
1282 		    options.jump_port <= 0 ? "" : port_s,
1283 		    /* Optional additional jump hosts ",..." */
1284 		    options.jump_extra == NULL ? "" : " -J ",
1285 		    options.jump_extra == NULL ? "" : options.jump_extra,
1286 		    /* Optional "-F" argumment if -F specified */
1287 		    config == NULL ? "" : " -F ",
1288 		    config == NULL ? "" : config,
1289 		    /* Optional "-v" arguments if -v set */
1290 		    debug_flag ? " -" : "",
1291 		    debug_flag, "vvv",
1292 		    /* Mandatory hostname */
1293 		    options.jump_host);
1294 		debug("Setting implicit ProxyCommand from ProxyJump: %s",
1295 		    options.proxy_command);
1296 	}
1297 
1298 	if (options.port == 0)
1299 		options.port = default_ssh_port();
1300 	channel_set_af(ssh, options.address_family);
1301 
1302 	/* Tidy and check options */
1303 	if (options.host_key_alias != NULL)
1304 		lowercase(options.host_key_alias);
1305 	if (options.proxy_command != NULL &&
1306 	    strcmp(options.proxy_command, "-") == 0 &&
1307 	    options.proxy_use_fdpass)
1308 		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1309 	if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1310 		if (options.control_persist && options.control_path != NULL) {
1311 			debug("UpdateHostKeys=ask is incompatible with "
1312 			    "ControlPersist; disabling");
1313 			options.update_hostkeys = 0;
1314 		} else if (sshbuf_len(command) != 0 ||
1315 		    options.remote_command != NULL ||
1316 		    options.request_tty == REQUEST_TTY_NO) {
1317 			debug("UpdateHostKeys=ask is incompatible with "
1318 			    "remote command execution; disabling");
1319 			options.update_hostkeys = 0;
1320 		} else if (options.log_level < SYSLOG_LEVEL_INFO) {
1321 			/* no point logging anything; user won't see it */
1322 			options.update_hostkeys = 0;
1323 		}
1324 	}
1325 	if (options.connection_attempts <= 0)
1326 		fatal("Invalid number of ConnectionAttempts");
1327 
1328 	if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1329 		fatal("Cannot execute command-line and remote command.");
1330 
1331 	/* Cannot fork to background if no command. */
1332 	if (fork_after_authentication_flag && sshbuf_len(command) == 0 &&
1333 	    options.remote_command == NULL && !no_shell_flag)
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 		log_verbose_add(options.log_verbose[j]);
1341 
1342 	if (options.request_tty == REQUEST_TTY_YES ||
1343 	    options.request_tty == REQUEST_TTY_FORCE)
1344 		tty_flag = 1;
1345 
1346 	/* Allocate a tty by default if no command specified. */
1347 	if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1348 		tty_flag = options.request_tty != REQUEST_TTY_NO;
1349 
1350 	/* Force no tty */
1351 	if (options.request_tty == REQUEST_TTY_NO ||
1352 	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1353 		tty_flag = 0;
1354 	/* Do not allocate a tty if stdin is not a tty. */
1355 	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1356 	    options.request_tty != REQUEST_TTY_FORCE) {
1357 		if (tty_flag)
1358 			logit("Pseudo-terminal will not be allocated because "
1359 			    "stdin is not a terminal.");
1360 		tty_flag = 0;
1361 	}
1362 
1363 	/* Set up strings used to percent_expand() arguments */
1364 	cinfo = xcalloc(1, sizeof(*cinfo));
1365 	if (gethostname(thishost, sizeof(thishost)) == -1)
1366 		fatal("gethostname: %s", strerror(errno));
1367 	cinfo->thishost = xstrdup(thishost);
1368 	thishost[strcspn(thishost, ".")] = '\0';
1369 	cinfo->shorthost = xstrdup(thishost);
1370 	xasprintf(&cinfo->portstr, "%d", options.port);
1371 	xasprintf(&cinfo->uidstr, "%llu",
1372 	    (unsigned long long)pw->pw_uid);
1373 	cinfo->keyalias = xstrdup(options.host_key_alias ?
1374 	    options.host_key_alias : host_arg);
1375 	cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
1376 	    cinfo->portstr, options.user);
1377 	cinfo->host_arg = xstrdup(host_arg);
1378 	cinfo->remhost = xstrdup(host);
1379 	cinfo->remuser = xstrdup(options.user);
1380 	cinfo->homedir = xstrdup(pw->pw_dir);
1381 	cinfo->locuser = xstrdup(pw->pw_name);
1382 
1383 	/*
1384 	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1385 	 * after port-forwarding is set up, so it may pick up any local
1386 	 * tunnel interface name allocated.
1387 	 */
1388 	if (options.remote_command != NULL) {
1389 		debug3("expanding RemoteCommand: %s", options.remote_command);
1390 		cp = options.remote_command;
1391 		options.remote_command = default_client_percent_expand(cp,
1392 		    cinfo);
1393 		debug3("expanded RemoteCommand: %s", options.remote_command);
1394 		free(cp);
1395 		if ((r = sshbuf_put(command, options.remote_command,
1396 		    strlen(options.remote_command))) != 0)
1397 			fatal_fr(r, "buffer error");
1398 	}
1399 
1400 	if (options.control_path != NULL) {
1401 		cp = tilde_expand_filename(options.control_path, getuid());
1402 		free(options.control_path);
1403 		options.control_path = default_client_percent_dollar_expand(cp,
1404 		    cinfo);
1405 		free(cp);
1406 	}
1407 
1408 	if (options.identity_agent != NULL) {
1409 		p = tilde_expand_filename(options.identity_agent, getuid());
1410 		cp = default_client_percent_dollar_expand(p, cinfo);
1411 		free(p);
1412 		free(options.identity_agent);
1413 		options.identity_agent = cp;
1414 	}
1415 
1416 	if (options.forward_agent_sock_path != NULL) {
1417 		p = tilde_expand_filename(options.forward_agent_sock_path,
1418 		    getuid());
1419 		cp = default_client_percent_dollar_expand(p, cinfo);
1420 		free(p);
1421 		free(options.forward_agent_sock_path);
1422 		options.forward_agent_sock_path = cp;
1423 	}
1424 
1425 	if (options.num_system_hostfiles > 0 &&
1426 	    strcasecmp(options.system_hostfiles[0], "none") == 0) {
1427 		if (options.num_system_hostfiles > 1)
1428 			fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1429 			    "appears with other entries");
1430 		free(options.system_hostfiles[0]);
1431 		options.system_hostfiles[0] = NULL;
1432 		options.num_system_hostfiles = 0;
1433 	}
1434 
1435 	if (options.num_user_hostfiles > 0 &&
1436 	    strcasecmp(options.user_hostfiles[0], "none") == 0) {
1437 		if (options.num_user_hostfiles > 1)
1438 			fatal("Invalid UserKnownHostsFiles: \"none\" "
1439 			    "appears with other entries");
1440 		free(options.user_hostfiles[0]);
1441 		options.user_hostfiles[0] = NULL;
1442 		options.num_user_hostfiles = 0;
1443 	}
1444 	for (j = 0; j < options.num_user_hostfiles; j++) {
1445 		if (options.user_hostfiles[j] == NULL)
1446 			continue;
1447 		cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1448 		p = default_client_percent_dollar_expand(cp, cinfo);
1449 		if (strcmp(options.user_hostfiles[j], p) != 0)
1450 			debug3("expanded UserKnownHostsFile '%s' -> "
1451 			    "'%s'", options.user_hostfiles[j], p);
1452 		free(options.user_hostfiles[j]);
1453 		free(cp);
1454 		options.user_hostfiles[j] = p;
1455 	}
1456 
1457 	for (i = 0; i < options.num_local_forwards; i++) {
1458 		if (options.local_forwards[i].listen_path != NULL) {
1459 			cp = options.local_forwards[i].listen_path;
1460 			p = options.local_forwards[i].listen_path =
1461 			    default_client_percent_expand(cp, cinfo);
1462 			if (strcmp(cp, p) != 0)
1463 				debug3("expanded LocalForward listen path "
1464 				    "'%s' -> '%s'", cp, p);
1465 			free(cp);
1466 		}
1467 		if (options.local_forwards[i].connect_path != NULL) {
1468 			cp = options.local_forwards[i].connect_path;
1469 			p = options.local_forwards[i].connect_path =
1470 			    default_client_percent_expand(cp, cinfo);
1471 			if (strcmp(cp, p) != 0)
1472 				debug3("expanded LocalForward connect path "
1473 				    "'%s' -> '%s'", cp, p);
1474 			free(cp);
1475 		}
1476 	}
1477 
1478 	for (i = 0; i < options.num_remote_forwards; i++) {
1479 		if (options.remote_forwards[i].listen_path != NULL) {
1480 			cp = options.remote_forwards[i].listen_path;
1481 			p = options.remote_forwards[i].listen_path =
1482 			    default_client_percent_expand(cp, cinfo);
1483 			if (strcmp(cp, p) != 0)
1484 				debug3("expanded RemoteForward listen path "
1485 				    "'%s' -> '%s'", cp, p);
1486 			free(cp);
1487 		}
1488 		if (options.remote_forwards[i].connect_path != NULL) {
1489 			cp = options.remote_forwards[i].connect_path;
1490 			p = options.remote_forwards[i].connect_path =
1491 			    default_client_percent_expand(cp, cinfo);
1492 			if (strcmp(cp, p) != 0)
1493 				debug3("expanded RemoteForward connect path "
1494 				    "'%s' -> '%s'", cp, p);
1495 			free(cp);
1496 		}
1497 	}
1498 
1499 	if (config_test) {
1500 		dump_client_config(&options, host);
1501 		exit(0);
1502 	}
1503 
1504 	/* Expand SecurityKeyProvider if it refers to an environment variable */
1505 	if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1506 	    strlen(options.sk_provider) > 1) {
1507 		if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1508 			debug("Authenticator provider %s did not resolve; "
1509 			    "disabling", options.sk_provider);
1510 			free(options.sk_provider);
1511 			options.sk_provider = NULL;
1512 		} else {
1513 			debug2("resolved SecurityKeyProvider %s => %s",
1514 			    options.sk_provider, cp);
1515 			free(options.sk_provider);
1516 			options.sk_provider = xstrdup(cp);
1517 		}
1518 	}
1519 
1520 	if (muxclient_command != 0 && options.control_path == NULL)
1521 		fatal("No ControlPath specified for \"-O\" command");
1522 	if (options.control_path != NULL) {
1523 		int sock;
1524 		if ((sock = muxclient(options.control_path)) >= 0) {
1525 			ssh_packet_set_connection(ssh, sock, sock);
1526 			ssh_packet_set_mux(ssh);
1527 			goto skip_connect;
1528 		}
1529 	}
1530 
1531 	/*
1532 	 * If hostname canonicalisation was not enabled, then we may not
1533 	 * have yet resolved the hostname. Do so now.
1534 	 */
1535 	if (addrs == NULL && options.proxy_command == NULL) {
1536 		debug2("resolving \"%s\" port %d", host, options.port);
1537 		if ((addrs = resolve_host(host, options.port, 1,
1538 		    cname, sizeof(cname))) == NULL)
1539 			cleanup_exit(255); /* resolve_host logs the error */
1540 	}
1541 
1542 	if (options.connection_timeout >= INT_MAX/1000)
1543 		timeout_ms = INT_MAX;
1544 	else
1545 		timeout_ms = options.connection_timeout * 1000;
1546 
1547 	/* Open a connection to the remote host. */
1548 	if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port,
1549 	    options.connection_attempts,
1550 	    &timeout_ms, options.tcp_keep_alive) != 0)
1551  		exit(255);
1552 
1553 	if (addrs != NULL)
1554 		freeaddrinfo(addrs);
1555 
1556 	ssh_packet_set_timeout(ssh, options.server_alive_interval,
1557 	    options.server_alive_count_max);
1558 
1559 	if (timeout_ms > 0)
1560 		debug3("timeout: %d ms remain after connect", timeout_ms);
1561 
1562 	/*
1563 	 * If we successfully made the connection and we have hostbased auth
1564 	 * enabled, load the public keys so we can later use the ssh-keysign
1565 	 * helper to sign challenges.
1566 	 */
1567 	sensitive_data.nkeys = 0;
1568 	sensitive_data.keys = NULL;
1569 	if (options.hostbased_authentication) {
1570 		sensitive_data.nkeys = 10;
1571 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1572 		    sizeof(struct sshkey));
1573 
1574 		/* XXX check errors? */
1575 #define L_PUBKEY(p,o) do { \
1576 	if ((o) >= sensitive_data.nkeys) \
1577 		fatal_f("pubkey out of array bounds"); \
1578 	check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1579 	    p, "pubkey"); \
1580 } while (0)
1581 #define L_CERT(p,o) do { \
1582 	if ((o) >= sensitive_data.nkeys) \
1583 		fatal_f("cert out of array bounds"); \
1584 	check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
1585 } while (0)
1586 
1587 		if (options.hostbased_authentication == 1) {
1588 			L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1589 			L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1590 			L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1591 			L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1592 			L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1593 			L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1594 			L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1595 			L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1596 			L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1597 			L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1598 		}
1599 	}
1600 
1601 	/* load options.identity_files */
1602 	load_public_identity_files(cinfo);
1603 
1604 	/* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1605 	if (options.identity_agent &&
1606 	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1607 		if (strcmp(options.identity_agent, "none") == 0) {
1608 			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1609 		} else {
1610 			cp = options.identity_agent;
1611 			/* legacy (limited) format */
1612 			if (cp[0] == '$' && cp[1] != '{') {
1613 				if (!valid_env_name(cp + 1)) {
1614 					fatal("Invalid IdentityAgent "
1615 					    "environment variable name %s", cp);
1616 				}
1617 				if ((p = getenv(cp + 1)) == NULL)
1618 					unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1619 				else
1620 					setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1621 			} else {
1622 				/* identity_agent specifies a path directly */
1623 				setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1624 			}
1625 		}
1626 	}
1627 
1628 	if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1629 		cp = options.forward_agent_sock_path;
1630 		if (cp[0] == '$') {
1631 			if (!valid_env_name(cp + 1)) {
1632 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1633 			}
1634 			if ((p = getenv(cp + 1)) != NULL)
1635 				forward_agent_sock_path = p;
1636 			else
1637 				options.forward_agent = 0;
1638 			free(cp);
1639 		} else {
1640 			forward_agent_sock_path = cp;
1641 		}
1642 	}
1643 
1644 	/* Expand ~ in known host file names. */
1645 	tilde_expand_paths(options.system_hostfiles,
1646 	    options.num_system_hostfiles);
1647 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1648 
1649 	ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1650 	ssh_signal(SIGCHLD, main_sigchld_handler);
1651 
1652 	/* Log into the remote system.  Never returns if the login fails. */
1653 	ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1654 	    options.port, pw, timeout_ms, cinfo);
1655 
1656 	if (ssh_packet_connection_is_on_socket(ssh)) {
1657 		verbose("Authenticated to %s ([%s]:%d).", host,
1658 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1659 	} else {
1660 		verbose("Authenticated to %s (via proxy).", host);
1661 	}
1662 
1663 	/* We no longer need the private host keys.  Clear them now. */
1664 	if (sensitive_data.nkeys != 0) {
1665 		for (i = 0; i < sensitive_data.nkeys; i++) {
1666 			if (sensitive_data.keys[i] != NULL) {
1667 				/* Destroys contents safely */
1668 				debug3("clear hostkey %d", i);
1669 				sshkey_free(sensitive_data.keys[i]);
1670 				sensitive_data.keys[i] = NULL;
1671 			}
1672 		}
1673 		free(sensitive_data.keys);
1674 	}
1675 	for (i = 0; i < options.num_identity_files; i++) {
1676 		free(options.identity_files[i]);
1677 		options.identity_files[i] = NULL;
1678 		if (options.identity_keys[i]) {
1679 			sshkey_free(options.identity_keys[i]);
1680 			options.identity_keys[i] = NULL;
1681 		}
1682 	}
1683 	for (i = 0; i < options.num_certificate_files; i++) {
1684 		free(options.certificate_files[i]);
1685 		options.certificate_files[i] = NULL;
1686 	}
1687 
1688  skip_connect:
1689 	exit_status = ssh_session2(ssh, cinfo);
1690 	ssh_conn_info_free(cinfo);
1691 	ssh_packet_close(ssh);
1692 
1693 	if (options.control_path != NULL && muxserver_sock != -1)
1694 		unlink(options.control_path);
1695 
1696 	/* Kill ProxyCommand if it is running. */
1697 	ssh_kill_proxy_command();
1698 
1699 	return exit_status;
1700 }
1701 
1702 static void
1703 control_persist_detach(void)
1704 {
1705 	pid_t pid;
1706 
1707 	debug_f("backgrounding master process");
1708 
1709 	/*
1710 	 * master (current process) into the background, and make the
1711 	 * foreground process a client of the backgrounded master.
1712 	 */
1713 	switch ((pid = fork())) {
1714 	case -1:
1715 		fatal_f("fork: %s", strerror(errno));
1716 	case 0:
1717 		/* Child: master process continues mainloop */
1718 		break;
1719 	default:
1720 		/* Parent: set up mux client to connect to backgrounded master */
1721 		debug2_f("background process is %ld", (long)pid);
1722 		stdin_null_flag = ostdin_null_flag;
1723 		options.request_tty = orequest_tty;
1724 		tty_flag = otty_flag;
1725 		close(muxserver_sock);
1726 		muxserver_sock = -1;
1727 		options.control_master = SSHCTL_MASTER_NO;
1728 		muxclient(options.control_path);
1729 		/* muxclient() doesn't return on success. */
1730 		fatal("Failed to connect to new control master");
1731 	}
1732 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1733 		error_f("stdfd_devnull failed");
1734 	daemon(1, 1);
1735 	setproctitle("%s [mux]", options.control_path);
1736 }
1737 
1738 /* Do fork() after authentication. Used by "ssh -f" */
1739 static void
1740 fork_postauth(void)
1741 {
1742 	if (need_controlpersist_detach)
1743 		control_persist_detach();
1744 	debug("forking to background");
1745 	fork_after_authentication_flag = 0;
1746 	if (daemon(1, 1) == -1)
1747 		fatal("daemon() failed: %.200s", strerror(errno));
1748 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1749 		error_f("stdfd_devnull failed");
1750 }
1751 
1752 static void
1753 forwarding_success(void)
1754 {
1755 	if (forward_confirms_pending == -1)
1756 		return;
1757 	if (--forward_confirms_pending == 0) {
1758 		debug_f("all expected forwarding replies received");
1759 		if (fork_after_authentication_flag)
1760 			fork_postauth();
1761 	} else {
1762 		debug2_f("%d expected forwarding replies remaining",
1763 		    forward_confirms_pending);
1764 	}
1765 }
1766 
1767 /* Callback for remote forward global requests */
1768 static void
1769 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1770 {
1771 	struct Forward *rfwd = (struct Forward *)ctxt;
1772 	u_int port;
1773 	int r;
1774 
1775 	/* XXX verbose() on failure? */
1776 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1777 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1778 	    rfwd->listen_path ? rfwd->listen_path :
1779 	    rfwd->listen_host ? rfwd->listen_host : "",
1780 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1781 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1782 	    rfwd->connect_host, rfwd->connect_port);
1783 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1784 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1785 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1786 				fatal_fr(r, "parse packet");
1787 			if (port > 65535) {
1788 				error("Invalid allocated port %u for remote "
1789 				    "forward to %s:%d", port,
1790 				    rfwd->connect_host, rfwd->connect_port);
1791 				/* Ensure failure processing runs below */
1792 				type = SSH2_MSG_REQUEST_FAILURE;
1793 				channel_update_permission(ssh,
1794 				    rfwd->handle, -1);
1795 			} else {
1796 				rfwd->allocated_port = (int)port;
1797 				logit("Allocated port %u for remote "
1798 				    "forward to %s:%d",
1799 				    rfwd->allocated_port, rfwd->connect_host,
1800 				    rfwd->connect_port);
1801 				channel_update_permission(ssh,
1802 				    rfwd->handle, rfwd->allocated_port);
1803 			}
1804 		} else {
1805 			channel_update_permission(ssh, rfwd->handle, -1);
1806 		}
1807 	}
1808 
1809 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1810 		if (options.exit_on_forward_failure) {
1811 			if (rfwd->listen_path != NULL)
1812 				fatal("Error: remote port forwarding failed "
1813 				    "for listen path %s", rfwd->listen_path);
1814 			else
1815 				fatal("Error: remote port forwarding failed "
1816 				    "for listen port %d", rfwd->listen_port);
1817 		} else {
1818 			if (rfwd->listen_path != NULL)
1819 				logit("Warning: remote port forwarding failed "
1820 				    "for listen path %s", rfwd->listen_path);
1821 			else
1822 				logit("Warning: remote port forwarding failed "
1823 				    "for listen port %d", rfwd->listen_port);
1824 		}
1825 	}
1826 	forwarding_success();
1827 }
1828 
1829 static void
1830 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1831 {
1832 	debug("stdio forwarding: done");
1833 	cleanup_exit(0);
1834 }
1835 
1836 static void
1837 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1838 {
1839 	if (!success)
1840 		fatal("stdio forwarding failed");
1841 }
1842 
1843 static void
1844 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1845 {
1846 	if (!success) {
1847 		error("Tunnel forwarding failed");
1848 		if (options.exit_on_forward_failure)
1849 			cleanup_exit(255);
1850 	}
1851 
1852 	debug_f("tunnel forward established, id=%d", id);
1853 	forwarding_success();
1854 }
1855 
1856 static void
1857 ssh_init_stdio_forwarding(struct ssh *ssh)
1858 {
1859 	Channel *c;
1860 	int in, out;
1861 
1862 	if (options.stdio_forward_host == NULL)
1863 		return;
1864 
1865 	debug3_f("%s:%d", options.stdio_forward_host,
1866 	    options.stdio_forward_port);
1867 
1868 	if ((in = dup(STDIN_FILENO)) == -1 ||
1869 	    (out = dup(STDOUT_FILENO)) == -1)
1870 		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1871 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1872 	    options.stdio_forward_port, in, out)) == NULL)
1873 		fatal_f("channel_connect_stdio_fwd failed");
1874 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1875 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1876 }
1877 
1878 static void
1879 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1880 {
1881 	int success = 0;
1882 	int i;
1883 
1884 	if (options.exit_on_forward_failure)
1885 		forward_confirms_pending = 0; /* track pending requests */
1886 	/* Initiate local TCP/IP port forwardings. */
1887 	for (i = 0; i < options.num_local_forwards; i++) {
1888 		debug("Local connections to %.200s:%d forwarded to remote "
1889 		    "address %.200s:%d",
1890 		    (options.local_forwards[i].listen_path != NULL) ?
1891 		    options.local_forwards[i].listen_path :
1892 		    (options.local_forwards[i].listen_host == NULL) ?
1893 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1894 		    options.local_forwards[i].listen_host,
1895 		    options.local_forwards[i].listen_port,
1896 		    (options.local_forwards[i].connect_path != NULL) ?
1897 		    options.local_forwards[i].connect_path :
1898 		    options.local_forwards[i].connect_host,
1899 		    options.local_forwards[i].connect_port);
1900 		success += channel_setup_local_fwd_listener(ssh,
1901 		    &options.local_forwards[i], &options.fwd_opts);
1902 	}
1903 	if (i > 0 && success != i && options.exit_on_forward_failure)
1904 		fatal("Could not request local forwarding.");
1905 	if (i > 0 && success == 0)
1906 		error("Could not request local forwarding.");
1907 
1908 	/* Initiate remote TCP/IP port forwardings. */
1909 	for (i = 0; i < options.num_remote_forwards; i++) {
1910 		debug("Remote connections from %.200s:%d forwarded to "
1911 		    "local address %.200s:%d",
1912 		    (options.remote_forwards[i].listen_path != NULL) ?
1913 		    options.remote_forwards[i].listen_path :
1914 		    (options.remote_forwards[i].listen_host == NULL) ?
1915 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1916 		    options.remote_forwards[i].listen_port,
1917 		    (options.remote_forwards[i].connect_path != NULL) ?
1918 		    options.remote_forwards[i].connect_path :
1919 		    options.remote_forwards[i].connect_host,
1920 		    options.remote_forwards[i].connect_port);
1921 		if ((options.remote_forwards[i].handle =
1922 		    channel_request_remote_forwarding(ssh,
1923 		    &options.remote_forwards[i])) >= 0) {
1924 			client_register_global_confirm(
1925 			    ssh_confirm_remote_forward,
1926 			    &options.remote_forwards[i]);
1927 			forward_confirms_pending++;
1928 		} else if (options.exit_on_forward_failure)
1929 			fatal("Could not request remote forwarding.");
1930 		else
1931 			logit("Warning: Could not request remote forwarding.");
1932 	}
1933 
1934 	/* Initiate tunnel forwarding. */
1935 	if (options.tun_open != SSH_TUNMODE_NO) {
1936 		if ((*ifname = client_request_tun_fwd(ssh,
1937 		    options.tun_open, options.tun_local,
1938 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
1939 			forward_confirms_pending++;
1940 		else if (options.exit_on_forward_failure)
1941 			fatal("Could not request tunnel forwarding.");
1942 		else
1943 			error("Could not request tunnel forwarding.");
1944 	}
1945 	if (forward_confirms_pending > 0) {
1946 		debug_f("expecting replies for %d forwards",
1947 		    forward_confirms_pending);
1948 	}
1949 }
1950 
1951 static void
1952 check_agent_present(void)
1953 {
1954 	int r;
1955 
1956 	if (options.forward_agent) {
1957 		/* Clear agent forwarding if we don't have an agent. */
1958 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1959 			options.forward_agent = 0;
1960 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
1961 				debug_r(r, "ssh_get_authentication_socket");
1962 		}
1963 	}
1964 }
1965 
1966 static void
1967 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1968 {
1969 	extern char **environ;
1970 	const char *display;
1971 	int r, interactive = tty_flag;
1972 	char *proto = NULL, *data = NULL;
1973 
1974 	if (!success)
1975 		return; /* No need for error message, channels code sens one */
1976 
1977 	display = getenv("DISPLAY");
1978 	if (display == NULL && options.forward_x11)
1979 		debug("X11 forwarding requested but DISPLAY not set");
1980 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
1981 	    options.xauth_location, options.forward_x11_trusted,
1982 	    options.forward_x11_timeout, &proto, &data) == 0) {
1983 		/* Request forwarding with authentication spoofing. */
1984 		debug("Requesting X11 forwarding with authentication "
1985 		    "spoofing.");
1986 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1987 		    data, 1);
1988 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1989 		/* XXX exit_on_forward_failure */
1990 		interactive = 1;
1991 	}
1992 
1993 	check_agent_present();
1994 	if (options.forward_agent) {
1995 		debug("Requesting authentication agent forwarding.");
1996 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1997 		if ((r = sshpkt_send(ssh)) != 0)
1998 			fatal_fr(r, "send packet");
1999 	}
2000 
2001 	/* Tell the packet module whether this is an interactive session. */
2002 	ssh_packet_set_interactive(ssh, interactive,
2003 	    options.ip_qos_interactive, options.ip_qos_bulk);
2004 
2005 	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
2006 	    NULL, fileno(stdin), command, environ);
2007 }
2008 
2009 /* open new channel for a session */
2010 static int
2011 ssh_session2_open(struct ssh *ssh)
2012 {
2013 	Channel *c;
2014 	int window, packetmax, in, out, err;
2015 
2016 	if (stdin_null_flag) {
2017 		in = open(_PATH_DEVNULL, O_RDONLY);
2018 	} else {
2019 		in = dup(STDIN_FILENO);
2020 	}
2021 	out = dup(STDOUT_FILENO);
2022 	err = dup(STDERR_FILENO);
2023 
2024 	if (in == -1 || out == -1 || err == -1)
2025 		fatal("dup() in/out/err failed");
2026 
2027 	/* enable nonblocking unless tty */
2028 	if (!isatty(in))
2029 		set_nonblock(in);
2030 	if (!isatty(out))
2031 		set_nonblock(out);
2032 	if (!isatty(err))
2033 		set_nonblock(err);
2034 
2035 	window = CHAN_SES_WINDOW_DEFAULT;
2036 	packetmax = CHAN_SES_PACKET_DEFAULT;
2037 	if (tty_flag) {
2038 		window >>= 1;
2039 		packetmax >>= 1;
2040 	}
2041 	c = channel_new(ssh,
2042 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2043 	    window, packetmax, CHAN_EXTENDED_WRITE,
2044 	    "client-session", /*nonblock*/0);
2045 
2046 	debug3_f("channel_new: %d", c->self);
2047 
2048 	channel_send_open(ssh, c->self);
2049 	if (!no_shell_flag)
2050 		channel_register_open_confirm(ssh, c->self,
2051 		    ssh_session2_setup, NULL);
2052 
2053 	return c->self;
2054 }
2055 
2056 static int
2057 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2058 {
2059 	int r, id = -1;
2060 	char *cp, *tun_fwd_ifname = NULL;
2061 
2062 	/* XXX should be pre-session */
2063 	if (!options.control_persist)
2064 		ssh_init_stdio_forwarding(ssh);
2065 
2066 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2067 
2068 	if (options.local_command != NULL) {
2069 		debug3("expanding LocalCommand: %s", options.local_command);
2070 		cp = options.local_command;
2071 		options.local_command = percent_expand(cp,
2072 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2073 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2074 		    (char *)NULL);
2075 		debug3("expanded LocalCommand: %s", options.local_command);
2076 		free(cp);
2077 	}
2078 
2079 	/* Start listening for multiplex clients */
2080 	if (!ssh_packet_get_mux(ssh))
2081 		muxserver_listen(ssh);
2082 
2083 	/*
2084 	 * If we are in control persist mode and have a working mux listen
2085 	 * socket, then prepare to background ourselves and have a foreground
2086 	 * client attach as a control client.
2087 	 * NB. we must save copies of the flags that we override for
2088 	 * the backgrounding, since we defer attachment of the client until
2089 	 * after the connection is fully established (in particular,
2090 	 * async rfwd replies have been received for ExitOnForwardFailure).
2091 	 */
2092 	if (options.control_persist && muxserver_sock != -1) {
2093 		ostdin_null_flag = stdin_null_flag;
2094 		ono_shell_flag = no_shell_flag;
2095 		orequest_tty = options.request_tty;
2096 		otty_flag = tty_flag;
2097 		stdin_null_flag = 1;
2098 		no_shell_flag = 1;
2099 		tty_flag = 0;
2100 		if (!fork_after_authentication_flag)
2101 			need_controlpersist_detach = 1;
2102 		fork_after_authentication_flag = 1;
2103 	}
2104 	/*
2105 	 * ControlPersist mux listen socket setup failed, attempt the
2106 	 * stdio forward setup that we skipped earlier.
2107 	 */
2108 	if (options.control_persist && muxserver_sock == -1)
2109 		ssh_init_stdio_forwarding(ssh);
2110 
2111 	if (!no_shell_flag)
2112 		id = ssh_session2_open(ssh);
2113 	else {
2114 		ssh_packet_set_interactive(ssh,
2115 		    options.control_master == SSHCTL_MASTER_NO,
2116 		    options.ip_qos_interactive, options.ip_qos_bulk);
2117 	}
2118 
2119 	/* If we don't expect to open a new session, then disallow it */
2120 	if (options.control_master == SSHCTL_MASTER_NO &&
2121 	    (ssh->compat & SSH_NEW_OPENSSH)) {
2122 		debug("Requesting no-more-sessions@openssh.com");
2123 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2124 		    (r = sshpkt_put_cstring(ssh,
2125 		    "no-more-sessions@openssh.com")) != 0 ||
2126 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2127 		    (r = sshpkt_send(ssh)) != 0)
2128 			fatal_fr(r, "send packet");
2129 	}
2130 
2131 	/* Execute a local command */
2132 	if (options.local_command != NULL &&
2133 	    options.permit_local_command)
2134 		ssh_local_cmd(options.local_command);
2135 
2136 	/*
2137 	 * stdout is now owned by the session channel; clobber it here
2138 	 * so future channel closes are propagated to the local fd.
2139 	 * NB. this can only happen after LocalCommand has completed,
2140 	 * as it may want to write to stdout.
2141 	 */
2142 	if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2143 		error_f("stdfd_devnull failed");
2144 
2145 	/*
2146 	 * If requested and we are not interested in replies to remote
2147 	 * forwarding requests, then let ssh continue in the background.
2148 	 */
2149 	if (fork_after_authentication_flag) {
2150 		if (options.exit_on_forward_failure &&
2151 		    options.num_remote_forwards > 0) {
2152 			debug("deferring postauth fork until remote forward "
2153 			    "confirmation received");
2154 		} else
2155 			fork_postauth();
2156 	}
2157 
2158 	return client_loop(ssh, tty_flag, tty_flag ?
2159 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2160 }
2161 
2162 /* Loads all IdentityFile and CertificateFile keys */
2163 static void
2164 load_public_identity_files(const struct ssh_conn_info *cinfo)
2165 {
2166 	char *filename, *cp;
2167 	struct sshkey *public;
2168 	int i;
2169 	u_int n_ids, n_certs;
2170 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2171 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2172 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2173 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2174 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2175 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2176 #ifdef ENABLE_PKCS11
2177 	struct sshkey **keys = NULL;
2178 	char **comments = NULL;
2179 	int nkeys;
2180 #endif /* PKCS11 */
2181 
2182 	n_ids = n_certs = 0;
2183 	memset(identity_files, 0, sizeof(identity_files));
2184 	memset(identity_keys, 0, sizeof(identity_keys));
2185 	memset(identity_file_userprovided, 0,
2186 	    sizeof(identity_file_userprovided));
2187 	memset(certificate_files, 0, sizeof(certificate_files));
2188 	memset(certificates, 0, sizeof(certificates));
2189 	memset(certificate_file_userprovided, 0,
2190 	    sizeof(certificate_file_userprovided));
2191 
2192 #ifdef ENABLE_PKCS11
2193 	if (options.pkcs11_provider != NULL &&
2194 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2195 	    (pkcs11_init(!options.batch_mode) == 0) &&
2196 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2197 	    &keys, &comments)) > 0) {
2198 		for (i = 0; i < nkeys; i++) {
2199 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2200 				sshkey_free(keys[i]);
2201 				free(comments[i]);
2202 				continue;
2203 			}
2204 			identity_keys[n_ids] = keys[i];
2205 			identity_files[n_ids] = comments[i]; /* transferred */
2206 			n_ids++;
2207 		}
2208 		free(keys);
2209 		free(comments);
2210 	}
2211 #endif /* ENABLE_PKCS11 */
2212 	for (i = 0; i < options.num_identity_files; i++) {
2213 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2214 		    strcasecmp(options.identity_files[i], "none") == 0) {
2215 			free(options.identity_files[i]);
2216 			options.identity_files[i] = NULL;
2217 			continue;
2218 		}
2219 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2220 		filename = default_client_percent_dollar_expand(cp, cinfo);
2221 		free(cp);
2222 		check_load(sshkey_load_public(filename, &public, NULL),
2223 		    filename, "pubkey");
2224 		debug("identity file %s type %d", filename,
2225 		    public ? public->type : -1);
2226 		free(options.identity_files[i]);
2227 		identity_files[n_ids] = filename;
2228 		identity_keys[n_ids] = public;
2229 		identity_file_userprovided[n_ids] =
2230 		    options.identity_file_userprovided[i];
2231 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2232 			continue;
2233 
2234 		/*
2235 		 * If no certificates have been explicitly listed then try
2236 		 * to add the default certificate variant too.
2237 		 */
2238 		if (options.num_certificate_files != 0)
2239 			continue;
2240 		xasprintf(&cp, "%s-cert", filename);
2241 		check_load(sshkey_load_public(cp, &public, NULL),
2242 		    filename, "pubkey");
2243 		debug("identity file %s type %d", cp,
2244 		    public ? public->type : -1);
2245 		if (public == NULL) {
2246 			free(cp);
2247 			continue;
2248 		}
2249 		if (!sshkey_is_cert(public)) {
2250 			debug_f("key %s type %s is not a certificate",
2251 			    cp, sshkey_type(public));
2252 			sshkey_free(public);
2253 			free(cp);
2254 			continue;
2255 		}
2256 		/* NB. leave filename pointing to private key */
2257 		identity_files[n_ids] = xstrdup(filename);
2258 		identity_keys[n_ids] = public;
2259 		identity_file_userprovided[n_ids] =
2260 		    options.identity_file_userprovided[i];
2261 		n_ids++;
2262 	}
2263 
2264 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2265 		fatal_f("too many certificates");
2266 	for (i = 0; i < options.num_certificate_files; i++) {
2267 		cp = tilde_expand_filename(options.certificate_files[i],
2268 		    getuid());
2269 		filename = default_client_percent_dollar_expand(cp, cinfo);
2270 		free(cp);
2271 
2272 		check_load(sshkey_load_public(filename, &public, NULL),
2273 		    filename, "certificate");
2274 		debug("certificate file %s type %d", filename,
2275 		    public ? public->type : -1);
2276 		free(options.certificate_files[i]);
2277 		options.certificate_files[i] = NULL;
2278 		if (public == NULL) {
2279 			free(filename);
2280 			continue;
2281 		}
2282 		if (!sshkey_is_cert(public)) {
2283 			debug_f("key %s type %s is not a certificate",
2284 			    filename, sshkey_type(public));
2285 			sshkey_free(public);
2286 			free(filename);
2287 			continue;
2288 		}
2289 		certificate_files[n_certs] = filename;
2290 		certificates[n_certs] = public;
2291 		certificate_file_userprovided[n_certs] =
2292 		    options.certificate_file_userprovided[i];
2293 		++n_certs;
2294 	}
2295 
2296 	options.num_identity_files = n_ids;
2297 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2298 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2299 	memcpy(options.identity_file_userprovided,
2300 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2301 
2302 	options.num_certificate_files = n_certs;
2303 	memcpy(options.certificate_files,
2304 	    certificate_files, sizeof(certificate_files));
2305 	memcpy(options.certificates, certificates, sizeof(certificates));
2306 	memcpy(options.certificate_file_userprovided,
2307 	    certificate_file_userprovided,
2308 	    sizeof(certificate_file_userprovided));
2309 }
2310 
2311 static void
2312 main_sigchld_handler(int sig)
2313 {
2314 	int save_errno = errno;
2315 	pid_t pid;
2316 	int status;
2317 
2318 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2319 	    (pid == -1 && errno == EINTR))
2320 		;
2321 	errno = save_errno;
2322 }
2323