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