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