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