xref: /openssh-portable/ssh.c (revision ed833da1)
1 /* $OpenBSD: ssh.c,v 1.522 2020/04/03 02:27:12 dtucker Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Ssh client program.  This program can be used to log into a remote machine.
7  * The software supports strong authentication, encryption, and forwarding
8  * of X11, TCP/IP, and authentication connections.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18  *
19  * Modified to work with 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 remote_forward_confirms_received = 0;
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 		if (cp[0] == '$') {
1547 			if (!valid_env_name(cp + 1)) {
1548 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1549 			}
1550 			if ((p = getenv(cp + 1)) != NULL)
1551 				forward_agent_sock_path = p;
1552 			else
1553 				options.forward_agent = 0;
1554 			free(cp);
1555 		} else {
1556 			forward_agent_sock_path = cp;
1557 		}
1558 	}
1559 
1560 	/* Expand ~ in known host file names. */
1561 	tilde_expand_paths(options.system_hostfiles,
1562 	    options.num_system_hostfiles);
1563 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1564 
1565 	ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1566 	ssh_signal(SIGCHLD, main_sigchld_handler);
1567 
1568 	/* Log into the remote system.  Never returns if the login fails. */
1569 	ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1570 	    options.port, pw, timeout_ms);
1571 
1572 	if (ssh_packet_connection_is_on_socket(ssh)) {
1573 		verbose("Authenticated to %s ([%s]:%d).", host,
1574 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1575 	} else {
1576 		verbose("Authenticated to %s (via proxy).", host);
1577 	}
1578 
1579 	/* We no longer need the private host keys.  Clear them now. */
1580 	if (sensitive_data.nkeys != 0) {
1581 		for (i = 0; i < sensitive_data.nkeys; i++) {
1582 			if (sensitive_data.keys[i] != NULL) {
1583 				/* Destroys contents safely */
1584 				debug3("clear hostkey %d", i);
1585 				sshkey_free(sensitive_data.keys[i]);
1586 				sensitive_data.keys[i] = NULL;
1587 			}
1588 		}
1589 		free(sensitive_data.keys);
1590 	}
1591 	for (i = 0; i < options.num_identity_files; i++) {
1592 		free(options.identity_files[i]);
1593 		options.identity_files[i] = NULL;
1594 		if (options.identity_keys[i]) {
1595 			sshkey_free(options.identity_keys[i]);
1596 			options.identity_keys[i] = NULL;
1597 		}
1598 	}
1599 	for (i = 0; i < options.num_certificate_files; i++) {
1600 		free(options.certificate_files[i]);
1601 		options.certificate_files[i] = NULL;
1602 	}
1603 
1604  skip_connect:
1605 	exit_status = ssh_session2(ssh, pw);
1606 	ssh_packet_close(ssh);
1607 
1608 	if (options.control_path != NULL && muxserver_sock != -1)
1609 		unlink(options.control_path);
1610 
1611 	/* Kill ProxyCommand if it is running. */
1612 	ssh_kill_proxy_command();
1613 
1614 	return exit_status;
1615 }
1616 
1617 static void
1618 control_persist_detach(void)
1619 {
1620 	pid_t pid;
1621 	int devnull, keep_stderr;
1622 
1623 	debug("%s: backgrounding master process", __func__);
1624 
1625 	/*
1626 	 * master (current process) into the background, and make the
1627 	 * foreground process a client of the backgrounded master.
1628 	 */
1629 	switch ((pid = fork())) {
1630 	case -1:
1631 		fatal("%s: fork: %s", __func__, strerror(errno));
1632 	case 0:
1633 		/* Child: master process continues mainloop */
1634 		break;
1635 	default:
1636 		/* Parent: set up mux slave to connect to backgrounded master */
1637 		debug2("%s: background process is %ld", __func__, (long)pid);
1638 		stdin_null_flag = ostdin_null_flag;
1639 		options.request_tty = orequest_tty;
1640 		tty_flag = otty_flag;
1641 		close(muxserver_sock);
1642 		muxserver_sock = -1;
1643 		options.control_master = SSHCTL_MASTER_NO;
1644 		muxclient(options.control_path);
1645 		/* muxclient() doesn't return on success. */
1646 		fatal("Failed to connect to new control master");
1647 	}
1648 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1649 		error("%s: open(\"/dev/null\"): %s", __func__,
1650 		    strerror(errno));
1651 	} else {
1652 		keep_stderr = log_is_on_stderr() && debug_flag;
1653 		if (dup2(devnull, STDIN_FILENO) == -1 ||
1654 		    dup2(devnull, STDOUT_FILENO) == -1 ||
1655 		    (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1656 			error("%s: dup2: %s", __func__, strerror(errno));
1657 		if (devnull > STDERR_FILENO)
1658 			close(devnull);
1659 	}
1660 	daemon(1, 1);
1661 	setproctitle("%s [mux]", options.control_path);
1662 }
1663 
1664 /* Do fork() after authentication. Used by "ssh -f" */
1665 static void
1666 fork_postauth(void)
1667 {
1668 	if (need_controlpersist_detach)
1669 		control_persist_detach();
1670 	debug("forking to background");
1671 	fork_after_authentication_flag = 0;
1672 	if (daemon(1, 1) == -1)
1673 		fatal("daemon() failed: %.200s", strerror(errno));
1674 }
1675 
1676 /* Callback for remote forward global requests */
1677 static void
1678 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1679 {
1680 	struct Forward *rfwd = (struct Forward *)ctxt;
1681 	u_int port;
1682 	int r;
1683 
1684 	/* XXX verbose() on failure? */
1685 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1686 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1687 	    rfwd->listen_path ? rfwd->listen_path :
1688 	    rfwd->listen_host ? rfwd->listen_host : "",
1689 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1690 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1691 	    rfwd->connect_host, rfwd->connect_port);
1692 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1693 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1694 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1695 				fatal("%s: %s", __func__, ssh_err(r));
1696 			if (port > 65535) {
1697 				error("Invalid allocated port %u for remote "
1698 				    "forward to %s:%d", port,
1699 				    rfwd->connect_host, rfwd->connect_port);
1700 				/* Ensure failure processing runs below */
1701 				type = SSH2_MSG_REQUEST_FAILURE;
1702 				channel_update_permission(ssh,
1703 				    rfwd->handle, -1);
1704 			} else {
1705 				rfwd->allocated_port = (int)port;
1706 				logit("Allocated port %u for remote "
1707 				    "forward to %s:%d",
1708 				    rfwd->allocated_port, rfwd->connect_host,
1709 				    rfwd->connect_port);
1710 				channel_update_permission(ssh,
1711 				    rfwd->handle, rfwd->allocated_port);
1712 			}
1713 		} else {
1714 			channel_update_permission(ssh, rfwd->handle, -1);
1715 		}
1716 	}
1717 
1718 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1719 		if (options.exit_on_forward_failure) {
1720 			if (rfwd->listen_path != NULL)
1721 				fatal("Error: remote port forwarding failed "
1722 				    "for listen path %s", rfwd->listen_path);
1723 			else
1724 				fatal("Error: remote port forwarding failed "
1725 				    "for listen port %d", rfwd->listen_port);
1726 		} else {
1727 			if (rfwd->listen_path != NULL)
1728 				logit("Warning: remote port forwarding failed "
1729 				    "for listen path %s", rfwd->listen_path);
1730 			else
1731 				logit("Warning: remote port forwarding failed "
1732 				    "for listen port %d", rfwd->listen_port);
1733 		}
1734 	}
1735 	if (++remote_forward_confirms_received == options.num_remote_forwards) {
1736 		debug("All remote forwarding requests processed");
1737 		if (fork_after_authentication_flag)
1738 			fork_postauth();
1739 	}
1740 }
1741 
1742 static void
1743 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1744 {
1745 	debug("stdio forwarding: done");
1746 	cleanup_exit(0);
1747 }
1748 
1749 static void
1750 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1751 {
1752 	if (!success)
1753 		fatal("stdio forwarding failed");
1754 }
1755 
1756 static void
1757 ssh_init_stdio_forwarding(struct ssh *ssh)
1758 {
1759 	Channel *c;
1760 	int in, out;
1761 
1762 	if (options.stdio_forward_host == NULL)
1763 		return;
1764 
1765 	debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1766 	    options.stdio_forward_port);
1767 
1768 	if ((in = dup(STDIN_FILENO)) == -1 ||
1769 	    (out = dup(STDOUT_FILENO)) == -1)
1770 		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1771 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1772 	    options.stdio_forward_port, in, out)) == NULL)
1773 		fatal("%s: channel_connect_stdio_fwd failed", __func__);
1774 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1775 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1776 }
1777 
1778 static void
1779 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1780 {
1781 	int success = 0;
1782 	int i;
1783 
1784 	/* Initiate local TCP/IP port forwardings. */
1785 	for (i = 0; i < options.num_local_forwards; i++) {
1786 		debug("Local connections to %.200s:%d forwarded to remote "
1787 		    "address %.200s:%d",
1788 		    (options.local_forwards[i].listen_path != NULL) ?
1789 		    options.local_forwards[i].listen_path :
1790 		    (options.local_forwards[i].listen_host == NULL) ?
1791 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1792 		    options.local_forwards[i].listen_host,
1793 		    options.local_forwards[i].listen_port,
1794 		    (options.local_forwards[i].connect_path != NULL) ?
1795 		    options.local_forwards[i].connect_path :
1796 		    options.local_forwards[i].connect_host,
1797 		    options.local_forwards[i].connect_port);
1798 		success += channel_setup_local_fwd_listener(ssh,
1799 		    &options.local_forwards[i], &options.fwd_opts);
1800 	}
1801 	if (i > 0 && success != i && options.exit_on_forward_failure)
1802 		fatal("Could not request local forwarding.");
1803 	if (i > 0 && success == 0)
1804 		error("Could not request local forwarding.");
1805 
1806 	/* Initiate remote TCP/IP port forwardings. */
1807 	for (i = 0; i < options.num_remote_forwards; i++) {
1808 		debug("Remote connections from %.200s:%d forwarded to "
1809 		    "local address %.200s:%d",
1810 		    (options.remote_forwards[i].listen_path != NULL) ?
1811 		    options.remote_forwards[i].listen_path :
1812 		    (options.remote_forwards[i].listen_host == NULL) ?
1813 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1814 		    options.remote_forwards[i].listen_port,
1815 		    (options.remote_forwards[i].connect_path != NULL) ?
1816 		    options.remote_forwards[i].connect_path :
1817 		    options.remote_forwards[i].connect_host,
1818 		    options.remote_forwards[i].connect_port);
1819 		options.remote_forwards[i].handle =
1820 		    channel_request_remote_forwarding(ssh,
1821 		    &options.remote_forwards[i]);
1822 		if (options.remote_forwards[i].handle < 0) {
1823 			if (options.exit_on_forward_failure)
1824 				fatal("Could not request remote forwarding.");
1825 			else
1826 				logit("Warning: Could not request remote "
1827 				    "forwarding.");
1828 		} else {
1829 			client_register_global_confirm(
1830 			    ssh_confirm_remote_forward,
1831 			    &options.remote_forwards[i]);
1832 		}
1833 	}
1834 
1835 	/* Initiate tunnel forwarding. */
1836 	if (options.tun_open != SSH_TUNMODE_NO) {
1837 		if ((*ifname = client_request_tun_fwd(ssh,
1838 		    options.tun_open, options.tun_local,
1839 		    options.tun_remote)) == NULL) {
1840 			if (options.exit_on_forward_failure)
1841 				fatal("Could not request tunnel forwarding.");
1842 			else
1843 				error("Could not request tunnel forwarding.");
1844 		}
1845 	}
1846 }
1847 
1848 static void
1849 check_agent_present(void)
1850 {
1851 	int r;
1852 
1853 	if (options.forward_agent) {
1854 		/* Clear agent forwarding if we don't have an agent. */
1855 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1856 			options.forward_agent = 0;
1857 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
1858 				debug("ssh_get_authentication_socket: %s",
1859 				    ssh_err(r));
1860 		}
1861 	}
1862 }
1863 
1864 static void
1865 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1866 {
1867 	extern char **environ;
1868 	const char *display;
1869 	int r, interactive = tty_flag;
1870 	char *proto = NULL, *data = NULL;
1871 
1872 	if (!success)
1873 		return; /* No need for error message, channels code sens one */
1874 
1875 	display = getenv("DISPLAY");
1876 	if (display == NULL && options.forward_x11)
1877 		debug("X11 forwarding requested but DISPLAY not set");
1878 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
1879 	    options.xauth_location, options.forward_x11_trusted,
1880 	    options.forward_x11_timeout, &proto, &data) == 0) {
1881 		/* Request forwarding with authentication spoofing. */
1882 		debug("Requesting X11 forwarding with authentication "
1883 		    "spoofing.");
1884 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1885 		    data, 1);
1886 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1887 		/* XXX exit_on_forward_failure */
1888 		interactive = 1;
1889 	}
1890 
1891 	check_agent_present();
1892 	if (options.forward_agent) {
1893 		debug("Requesting authentication agent forwarding.");
1894 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1895 		if ((r = sshpkt_send(ssh)) != 0)
1896 			fatal("%s: %s", __func__, ssh_err(r));
1897 	}
1898 
1899 	/* Tell the packet module whether this is an interactive session. */
1900 	ssh_packet_set_interactive(ssh, interactive,
1901 	    options.ip_qos_interactive, options.ip_qos_bulk);
1902 
1903 	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
1904 	    NULL, fileno(stdin), command, environ);
1905 }
1906 
1907 /* open new channel for a session */
1908 static int
1909 ssh_session2_open(struct ssh *ssh)
1910 {
1911 	Channel *c;
1912 	int window, packetmax, in, out, err;
1913 
1914 	if (stdin_null_flag) {
1915 		in = open(_PATH_DEVNULL, O_RDONLY);
1916 	} else {
1917 		in = dup(STDIN_FILENO);
1918 	}
1919 	out = dup(STDOUT_FILENO);
1920 	err = dup(STDERR_FILENO);
1921 
1922 	if (in == -1 || out == -1 || err == -1)
1923 		fatal("dup() in/out/err failed");
1924 
1925 	/* enable nonblocking unless tty */
1926 	if (!isatty(in))
1927 		set_nonblock(in);
1928 	if (!isatty(out))
1929 		set_nonblock(out);
1930 	if (!isatty(err))
1931 		set_nonblock(err);
1932 
1933 	window = CHAN_SES_WINDOW_DEFAULT;
1934 	packetmax = CHAN_SES_PACKET_DEFAULT;
1935 	if (tty_flag) {
1936 		window >>= 1;
1937 		packetmax >>= 1;
1938 	}
1939 	c = channel_new(ssh,
1940 	    "session", SSH_CHANNEL_OPENING, in, out, err,
1941 	    window, packetmax, CHAN_EXTENDED_WRITE,
1942 	    "client-session", /*nonblock*/0);
1943 
1944 	debug3("%s: channel_new: %d", __func__, c->self);
1945 
1946 	channel_send_open(ssh, c->self);
1947 	if (!no_shell_flag)
1948 		channel_register_open_confirm(ssh, c->self,
1949 		    ssh_session2_setup, NULL);
1950 
1951 	return c->self;
1952 }
1953 
1954 static int
1955 ssh_session2(struct ssh *ssh, struct passwd *pw)
1956 {
1957 	int r, devnull, id = -1;
1958 	char *cp, *tun_fwd_ifname = NULL;
1959 
1960 	/* XXX should be pre-session */
1961 	if (!options.control_persist)
1962 		ssh_init_stdio_forwarding(ssh);
1963 
1964 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
1965 
1966 	if (options.local_command != NULL) {
1967 		debug3("expanding LocalCommand: %s", options.local_command);
1968 		cp = options.local_command;
1969 		options.local_command = percent_expand(cp,
1970 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS,
1971 		    "d", pw->pw_dir,
1972 		    "h", host,
1973 		    "r", options.user,
1974 		    "u", pw->pw_name,
1975 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
1976 		    (char *)NULL);
1977 		debug3("expanded LocalCommand: %s", options.local_command);
1978 		free(cp);
1979 	}
1980 
1981 	/* Start listening for multiplex clients */
1982 	if (!ssh_packet_get_mux(ssh))
1983 		muxserver_listen(ssh);
1984 
1985 	/*
1986 	 * If we are in control persist mode and have a working mux listen
1987 	 * socket, then prepare to background ourselves and have a foreground
1988 	 * client attach as a control slave.
1989 	 * NB. we must save copies of the flags that we override for
1990 	 * the backgrounding, since we defer attachment of the slave until
1991 	 * after the connection is fully established (in particular,
1992 	 * async rfwd replies have been received for ExitOnForwardFailure).
1993 	 */
1994 	if (options.control_persist && muxserver_sock != -1) {
1995 		ostdin_null_flag = stdin_null_flag;
1996 		ono_shell_flag = no_shell_flag;
1997 		orequest_tty = options.request_tty;
1998 		otty_flag = tty_flag;
1999 		stdin_null_flag = 1;
2000 		no_shell_flag = 1;
2001 		tty_flag = 0;
2002 		if (!fork_after_authentication_flag)
2003 			need_controlpersist_detach = 1;
2004 		fork_after_authentication_flag = 1;
2005 	}
2006 	/*
2007 	 * ControlPersist mux listen socket setup failed, attempt the
2008 	 * stdio forward setup that we skipped earlier.
2009 	 */
2010 	if (options.control_persist && muxserver_sock == -1)
2011 		ssh_init_stdio_forwarding(ssh);
2012 
2013 	if (!no_shell_flag)
2014 		id = ssh_session2_open(ssh);
2015 	else {
2016 		ssh_packet_set_interactive(ssh,
2017 		    options.control_master == SSHCTL_MASTER_NO,
2018 		    options.ip_qos_interactive, options.ip_qos_bulk);
2019 	}
2020 
2021 	/* If we don't expect to open a new session, then disallow it */
2022 	if (options.control_master == SSHCTL_MASTER_NO &&
2023 	    (datafellows & SSH_NEW_OPENSSH)) {
2024 		debug("Requesting no-more-sessions@openssh.com");
2025 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2026 		    (r = sshpkt_put_cstring(ssh,
2027 		    "no-more-sessions@openssh.com")) != 0 ||
2028 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2029 		    (r = sshpkt_send(ssh)) != 0)
2030 			fatal("%s: %s", __func__, ssh_err(r));
2031 	}
2032 
2033 	/* Execute a local command */
2034 	if (options.local_command != NULL &&
2035 	    options.permit_local_command)
2036 		ssh_local_cmd(options.local_command);
2037 
2038 	/*
2039 	 * stdout is now owned by the session channel; clobber it here
2040 	 * so future channel closes are propagated to the local fd.
2041 	 * NB. this can only happen after LocalCommand has completed,
2042 	 * as it may want to write to stdout.
2043 	 */
2044 	if (!need_controlpersist_detach) {
2045 		if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1)
2046 			error("%s: open %s: %s", __func__,
2047 			    _PATH_DEVNULL, strerror(errno));
2048 		if (dup2(devnull, STDOUT_FILENO) == -1)
2049 			fatal("%s: dup2() stdout failed", __func__);
2050 		if (devnull > STDERR_FILENO)
2051 			close(devnull);
2052 	}
2053 
2054 	/*
2055 	 * If requested and we are not interested in replies to remote
2056 	 * forwarding requests, then let ssh continue in the background.
2057 	 */
2058 	if (fork_after_authentication_flag) {
2059 		if (options.exit_on_forward_failure &&
2060 		    options.num_remote_forwards > 0) {
2061 			debug("deferring postauth fork until remote forward "
2062 			    "confirmation received");
2063 		} else
2064 			fork_postauth();
2065 	}
2066 
2067 	return client_loop(ssh, tty_flag, tty_flag ?
2068 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2069 }
2070 
2071 /* Loads all IdentityFile and CertificateFile keys */
2072 static void
2073 load_public_identity_files(struct passwd *pw)
2074 {
2075 	char *filename, *cp;
2076 	struct sshkey *public;
2077 	int i;
2078 	u_int n_ids, n_certs;
2079 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2080 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2081 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2082 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2083 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2084 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2085 #ifdef ENABLE_PKCS11
2086 	struct sshkey **keys = NULL;
2087 	char **comments = NULL;
2088 	int nkeys;
2089 #endif /* PKCS11 */
2090 
2091 	n_ids = n_certs = 0;
2092 	memset(identity_files, 0, sizeof(identity_files));
2093 	memset(identity_keys, 0, sizeof(identity_keys));
2094 	memset(identity_file_userprovided, 0,
2095 	    sizeof(identity_file_userprovided));
2096 	memset(certificate_files, 0, sizeof(certificate_files));
2097 	memset(certificates, 0, sizeof(certificates));
2098 	memset(certificate_file_userprovided, 0,
2099 	    sizeof(certificate_file_userprovided));
2100 
2101 #ifdef ENABLE_PKCS11
2102 	if (options.pkcs11_provider != NULL &&
2103 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2104 	    (pkcs11_init(!options.batch_mode) == 0) &&
2105 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2106 	    &keys, &comments)) > 0) {
2107 		for (i = 0; i < nkeys; i++) {
2108 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2109 				sshkey_free(keys[i]);
2110 				free(comments[i]);
2111 				continue;
2112 			}
2113 			identity_keys[n_ids] = keys[i];
2114 			identity_files[n_ids] = comments[i]; /* transferred */
2115 			n_ids++;
2116 		}
2117 		free(keys);
2118 		free(comments);
2119 	}
2120 #endif /* ENABLE_PKCS11 */
2121 	for (i = 0; i < options.num_identity_files; i++) {
2122 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2123 		    strcasecmp(options.identity_files[i], "none") == 0) {
2124 			free(options.identity_files[i]);
2125 			options.identity_files[i] = NULL;
2126 			continue;
2127 		}
2128 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2129 		filename = percent_expand(cp,
2130 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS,
2131 		    "d", pw->pw_dir,
2132 		    "h", host,
2133 		    "r", options.user,
2134 		    "u", pw->pw_name,
2135 		    (char *)NULL);
2136 		free(cp);
2137 		check_load(sshkey_load_public(filename, &public, NULL),
2138 		    filename, "pubkey");
2139 		debug("identity file %s type %d", filename,
2140 		    public ? public->type : -1);
2141 		free(options.identity_files[i]);
2142 		identity_files[n_ids] = filename;
2143 		identity_keys[n_ids] = public;
2144 		identity_file_userprovided[n_ids] =
2145 		    options.identity_file_userprovided[i];
2146 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2147 			continue;
2148 
2149 		/*
2150 		 * If no certificates have been explicitly listed then try
2151 		 * to add the default certificate variant too.
2152 		 */
2153 		if (options.num_certificate_files != 0)
2154 			continue;
2155 		xasprintf(&cp, "%s-cert", filename);
2156 		check_load(sshkey_load_public(cp, &public, NULL),
2157 		    filename, "pubkey");
2158 		debug("identity file %s type %d", cp,
2159 		    public ? public->type : -1);
2160 		if (public == NULL) {
2161 			free(cp);
2162 			continue;
2163 		}
2164 		if (!sshkey_is_cert(public)) {
2165 			debug("%s: key %s type %s is not a certificate",
2166 			    __func__, cp, sshkey_type(public));
2167 			sshkey_free(public);
2168 			free(cp);
2169 			continue;
2170 		}
2171 		/* NB. leave filename pointing to private key */
2172 		identity_files[n_ids] = xstrdup(filename);
2173 		identity_keys[n_ids] = public;
2174 		identity_file_userprovided[n_ids] =
2175 		    options.identity_file_userprovided[i];
2176 		n_ids++;
2177 	}
2178 
2179 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2180 		fatal("%s: too many certificates", __func__);
2181 	for (i = 0; i < options.num_certificate_files; i++) {
2182 		cp = tilde_expand_filename(options.certificate_files[i],
2183 		    getuid());
2184 		filename = percent_expand(cp,
2185 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS,
2186 		    "d", pw->pw_dir,
2187 		    "h", host,
2188 		    "r", options.user,
2189 		    "u", pw->pw_name,
2190 		    (char *)NULL);
2191 		free(cp);
2192 
2193 		check_load(sshkey_load_public(filename, &public, NULL),
2194 		    filename, "certificate");
2195 		debug("certificate file %s type %d", filename,
2196 		    public ? public->type : -1);
2197 		free(options.certificate_files[i]);
2198 		options.certificate_files[i] = NULL;
2199 		if (public == NULL) {
2200 			free(filename);
2201 			continue;
2202 		}
2203 		if (!sshkey_is_cert(public)) {
2204 			debug("%s: key %s type %s is not a certificate",
2205 			    __func__, filename, sshkey_type(public));
2206 			sshkey_free(public);
2207 			free(filename);
2208 			continue;
2209 		}
2210 		certificate_files[n_certs] = filename;
2211 		certificates[n_certs] = public;
2212 		certificate_file_userprovided[n_certs] =
2213 		    options.certificate_file_userprovided[i];
2214 		++n_certs;
2215 	}
2216 
2217 	options.num_identity_files = n_ids;
2218 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2219 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2220 	memcpy(options.identity_file_userprovided,
2221 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2222 
2223 	options.num_certificate_files = n_certs;
2224 	memcpy(options.certificate_files,
2225 	    certificate_files, sizeof(certificate_files));
2226 	memcpy(options.certificates, certificates, sizeof(certificates));
2227 	memcpy(options.certificate_file_userprovided,
2228 	    certificate_file_userprovided,
2229 	    sizeof(certificate_file_userprovided));
2230 }
2231 
2232 static void
2233 main_sigchld_handler(int sig)
2234 {
2235 	int save_errno = errno;
2236 	pid_t pid;
2237 	int status;
2238 
2239 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2240 	    (pid == -1 && errno == EINTR))
2241 		;
2242 	errno = save_errno;
2243 }
2244