xref: /openssh-portable/ssh.c (revision 69338ab4)
1 /* $OpenBSD: ssh.c,v 1.550 2021/02/02 22:36:59 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 	}
1423 
1424 	if (options.num_system_hostfiles > 0 &&
1425 	    strcasecmp(options.system_hostfiles[0], "none") == 0) {
1426 		if (options.num_system_hostfiles > 1)
1427 			fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1428 			    "appears with other entries");
1429 		free(options.system_hostfiles[0]);
1430 		options.system_hostfiles[0] = NULL;
1431 		options.num_system_hostfiles = 0;
1432 	}
1433 
1434 	if (options.num_user_hostfiles > 0 &&
1435 	    strcasecmp(options.user_hostfiles[0], "none") == 0) {
1436 		if (options.num_user_hostfiles > 1)
1437 			fatal("Invalid UserKnownHostsFiles: \"none\" "
1438 			    "appears with other entries");
1439 		free(options.user_hostfiles[0]);
1440 		options.user_hostfiles[0] = NULL;
1441 		options.num_user_hostfiles = 0;
1442 	}
1443 	for (j = 0; j < options.num_user_hostfiles; j++) {
1444 		if (options.user_hostfiles[j] == NULL)
1445 			continue;
1446 		cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1447 		p = default_client_percent_dollar_expand(cp, cinfo);
1448 		if (strcmp(options.user_hostfiles[j], p) != 0)
1449 			debug3("expanded UserKnownHostsFile '%s' -> "
1450 			    "'%s'", options.user_hostfiles[j], p);
1451 		free(options.user_hostfiles[j]);
1452 		free(cp);
1453 		options.user_hostfiles[j] = p;
1454 	}
1455 
1456 	for (i = 0; i < options.num_local_forwards; i++) {
1457 		if (options.local_forwards[i].listen_path != NULL) {
1458 			cp = options.local_forwards[i].listen_path;
1459 			p = options.local_forwards[i].listen_path =
1460 			    default_client_percent_expand(cp, cinfo);
1461 			if (strcmp(cp, p) != 0)
1462 				debug3("expanded LocalForward listen path "
1463 				    "'%s' -> '%s'", cp, p);
1464 			free(cp);
1465 		}
1466 		if (options.local_forwards[i].connect_path != NULL) {
1467 			cp = options.local_forwards[i].connect_path;
1468 			p = options.local_forwards[i].connect_path =
1469 			    default_client_percent_expand(cp, cinfo);
1470 			if (strcmp(cp, p) != 0)
1471 				debug3("expanded LocalForward connect path "
1472 				    "'%s' -> '%s'", cp, p);
1473 			free(cp);
1474 		}
1475 	}
1476 
1477 	for (i = 0; i < options.num_remote_forwards; i++) {
1478 		if (options.remote_forwards[i].listen_path != NULL) {
1479 			cp = options.remote_forwards[i].listen_path;
1480 			p = options.remote_forwards[i].listen_path =
1481 			    default_client_percent_expand(cp, cinfo);
1482 			if (strcmp(cp, p) != 0)
1483 				debug3("expanded RemoteForward listen path "
1484 				    "'%s' -> '%s'", cp, p);
1485 			free(cp);
1486 		}
1487 		if (options.remote_forwards[i].connect_path != NULL) {
1488 			cp = options.remote_forwards[i].connect_path;
1489 			p = options.remote_forwards[i].connect_path =
1490 			    default_client_percent_expand(cp, cinfo);
1491 			if (strcmp(cp, p) != 0)
1492 				debug3("expanded RemoteForward connect path "
1493 				    "'%s' -> '%s'", cp, p);
1494 			free(cp);
1495 		}
1496 	}
1497 
1498 	if (config_test) {
1499 		dump_client_config(&options, host);
1500 		exit(0);
1501 	}
1502 
1503 	/* Expand SecurityKeyProvider if it refers to an environment variable */
1504 	if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1505 	    strlen(options.sk_provider) > 1) {
1506 		if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1507 			debug("Authenticator provider %s did not resolve; "
1508 			    "disabling", options.sk_provider);
1509 			free(options.sk_provider);
1510 			options.sk_provider = NULL;
1511 		} else {
1512 			debug2("resolved SecurityKeyProvider %s => %s",
1513 			    options.sk_provider, cp);
1514 			free(options.sk_provider);
1515 			options.sk_provider = xstrdup(cp);
1516 		}
1517 	}
1518 
1519 	if (muxclient_command != 0 && options.control_path == NULL)
1520 		fatal("No ControlPath specified for \"-O\" command");
1521 	if (options.control_path != NULL) {
1522 		int sock;
1523 		if ((sock = muxclient(options.control_path)) >= 0) {
1524 			ssh_packet_set_connection(ssh, sock, sock);
1525 			ssh_packet_set_mux(ssh);
1526 			goto skip_connect;
1527 		}
1528 	}
1529 
1530 	/*
1531 	 * If hostname canonicalisation was not enabled, then we may not
1532 	 * have yet resolved the hostname. Do so now.
1533 	 */
1534 	if (addrs == NULL && options.proxy_command == NULL) {
1535 		debug2("resolving \"%s\" port %d", host, options.port);
1536 		if ((addrs = resolve_host(host, options.port, 1,
1537 		    cname, sizeof(cname))) == NULL)
1538 			cleanup_exit(255); /* resolve_host logs the error */
1539 	}
1540 
1541 	if (options.connection_timeout >= INT_MAX/1000)
1542 		timeout_ms = INT_MAX;
1543 	else
1544 		timeout_ms = options.connection_timeout * 1000;
1545 
1546 	/* Open a connection to the remote host. */
1547 	if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port,
1548 	    options.connection_attempts,
1549 	    &timeout_ms, options.tcp_keep_alive) != 0)
1550  		exit(255);
1551 
1552 	if (addrs != NULL)
1553 		freeaddrinfo(addrs);
1554 
1555 	ssh_packet_set_timeout(ssh, options.server_alive_interval,
1556 	    options.server_alive_count_max);
1557 
1558 	if (timeout_ms > 0)
1559 		debug3("timeout: %d ms remain after connect", timeout_ms);
1560 
1561 	/*
1562 	 * If we successfully made the connection and we have hostbased auth
1563 	 * enabled, load the public keys so we can later use the ssh-keysign
1564 	 * helper to sign challenges.
1565 	 */
1566 	sensitive_data.nkeys = 0;
1567 	sensitive_data.keys = NULL;
1568 	if (options.hostbased_authentication) {
1569 		sensitive_data.nkeys = 10;
1570 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1571 		    sizeof(struct sshkey));
1572 
1573 		/* XXX check errors? */
1574 #define L_PUBKEY(p,o) do { \
1575 	if ((o) >= sensitive_data.nkeys) \
1576 		fatal_f("pubkey out of array bounds"); \
1577 	check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1578 	    p, "pubkey"); \
1579 } while (0)
1580 #define L_CERT(p,o) do { \
1581 	if ((o) >= sensitive_data.nkeys) \
1582 		fatal_f("cert out of array bounds"); \
1583 	check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
1584 } while (0)
1585 
1586 		if (options.hostbased_authentication == 1) {
1587 			L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1588 			L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1589 			L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1590 			L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1591 			L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1592 			L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1593 			L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1594 			L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1595 			L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1596 			L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1597 		}
1598 	}
1599 
1600 	/* load options.identity_files */
1601 	load_public_identity_files(cinfo);
1602 
1603 	/* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1604 	if (options.identity_agent &&
1605 	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1606 		if (strcmp(options.identity_agent, "none") == 0) {
1607 			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1608 		} else {
1609 			cp = options.identity_agent;
1610 			/* legacy (limited) format */
1611 			if (cp[0] == '$' && cp[1] != '{') {
1612 				if (!valid_env_name(cp + 1)) {
1613 					fatal("Invalid IdentityAgent "
1614 					    "environment variable name %s", cp);
1615 				}
1616 				if ((p = getenv(cp + 1)) == NULL)
1617 					unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1618 				else
1619 					setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1620 			} else {
1621 				/* identity_agent specifies a path directly */
1622 				setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1623 			}
1624 		}
1625 	}
1626 
1627 	if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1628 		cp = options.forward_agent_sock_path;
1629 		if (cp[0] == '$') {
1630 			if (!valid_env_name(cp + 1)) {
1631 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1632 			}
1633 			if ((p = getenv(cp + 1)) != NULL)
1634 				forward_agent_sock_path = p;
1635 			else
1636 				options.forward_agent = 0;
1637 			free(cp);
1638 		} else {
1639 			forward_agent_sock_path = cp;
1640 		}
1641 	}
1642 
1643 	/* Expand ~ in known host file names. */
1644 	tilde_expand_paths(options.system_hostfiles,
1645 	    options.num_system_hostfiles);
1646 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1647 
1648 	ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1649 	ssh_signal(SIGCHLD, main_sigchld_handler);
1650 
1651 	/* Log into the remote system.  Never returns if the login fails. */
1652 	ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1653 	    options.port, pw, timeout_ms, cinfo);
1654 
1655 	if (ssh_packet_connection_is_on_socket(ssh)) {
1656 		verbose("Authenticated to %s ([%s]:%d).", host,
1657 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1658 	} else {
1659 		verbose("Authenticated to %s (via proxy).", host);
1660 	}
1661 
1662 	/* We no longer need the private host keys.  Clear them now. */
1663 	if (sensitive_data.nkeys != 0) {
1664 		for (i = 0; i < sensitive_data.nkeys; i++) {
1665 			if (sensitive_data.keys[i] != NULL) {
1666 				/* Destroys contents safely */
1667 				debug3("clear hostkey %d", i);
1668 				sshkey_free(sensitive_data.keys[i]);
1669 				sensitive_data.keys[i] = NULL;
1670 			}
1671 		}
1672 		free(sensitive_data.keys);
1673 	}
1674 	for (i = 0; i < options.num_identity_files; i++) {
1675 		free(options.identity_files[i]);
1676 		options.identity_files[i] = NULL;
1677 		if (options.identity_keys[i]) {
1678 			sshkey_free(options.identity_keys[i]);
1679 			options.identity_keys[i] = NULL;
1680 		}
1681 	}
1682 	for (i = 0; i < options.num_certificate_files; i++) {
1683 		free(options.certificate_files[i]);
1684 		options.certificate_files[i] = NULL;
1685 	}
1686 
1687  skip_connect:
1688 	exit_status = ssh_session2(ssh, cinfo);
1689 	ssh_conn_info_free(cinfo);
1690 	ssh_packet_close(ssh);
1691 
1692 	if (options.control_path != NULL && muxserver_sock != -1)
1693 		unlink(options.control_path);
1694 
1695 	/* Kill ProxyCommand if it is running. */
1696 	ssh_kill_proxy_command();
1697 
1698 	return exit_status;
1699 }
1700 
1701 static void
1702 control_persist_detach(void)
1703 {
1704 	pid_t pid;
1705 
1706 	debug_f("backgrounding master process");
1707 
1708 	/*
1709 	 * master (current process) into the background, and make the
1710 	 * foreground process a client of the backgrounded master.
1711 	 */
1712 	switch ((pid = fork())) {
1713 	case -1:
1714 		fatal_f("fork: %s", strerror(errno));
1715 	case 0:
1716 		/* Child: master process continues mainloop */
1717 		break;
1718 	default:
1719 		/* Parent: set up mux client to connect to backgrounded master */
1720 		debug2_f("background process is %ld", (long)pid);
1721 		stdin_null_flag = ostdin_null_flag;
1722 		options.request_tty = orequest_tty;
1723 		tty_flag = otty_flag;
1724 		close(muxserver_sock);
1725 		muxserver_sock = -1;
1726 		options.control_master = SSHCTL_MASTER_NO;
1727 		muxclient(options.control_path);
1728 		/* muxclient() doesn't return on success. */
1729 		fatal("Failed to connect to new control master");
1730 	}
1731 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1732 		error_f("stdfd_devnull failed");
1733 	daemon(1, 1);
1734 	setproctitle("%s [mux]", options.control_path);
1735 }
1736 
1737 /* Do fork() after authentication. Used by "ssh -f" */
1738 static void
1739 fork_postauth(void)
1740 {
1741 	if (need_controlpersist_detach)
1742 		control_persist_detach();
1743 	debug("forking to background");
1744 	fork_after_authentication_flag = 0;
1745 	if (daemon(1, 1) == -1)
1746 		fatal("daemon() failed: %.200s", strerror(errno));
1747 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1748 		error_f("stdfd_devnull failed");
1749 }
1750 
1751 static void
1752 forwarding_success(void)
1753 {
1754 	if (forward_confirms_pending == -1)
1755 		return;
1756 	if (--forward_confirms_pending == 0) {
1757 		debug_f("all expected forwarding replies received");
1758 		if (fork_after_authentication_flag)
1759 			fork_postauth();
1760 	} else {
1761 		debug2_f("%d expected forwarding replies remaining",
1762 		    forward_confirms_pending);
1763 	}
1764 }
1765 
1766 /* Callback for remote forward global requests */
1767 static void
1768 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1769 {
1770 	struct Forward *rfwd = (struct Forward *)ctxt;
1771 	u_int port;
1772 	int r;
1773 
1774 	/* XXX verbose() on failure? */
1775 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1776 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1777 	    rfwd->listen_path ? rfwd->listen_path :
1778 	    rfwd->listen_host ? rfwd->listen_host : "",
1779 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1780 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1781 	    rfwd->connect_host, rfwd->connect_port);
1782 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1783 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1784 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1785 				fatal_fr(r, "parse packet");
1786 			if (port > 65535) {
1787 				error("Invalid allocated port %u for remote "
1788 				    "forward to %s:%d", port,
1789 				    rfwd->connect_host, rfwd->connect_port);
1790 				/* Ensure failure processing runs below */
1791 				type = SSH2_MSG_REQUEST_FAILURE;
1792 				channel_update_permission(ssh,
1793 				    rfwd->handle, -1);
1794 			} else {
1795 				rfwd->allocated_port = (int)port;
1796 				logit("Allocated port %u for remote "
1797 				    "forward to %s:%d",
1798 				    rfwd->allocated_port, rfwd->connect_host,
1799 				    rfwd->connect_port);
1800 				channel_update_permission(ssh,
1801 				    rfwd->handle, rfwd->allocated_port);
1802 			}
1803 		} else {
1804 			channel_update_permission(ssh, rfwd->handle, -1);
1805 		}
1806 	}
1807 
1808 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1809 		if (options.exit_on_forward_failure) {
1810 			if (rfwd->listen_path != NULL)
1811 				fatal("Error: remote port forwarding failed "
1812 				    "for listen path %s", rfwd->listen_path);
1813 			else
1814 				fatal("Error: remote port forwarding failed "
1815 				    "for listen port %d", rfwd->listen_port);
1816 		} else {
1817 			if (rfwd->listen_path != NULL)
1818 				logit("Warning: remote port forwarding failed "
1819 				    "for listen path %s", rfwd->listen_path);
1820 			else
1821 				logit("Warning: remote port forwarding failed "
1822 				    "for listen port %d", rfwd->listen_port);
1823 		}
1824 	}
1825 	forwarding_success();
1826 }
1827 
1828 static void
1829 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1830 {
1831 	debug("stdio forwarding: done");
1832 	cleanup_exit(0);
1833 }
1834 
1835 static void
1836 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1837 {
1838 	if (!success)
1839 		fatal("stdio forwarding failed");
1840 }
1841 
1842 static void
1843 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1844 {
1845 	if (!success) {
1846 		error("Tunnel forwarding failed");
1847 		if (options.exit_on_forward_failure)
1848 			cleanup_exit(255);
1849 	}
1850 
1851 	debug_f("tunnel forward established, id=%d", id);
1852 	forwarding_success();
1853 }
1854 
1855 static void
1856 ssh_init_stdio_forwarding(struct ssh *ssh)
1857 {
1858 	Channel *c;
1859 	int in, out;
1860 
1861 	if (options.stdio_forward_host == NULL)
1862 		return;
1863 
1864 	debug3_f("%s:%d", options.stdio_forward_host,
1865 	    options.stdio_forward_port);
1866 
1867 	if ((in = dup(STDIN_FILENO)) == -1 ||
1868 	    (out = dup(STDOUT_FILENO)) == -1)
1869 		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1870 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1871 	    options.stdio_forward_port, in, out)) == NULL)
1872 		fatal_f("channel_connect_stdio_fwd failed");
1873 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1874 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1875 }
1876 
1877 static void
1878 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1879 {
1880 	int success = 0;
1881 	int i;
1882 
1883 	if (options.exit_on_forward_failure)
1884 		forward_confirms_pending = 0; /* track pending requests */
1885 	/* Initiate local TCP/IP port forwardings. */
1886 	for (i = 0; i < options.num_local_forwards; i++) {
1887 		debug("Local connections to %.200s:%d forwarded to remote "
1888 		    "address %.200s:%d",
1889 		    (options.local_forwards[i].listen_path != NULL) ?
1890 		    options.local_forwards[i].listen_path :
1891 		    (options.local_forwards[i].listen_host == NULL) ?
1892 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1893 		    options.local_forwards[i].listen_host,
1894 		    options.local_forwards[i].listen_port,
1895 		    (options.local_forwards[i].connect_path != NULL) ?
1896 		    options.local_forwards[i].connect_path :
1897 		    options.local_forwards[i].connect_host,
1898 		    options.local_forwards[i].connect_port);
1899 		success += channel_setup_local_fwd_listener(ssh,
1900 		    &options.local_forwards[i], &options.fwd_opts);
1901 	}
1902 	if (i > 0 && success != i && options.exit_on_forward_failure)
1903 		fatal("Could not request local forwarding.");
1904 	if (i > 0 && success == 0)
1905 		error("Could not request local forwarding.");
1906 
1907 	/* Initiate remote TCP/IP port forwardings. */
1908 	for (i = 0; i < options.num_remote_forwards; i++) {
1909 		debug("Remote connections from %.200s:%d forwarded to "
1910 		    "local address %.200s:%d",
1911 		    (options.remote_forwards[i].listen_path != NULL) ?
1912 		    options.remote_forwards[i].listen_path :
1913 		    (options.remote_forwards[i].listen_host == NULL) ?
1914 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1915 		    options.remote_forwards[i].listen_port,
1916 		    (options.remote_forwards[i].connect_path != NULL) ?
1917 		    options.remote_forwards[i].connect_path :
1918 		    options.remote_forwards[i].connect_host,
1919 		    options.remote_forwards[i].connect_port);
1920 		if ((options.remote_forwards[i].handle =
1921 		    channel_request_remote_forwarding(ssh,
1922 		    &options.remote_forwards[i])) >= 0) {
1923 			client_register_global_confirm(
1924 			    ssh_confirm_remote_forward,
1925 			    &options.remote_forwards[i]);
1926 			forward_confirms_pending++;
1927 		} else if (options.exit_on_forward_failure)
1928 			fatal("Could not request remote forwarding.");
1929 		else
1930 			logit("Warning: Could not request remote forwarding.");
1931 	}
1932 
1933 	/* Initiate tunnel forwarding. */
1934 	if (options.tun_open != SSH_TUNMODE_NO) {
1935 		if ((*ifname = client_request_tun_fwd(ssh,
1936 		    options.tun_open, options.tun_local,
1937 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
1938 			forward_confirms_pending++;
1939 		else if (options.exit_on_forward_failure)
1940 			fatal("Could not request tunnel forwarding.");
1941 		else
1942 			error("Could not request tunnel forwarding.");
1943 	}
1944 	if (forward_confirms_pending > 0) {
1945 		debug_f("expecting replies for %d forwards",
1946 		    forward_confirms_pending);
1947 	}
1948 }
1949 
1950 static void
1951 check_agent_present(void)
1952 {
1953 	int r;
1954 
1955 	if (options.forward_agent) {
1956 		/* Clear agent forwarding if we don't have an agent. */
1957 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1958 			options.forward_agent = 0;
1959 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
1960 				debug_r(r, "ssh_get_authentication_socket");
1961 		}
1962 	}
1963 }
1964 
1965 static void
1966 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1967 {
1968 	extern char **environ;
1969 	const char *display;
1970 	int r, interactive = tty_flag;
1971 	char *proto = NULL, *data = NULL;
1972 
1973 	if (!success)
1974 		return; /* No need for error message, channels code sens one */
1975 
1976 	display = getenv("DISPLAY");
1977 	if (display == NULL && options.forward_x11)
1978 		debug("X11 forwarding requested but DISPLAY not set");
1979 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
1980 	    options.xauth_location, options.forward_x11_trusted,
1981 	    options.forward_x11_timeout, &proto, &data) == 0) {
1982 		/* Request forwarding with authentication spoofing. */
1983 		debug("Requesting X11 forwarding with authentication "
1984 		    "spoofing.");
1985 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1986 		    data, 1);
1987 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1988 		/* XXX exit_on_forward_failure */
1989 		interactive = 1;
1990 	}
1991 
1992 	check_agent_present();
1993 	if (options.forward_agent) {
1994 		debug("Requesting authentication agent forwarding.");
1995 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1996 		if ((r = sshpkt_send(ssh)) != 0)
1997 			fatal_fr(r, "send packet");
1998 	}
1999 
2000 	/* Tell the packet module whether this is an interactive session. */
2001 	ssh_packet_set_interactive(ssh, interactive,
2002 	    options.ip_qos_interactive, options.ip_qos_bulk);
2003 
2004 	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
2005 	    NULL, fileno(stdin), command, environ);
2006 }
2007 
2008 /* open new channel for a session */
2009 static int
2010 ssh_session2_open(struct ssh *ssh)
2011 {
2012 	Channel *c;
2013 	int window, packetmax, in, out, err;
2014 
2015 	if (stdin_null_flag) {
2016 		in = open(_PATH_DEVNULL, O_RDONLY);
2017 	} else {
2018 		in = dup(STDIN_FILENO);
2019 	}
2020 	out = dup(STDOUT_FILENO);
2021 	err = dup(STDERR_FILENO);
2022 
2023 	if (in == -1 || out == -1 || err == -1)
2024 		fatal("dup() in/out/err failed");
2025 
2026 	/* enable nonblocking unless tty */
2027 	if (!isatty(in))
2028 		set_nonblock(in);
2029 	if (!isatty(out))
2030 		set_nonblock(out);
2031 	if (!isatty(err))
2032 		set_nonblock(err);
2033 
2034 	window = CHAN_SES_WINDOW_DEFAULT;
2035 	packetmax = CHAN_SES_PACKET_DEFAULT;
2036 	if (tty_flag) {
2037 		window >>= 1;
2038 		packetmax >>= 1;
2039 	}
2040 	c = channel_new(ssh,
2041 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2042 	    window, packetmax, CHAN_EXTENDED_WRITE,
2043 	    "client-session", /*nonblock*/0);
2044 
2045 	debug3_f("channel_new: %d", c->self);
2046 
2047 	channel_send_open(ssh, c->self);
2048 	if (!no_shell_flag)
2049 		channel_register_open_confirm(ssh, c->self,
2050 		    ssh_session2_setup, NULL);
2051 
2052 	return c->self;
2053 }
2054 
2055 static int
2056 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2057 {
2058 	int r, id = -1;
2059 	char *cp, *tun_fwd_ifname = NULL;
2060 
2061 	/* XXX should be pre-session */
2062 	if (!options.control_persist)
2063 		ssh_init_stdio_forwarding(ssh);
2064 
2065 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2066 
2067 	if (options.local_command != NULL) {
2068 		debug3("expanding LocalCommand: %s", options.local_command);
2069 		cp = options.local_command;
2070 		options.local_command = percent_expand(cp,
2071 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2072 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2073 		    (char *)NULL);
2074 		debug3("expanded LocalCommand: %s", options.local_command);
2075 		free(cp);
2076 	}
2077 
2078 	/* Start listening for multiplex clients */
2079 	if (!ssh_packet_get_mux(ssh))
2080 		muxserver_listen(ssh);
2081 
2082 	/*
2083 	 * If we are in control persist mode and have a working mux listen
2084 	 * socket, then prepare to background ourselves and have a foreground
2085 	 * client attach as a control client.
2086 	 * NB. we must save copies of the flags that we override for
2087 	 * the backgrounding, since we defer attachment of the client until
2088 	 * after the connection is fully established (in particular,
2089 	 * async rfwd replies have been received for ExitOnForwardFailure).
2090 	 */
2091 	if (options.control_persist && muxserver_sock != -1) {
2092 		ostdin_null_flag = stdin_null_flag;
2093 		ono_shell_flag = no_shell_flag;
2094 		orequest_tty = options.request_tty;
2095 		otty_flag = tty_flag;
2096 		stdin_null_flag = 1;
2097 		no_shell_flag = 1;
2098 		tty_flag = 0;
2099 		if (!fork_after_authentication_flag)
2100 			need_controlpersist_detach = 1;
2101 		fork_after_authentication_flag = 1;
2102 	}
2103 	/*
2104 	 * ControlPersist mux listen socket setup failed, attempt the
2105 	 * stdio forward setup that we skipped earlier.
2106 	 */
2107 	if (options.control_persist && muxserver_sock == -1)
2108 		ssh_init_stdio_forwarding(ssh);
2109 
2110 	if (!no_shell_flag)
2111 		id = ssh_session2_open(ssh);
2112 	else {
2113 		ssh_packet_set_interactive(ssh,
2114 		    options.control_master == SSHCTL_MASTER_NO,
2115 		    options.ip_qos_interactive, options.ip_qos_bulk);
2116 	}
2117 
2118 	/* If we don't expect to open a new session, then disallow it */
2119 	if (options.control_master == SSHCTL_MASTER_NO &&
2120 	    (ssh->compat & SSH_NEW_OPENSSH)) {
2121 		debug("Requesting no-more-sessions@openssh.com");
2122 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2123 		    (r = sshpkt_put_cstring(ssh,
2124 		    "no-more-sessions@openssh.com")) != 0 ||
2125 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2126 		    (r = sshpkt_send(ssh)) != 0)
2127 			fatal_fr(r, "send packet");
2128 	}
2129 
2130 	/* Execute a local command */
2131 	if (options.local_command != NULL &&
2132 	    options.permit_local_command)
2133 		ssh_local_cmd(options.local_command);
2134 
2135 	/*
2136 	 * stdout is now owned by the session channel; clobber it here
2137 	 * so future channel closes are propagated to the local fd.
2138 	 * NB. this can only happen after LocalCommand has completed,
2139 	 * as it may want to write to stdout.
2140 	 */
2141 	if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2142 		error_f("stdfd_devnull failed");
2143 
2144 	/*
2145 	 * If requested and we are not interested in replies to remote
2146 	 * forwarding requests, then let ssh continue in the background.
2147 	 */
2148 	if (fork_after_authentication_flag) {
2149 		if (options.exit_on_forward_failure &&
2150 		    options.num_remote_forwards > 0) {
2151 			debug("deferring postauth fork until remote forward "
2152 			    "confirmation received");
2153 		} else
2154 			fork_postauth();
2155 	}
2156 
2157 	return client_loop(ssh, tty_flag, tty_flag ?
2158 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2159 }
2160 
2161 /* Loads all IdentityFile and CertificateFile keys */
2162 static void
2163 load_public_identity_files(const struct ssh_conn_info *cinfo)
2164 {
2165 	char *filename, *cp;
2166 	struct sshkey *public;
2167 	int i;
2168 	u_int n_ids, n_certs;
2169 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2170 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2171 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2172 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2173 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2174 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2175 #ifdef ENABLE_PKCS11
2176 	struct sshkey **keys = NULL;
2177 	char **comments = NULL;
2178 	int nkeys;
2179 #endif /* PKCS11 */
2180 
2181 	n_ids = n_certs = 0;
2182 	memset(identity_files, 0, sizeof(identity_files));
2183 	memset(identity_keys, 0, sizeof(identity_keys));
2184 	memset(identity_file_userprovided, 0,
2185 	    sizeof(identity_file_userprovided));
2186 	memset(certificate_files, 0, sizeof(certificate_files));
2187 	memset(certificates, 0, sizeof(certificates));
2188 	memset(certificate_file_userprovided, 0,
2189 	    sizeof(certificate_file_userprovided));
2190 
2191 #ifdef ENABLE_PKCS11
2192 	if (options.pkcs11_provider != NULL &&
2193 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2194 	    (pkcs11_init(!options.batch_mode) == 0) &&
2195 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2196 	    &keys, &comments)) > 0) {
2197 		for (i = 0; i < nkeys; i++) {
2198 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2199 				sshkey_free(keys[i]);
2200 				free(comments[i]);
2201 				continue;
2202 			}
2203 			identity_keys[n_ids] = keys[i];
2204 			identity_files[n_ids] = comments[i]; /* transferred */
2205 			n_ids++;
2206 		}
2207 		free(keys);
2208 		free(comments);
2209 	}
2210 #endif /* ENABLE_PKCS11 */
2211 	for (i = 0; i < options.num_identity_files; i++) {
2212 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2213 		    strcasecmp(options.identity_files[i], "none") == 0) {
2214 			free(options.identity_files[i]);
2215 			options.identity_files[i] = NULL;
2216 			continue;
2217 		}
2218 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2219 		filename = default_client_percent_dollar_expand(cp, cinfo);
2220 		free(cp);
2221 		check_load(sshkey_load_public(filename, &public, NULL),
2222 		    filename, "pubkey");
2223 		debug("identity file %s type %d", filename,
2224 		    public ? public->type : -1);
2225 		free(options.identity_files[i]);
2226 		identity_files[n_ids] = filename;
2227 		identity_keys[n_ids] = public;
2228 		identity_file_userprovided[n_ids] =
2229 		    options.identity_file_userprovided[i];
2230 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2231 			continue;
2232 
2233 		/*
2234 		 * If no certificates have been explicitly listed then try
2235 		 * to add the default certificate variant too.
2236 		 */
2237 		if (options.num_certificate_files != 0)
2238 			continue;
2239 		xasprintf(&cp, "%s-cert", filename);
2240 		check_load(sshkey_load_public(cp, &public, NULL),
2241 		    filename, "pubkey");
2242 		debug("identity file %s type %d", cp,
2243 		    public ? public->type : -1);
2244 		if (public == NULL) {
2245 			free(cp);
2246 			continue;
2247 		}
2248 		if (!sshkey_is_cert(public)) {
2249 			debug_f("key %s type %s is not a certificate",
2250 			    cp, sshkey_type(public));
2251 			sshkey_free(public);
2252 			free(cp);
2253 			continue;
2254 		}
2255 		/* NB. leave filename pointing to private key */
2256 		identity_files[n_ids] = xstrdup(filename);
2257 		identity_keys[n_ids] = public;
2258 		identity_file_userprovided[n_ids] =
2259 		    options.identity_file_userprovided[i];
2260 		n_ids++;
2261 	}
2262 
2263 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2264 		fatal_f("too many certificates");
2265 	for (i = 0; i < options.num_certificate_files; i++) {
2266 		cp = tilde_expand_filename(options.certificate_files[i],
2267 		    getuid());
2268 		filename = default_client_percent_dollar_expand(cp, cinfo);
2269 		free(cp);
2270 
2271 		check_load(sshkey_load_public(filename, &public, NULL),
2272 		    filename, "certificate");
2273 		debug("certificate file %s type %d", filename,
2274 		    public ? public->type : -1);
2275 		free(options.certificate_files[i]);
2276 		options.certificate_files[i] = NULL;
2277 		if (public == NULL) {
2278 			free(filename);
2279 			continue;
2280 		}
2281 		if (!sshkey_is_cert(public)) {
2282 			debug_f("key %s type %s is not a certificate",
2283 			    filename, sshkey_type(public));
2284 			sshkey_free(public);
2285 			free(filename);
2286 			continue;
2287 		}
2288 		certificate_files[n_certs] = filename;
2289 		certificates[n_certs] = public;
2290 		certificate_file_userprovided[n_certs] =
2291 		    options.certificate_file_userprovided[i];
2292 		++n_certs;
2293 	}
2294 
2295 	options.num_identity_files = n_ids;
2296 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2297 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2298 	memcpy(options.identity_file_userprovided,
2299 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2300 
2301 	options.num_certificate_files = n_certs;
2302 	memcpy(options.certificate_files,
2303 	    certificate_files, sizeof(certificate_files));
2304 	memcpy(options.certificates, certificates, sizeof(certificates));
2305 	memcpy(options.certificate_file_userprovided,
2306 	    certificate_file_userprovided,
2307 	    sizeof(certificate_file_userprovided));
2308 }
2309 
2310 static void
2311 main_sigchld_handler(int sig)
2312 {
2313 	int save_errno = errno;
2314 	pid_t pid;
2315 	int status;
2316 
2317 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2318 	    (pid == -1 && errno == EINTR))
2319 		;
2320 	errno = save_errno;
2321 }
2322