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