xref: /freebsd/crypto/openssh/ssh.c (revision 00698711dee1d990d3db9c41bf58394e589eecfe)
1 /* $OpenBSD: ssh.c,v 1.569 2021/09/20 04:02:13 dtucker Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Ssh client program.  This program can be used to log into a remote machine.
7  * The software supports strong authentication, encryption, and forwarding
8  * of X11, TCP/IP, and authentication connections.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18  *
19  * Modified to work with SSLeay by Niels Provos <provos@citi.umich.edu>
20  * in Canada (German citizen).
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the above copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41  */
42 
43 #include "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) {
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" argumment 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 		tty_flag = 0;
1355 	/* Do not allocate a tty if stdin is not a tty. */
1356 	if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1357 	    options.request_tty != REQUEST_TTY_FORCE) {
1358 		if (tty_flag)
1359 			logit("Pseudo-terminal will not be allocated because "
1360 			    "stdin is not a terminal.");
1361 		tty_flag = 0;
1362 	}
1363 
1364 	/* Set up strings used to percent_expand() arguments */
1365 	cinfo = xcalloc(1, sizeof(*cinfo));
1366 	if (gethostname(thishost, sizeof(thishost)) == -1)
1367 		fatal("gethostname: %s", strerror(errno));
1368 	cinfo->thishost = xstrdup(thishost);
1369 	thishost[strcspn(thishost, ".")] = '\0';
1370 	cinfo->shorthost = xstrdup(thishost);
1371 	xasprintf(&cinfo->portstr, "%d", options.port);
1372 	xasprintf(&cinfo->uidstr, "%llu",
1373 	    (unsigned long long)pw->pw_uid);
1374 	cinfo->keyalias = xstrdup(options.host_key_alias ?
1375 	    options.host_key_alias : host_arg);
1376 	cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
1377 	    cinfo->portstr, options.user);
1378 	cinfo->host_arg = xstrdup(host_arg);
1379 	cinfo->remhost = xstrdup(host);
1380 	cinfo->remuser = xstrdup(options.user);
1381 	cinfo->homedir = xstrdup(pw->pw_dir);
1382 	cinfo->locuser = xstrdup(pw->pw_name);
1383 
1384 	/* Find canonic host name. */
1385 	if (strchr(host, '.') == 0) {
1386 		struct addrinfo hints;
1387 		struct addrinfo *ai = NULL;
1388 		int errgai;
1389 		memset(&hints, 0, sizeof(hints));
1390 		hints.ai_family = options.address_family;
1391 		hints.ai_flags = AI_CANONNAME;
1392 		hints.ai_socktype = SOCK_STREAM;
1393 		errgai = getaddrinfo(host, NULL, &hints, &ai);
1394 		if (errgai == 0) {
1395 			if (ai->ai_canonname != NULL)
1396 				host = xstrdup(ai->ai_canonname);
1397 			freeaddrinfo(ai);
1398 		}
1399 	}
1400 
1401 	/*
1402 	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1403 	 * after port-forwarding is set up, so it may pick up any local
1404 	 * tunnel interface name allocated.
1405 	 */
1406 	if (options.remote_command != NULL) {
1407 		debug3("expanding RemoteCommand: %s", options.remote_command);
1408 		cp = options.remote_command;
1409 		options.remote_command = default_client_percent_expand(cp,
1410 		    cinfo);
1411 		debug3("expanded RemoteCommand: %s", options.remote_command);
1412 		free(cp);
1413 		if ((r = sshbuf_put(command, options.remote_command,
1414 		    strlen(options.remote_command))) != 0)
1415 			fatal_fr(r, "buffer error");
1416 	}
1417 
1418 	if (options.control_path != NULL) {
1419 		cp = tilde_expand_filename(options.control_path, getuid());
1420 		free(options.control_path);
1421 		options.control_path = default_client_percent_dollar_expand(cp,
1422 		    cinfo);
1423 		free(cp);
1424 	}
1425 
1426 	if (options.identity_agent != NULL) {
1427 		p = tilde_expand_filename(options.identity_agent, getuid());
1428 		cp = default_client_percent_dollar_expand(p, cinfo);
1429 		free(p);
1430 		free(options.identity_agent);
1431 		options.identity_agent = cp;
1432 	}
1433 
1434 	if (options.forward_agent_sock_path != NULL) {
1435 		p = tilde_expand_filename(options.forward_agent_sock_path,
1436 		    getuid());
1437 		cp = default_client_percent_dollar_expand(p, cinfo);
1438 		free(p);
1439 		free(options.forward_agent_sock_path);
1440 		options.forward_agent_sock_path = cp;
1441 		if (stat(options.forward_agent_sock_path, &st) != 0) {
1442 			error("Cannot forward agent socket path \"%s\": %s",
1443 			    options.forward_agent_sock_path, strerror(errno));
1444 			if (options.exit_on_forward_failure)
1445 				cleanup_exit(255);
1446 		}
1447 	}
1448 
1449 	if (options.num_system_hostfiles > 0 &&
1450 	    strcasecmp(options.system_hostfiles[0], "none") == 0) {
1451 		if (options.num_system_hostfiles > 1)
1452 			fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1453 			    "appears with other entries");
1454 		free(options.system_hostfiles[0]);
1455 		options.system_hostfiles[0] = NULL;
1456 		options.num_system_hostfiles = 0;
1457 	}
1458 
1459 	if (options.num_user_hostfiles > 0 &&
1460 	    strcasecmp(options.user_hostfiles[0], "none") == 0) {
1461 		if (options.num_user_hostfiles > 1)
1462 			fatal("Invalid UserKnownHostsFiles: \"none\" "
1463 			    "appears with other entries");
1464 		free(options.user_hostfiles[0]);
1465 		options.user_hostfiles[0] = NULL;
1466 		options.num_user_hostfiles = 0;
1467 	}
1468 	for (j = 0; j < options.num_user_hostfiles; j++) {
1469 		if (options.user_hostfiles[j] == NULL)
1470 			continue;
1471 		cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1472 		p = default_client_percent_dollar_expand(cp, cinfo);
1473 		if (strcmp(options.user_hostfiles[j], p) != 0)
1474 			debug3("expanded UserKnownHostsFile '%s' -> "
1475 			    "'%s'", options.user_hostfiles[j], p);
1476 		free(options.user_hostfiles[j]);
1477 		free(cp);
1478 		options.user_hostfiles[j] = p;
1479 	}
1480 
1481 	for (i = 0; i < options.num_local_forwards; i++) {
1482 		if (options.local_forwards[i].listen_path != NULL) {
1483 			cp = options.local_forwards[i].listen_path;
1484 			p = options.local_forwards[i].listen_path =
1485 			    default_client_percent_expand(cp, cinfo);
1486 			if (strcmp(cp, p) != 0)
1487 				debug3("expanded LocalForward listen path "
1488 				    "'%s' -> '%s'", cp, p);
1489 			free(cp);
1490 		}
1491 		if (options.local_forwards[i].connect_path != NULL) {
1492 			cp = options.local_forwards[i].connect_path;
1493 			p = options.local_forwards[i].connect_path =
1494 			    default_client_percent_expand(cp, cinfo);
1495 			if (strcmp(cp, p) != 0)
1496 				debug3("expanded LocalForward connect path "
1497 				    "'%s' -> '%s'", cp, p);
1498 			free(cp);
1499 		}
1500 	}
1501 
1502 	for (i = 0; i < options.num_remote_forwards; i++) {
1503 		if (options.remote_forwards[i].listen_path != NULL) {
1504 			cp = options.remote_forwards[i].listen_path;
1505 			p = options.remote_forwards[i].listen_path =
1506 			    default_client_percent_expand(cp, cinfo);
1507 			if (strcmp(cp, p) != 0)
1508 				debug3("expanded RemoteForward listen path "
1509 				    "'%s' -> '%s'", cp, p);
1510 			free(cp);
1511 		}
1512 		if (options.remote_forwards[i].connect_path != NULL) {
1513 			cp = options.remote_forwards[i].connect_path;
1514 			p = options.remote_forwards[i].connect_path =
1515 			    default_client_percent_expand(cp, cinfo);
1516 			if (strcmp(cp, p) != 0)
1517 				debug3("expanded RemoteForward connect path "
1518 				    "'%s' -> '%s'", cp, p);
1519 			free(cp);
1520 		}
1521 	}
1522 
1523 	if (config_test) {
1524 		dump_client_config(&options, host);
1525 		exit(0);
1526 	}
1527 
1528 	/* Expand SecurityKeyProvider if it refers to an environment variable */
1529 	if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1530 	    strlen(options.sk_provider) > 1) {
1531 		if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1532 			debug("Authenticator provider %s did not resolve; "
1533 			    "disabling", options.sk_provider);
1534 			free(options.sk_provider);
1535 			options.sk_provider = NULL;
1536 		} else {
1537 			debug2("resolved SecurityKeyProvider %s => %s",
1538 			    options.sk_provider, cp);
1539 			free(options.sk_provider);
1540 			options.sk_provider = xstrdup(cp);
1541 		}
1542 	}
1543 
1544 	if (muxclient_command != 0 && options.control_path == NULL)
1545 		fatal("No ControlPath specified for \"-O\" command");
1546 	if (options.control_path != NULL) {
1547 		int sock;
1548 		if ((sock = muxclient(options.control_path)) >= 0) {
1549 			ssh_packet_set_connection(ssh, sock, sock);
1550 			ssh_packet_set_mux(ssh);
1551 			goto skip_connect;
1552 		}
1553 	}
1554 
1555 	/*
1556 	 * If hostname canonicalisation was not enabled, then we may not
1557 	 * have yet resolved the hostname. Do so now.
1558 	 */
1559 	if (addrs == NULL && options.proxy_command == NULL) {
1560 		debug2("resolving \"%s\" port %d", host, options.port);
1561 		if ((addrs = resolve_host(host, options.port, 1,
1562 		    cname, sizeof(cname))) == NULL)
1563 			cleanup_exit(255); /* resolve_host logs the error */
1564 	}
1565 
1566 	if (options.connection_timeout >= INT_MAX/1000)
1567 		timeout_ms = INT_MAX;
1568 	else
1569 		timeout_ms = options.connection_timeout * 1000;
1570 
1571 	/* Open a connection to the remote host. */
1572 	if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port,
1573 	    options.connection_attempts,
1574 	    &timeout_ms, options.tcp_keep_alive) != 0)
1575 		exit(255);
1576 
1577 	if (addrs != NULL)
1578 		freeaddrinfo(addrs);
1579 
1580 	ssh_packet_set_timeout(ssh, options.server_alive_interval,
1581 	    options.server_alive_count_max);
1582 
1583 	if (timeout_ms > 0)
1584 		debug3("timeout: %d ms remain after connect", timeout_ms);
1585 
1586 	/*
1587 	 * If we successfully made the connection and we have hostbased auth
1588 	 * enabled, load the public keys so we can later use the ssh-keysign
1589 	 * helper to sign challenges.
1590 	 */
1591 	sensitive_data.nkeys = 0;
1592 	sensitive_data.keys = NULL;
1593 	if (options.hostbased_authentication) {
1594 		sensitive_data.nkeys = 10;
1595 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1596 		    sizeof(struct sshkey));
1597 
1598 		/* XXX check errors? */
1599 #define L_PUBKEY(p,o) do { \
1600 	if ((o) >= sensitive_data.nkeys) \
1601 		fatal_f("pubkey out of array bounds"); \
1602 	check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1603 	    p, "pubkey"); \
1604 } while (0)
1605 #define L_CERT(p,o) do { \
1606 	if ((o) >= sensitive_data.nkeys) \
1607 		fatal_f("cert out of array bounds"); \
1608 	check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
1609 } while (0)
1610 
1611 		if (options.hostbased_authentication == 1) {
1612 			L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1613 			L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1614 			L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1615 			L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1616 			L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1617 			L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1618 			L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1619 			L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1620 			L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1621 			L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1622 		}
1623 	}
1624 
1625 	/* load options.identity_files */
1626 	load_public_identity_files(cinfo);
1627 
1628 	/* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1629 	if (options.identity_agent &&
1630 	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1631 		if (strcmp(options.identity_agent, "none") == 0) {
1632 			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1633 		} else {
1634 			cp = options.identity_agent;
1635 			/* legacy (limited) format */
1636 			if (cp[0] == '$' && cp[1] != '{') {
1637 				if (!valid_env_name(cp + 1)) {
1638 					fatal("Invalid IdentityAgent "
1639 					    "environment variable name %s", cp);
1640 				}
1641 				if ((p = getenv(cp + 1)) == NULL)
1642 					unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1643 				else
1644 					setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1645 			} else {
1646 				/* identity_agent specifies a path directly */
1647 				setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1648 			}
1649 		}
1650 	}
1651 
1652 	if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1653 		cp = options.forward_agent_sock_path;
1654 		if (cp[0] == '$') {
1655 			if (!valid_env_name(cp + 1)) {
1656 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1657 			}
1658 			if ((p = getenv(cp + 1)) != NULL)
1659 				forward_agent_sock_path = xstrdup(p);
1660 			else
1661 				options.forward_agent = 0;
1662 			free(cp);
1663 		} else {
1664 			forward_agent_sock_path = cp;
1665 		}
1666 	}
1667 
1668 	/* Expand ~ in known host file names. */
1669 	tilde_expand_paths(options.system_hostfiles,
1670 	    options.num_system_hostfiles);
1671 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1672 
1673 	ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1674 	ssh_signal(SIGCHLD, main_sigchld_handler);
1675 
1676 	/* Log into the remote system.  Never returns if the login fails. */
1677 	ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1678 	    options.port, pw, timeout_ms, cinfo);
1679 
1680 	/* We no longer need the private host keys.  Clear them now. */
1681 	if (sensitive_data.nkeys != 0) {
1682 		for (i = 0; i < sensitive_data.nkeys; i++) {
1683 			if (sensitive_data.keys[i] != NULL) {
1684 				/* Destroys contents safely */
1685 				debug3("clear hostkey %d", i);
1686 				sshkey_free(sensitive_data.keys[i]);
1687 				sensitive_data.keys[i] = NULL;
1688 			}
1689 		}
1690 		free(sensitive_data.keys);
1691 	}
1692 	for (i = 0; i < options.num_identity_files; i++) {
1693 		free(options.identity_files[i]);
1694 		options.identity_files[i] = NULL;
1695 		if (options.identity_keys[i]) {
1696 			sshkey_free(options.identity_keys[i]);
1697 			options.identity_keys[i] = NULL;
1698 		}
1699 	}
1700 	for (i = 0; i < options.num_certificate_files; i++) {
1701 		free(options.certificate_files[i]);
1702 		options.certificate_files[i] = NULL;
1703 	}
1704 
1705 #ifdef ENABLE_PKCS11
1706 	(void)pkcs11_del_provider(options.pkcs11_provider);
1707 #endif
1708 
1709  skip_connect:
1710 	exit_status = ssh_session2(ssh, cinfo);
1711 	ssh_conn_info_free(cinfo);
1712 	ssh_packet_close(ssh);
1713 
1714 	if (options.control_path != NULL && muxserver_sock != -1)
1715 		unlink(options.control_path);
1716 
1717 	/* Kill ProxyCommand if it is running. */
1718 	ssh_kill_proxy_command();
1719 
1720 	return exit_status;
1721 }
1722 
1723 static void
1724 control_persist_detach(void)
1725 {
1726 	pid_t pid;
1727 
1728 	debug_f("backgrounding master process");
1729 
1730 	/*
1731 	 * master (current process) into the background, and make the
1732 	 * foreground process a client of the backgrounded master.
1733 	 */
1734 	switch ((pid = fork())) {
1735 	case -1:
1736 		fatal_f("fork: %s", strerror(errno));
1737 	case 0:
1738 		/* Child: master process continues mainloop */
1739 		break;
1740 	default:
1741 		/* Parent: set up mux client to connect to backgrounded master */
1742 		debug2_f("background process is %ld", (long)pid);
1743 		options.stdin_null = ostdin_null_flag;
1744 		options.request_tty = orequest_tty;
1745 		tty_flag = otty_flag;
1746 		options.session_type = osession_type;
1747 		close(muxserver_sock);
1748 		muxserver_sock = -1;
1749 		options.control_master = SSHCTL_MASTER_NO;
1750 		muxclient(options.control_path);
1751 		/* muxclient() doesn't return on success. */
1752 		fatal("Failed to connect to new control master");
1753 	}
1754 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1755 		error_f("stdfd_devnull failed");
1756 	daemon(1, 1);
1757 	setproctitle("%s [mux]", options.control_path);
1758 }
1759 
1760 /* Do fork() after authentication. Used by "ssh -f" */
1761 static void
1762 fork_postauth(void)
1763 {
1764 	if (need_controlpersist_detach)
1765 		control_persist_detach();
1766 	debug("forking to background");
1767 	options.fork_after_authentication = 0;
1768 	if (daemon(1, 1) == -1)
1769 		fatal("daemon() failed: %.200s", strerror(errno));
1770 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1771 		error_f("stdfd_devnull failed");
1772 }
1773 
1774 static void
1775 forwarding_success(void)
1776 {
1777 	if (forward_confirms_pending == -1)
1778 		return;
1779 	if (--forward_confirms_pending == 0) {
1780 		debug_f("all expected forwarding replies received");
1781 		if (options.fork_after_authentication)
1782 			fork_postauth();
1783 	} else {
1784 		debug2_f("%d expected forwarding replies remaining",
1785 		    forward_confirms_pending);
1786 	}
1787 }
1788 
1789 /* Callback for remote forward global requests */
1790 static void
1791 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1792 {
1793 	struct Forward *rfwd = (struct Forward *)ctxt;
1794 	u_int port;
1795 	int r;
1796 
1797 	/* XXX verbose() on failure? */
1798 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1799 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1800 	    rfwd->listen_path ? rfwd->listen_path :
1801 	    rfwd->listen_host ? rfwd->listen_host : "",
1802 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1803 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1804 	    rfwd->connect_host, rfwd->connect_port);
1805 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1806 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1807 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1808 				fatal_fr(r, "parse packet");
1809 			if (port > 65535) {
1810 				error("Invalid allocated port %u for remote "
1811 				    "forward to %s:%d", port,
1812 				    rfwd->connect_host, rfwd->connect_port);
1813 				/* Ensure failure processing runs below */
1814 				type = SSH2_MSG_REQUEST_FAILURE;
1815 				channel_update_permission(ssh,
1816 				    rfwd->handle, -1);
1817 			} else {
1818 				rfwd->allocated_port = (int)port;
1819 				logit("Allocated port %u for remote "
1820 				    "forward to %s:%d",
1821 				    rfwd->allocated_port, rfwd->connect_path ?
1822 				    rfwd->connect_path : rfwd->connect_host,
1823 				    rfwd->connect_port);
1824 				channel_update_permission(ssh,
1825 				    rfwd->handle, rfwd->allocated_port);
1826 			}
1827 		} else {
1828 			channel_update_permission(ssh, rfwd->handle, -1);
1829 		}
1830 	}
1831 
1832 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1833 		if (options.exit_on_forward_failure) {
1834 			if (rfwd->listen_path != NULL)
1835 				fatal("Error: remote port forwarding failed "
1836 				    "for listen path %s", rfwd->listen_path);
1837 			else
1838 				fatal("Error: remote port forwarding failed "
1839 				    "for listen port %d", rfwd->listen_port);
1840 		} else {
1841 			if (rfwd->listen_path != NULL)
1842 				logit("Warning: remote port forwarding failed "
1843 				    "for listen path %s", rfwd->listen_path);
1844 			else
1845 				logit("Warning: remote port forwarding failed "
1846 				    "for listen port %d", rfwd->listen_port);
1847 		}
1848 	}
1849 	forwarding_success();
1850 }
1851 
1852 static void
1853 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1854 {
1855 	debug("stdio forwarding: done");
1856 	cleanup_exit(0);
1857 }
1858 
1859 static void
1860 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1861 {
1862 	if (!success)
1863 		fatal("stdio forwarding failed");
1864 }
1865 
1866 static void
1867 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1868 {
1869 	if (!success) {
1870 		error("Tunnel forwarding failed");
1871 		if (options.exit_on_forward_failure)
1872 			cleanup_exit(255);
1873 	}
1874 
1875 	debug_f("tunnel forward established, id=%d", id);
1876 	forwarding_success();
1877 }
1878 
1879 static void
1880 ssh_init_stdio_forwarding(struct ssh *ssh)
1881 {
1882 	Channel *c;
1883 	int in, out;
1884 
1885 	if (options.stdio_forward_host == NULL)
1886 		return;
1887 
1888 	debug3_f("%s:%d", options.stdio_forward_host,
1889 	    options.stdio_forward_port);
1890 
1891 	if ((in = dup(STDIN_FILENO)) == -1 ||
1892 	    (out = dup(STDOUT_FILENO)) == -1)
1893 		fatal_f("dup() in/out failed");
1894 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1895 	    options.stdio_forward_port, in, out,
1896 	    CHANNEL_NONBLOCK_STDIO)) == NULL)
1897 		fatal_f("channel_connect_stdio_fwd failed");
1898 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1899 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1900 }
1901 
1902 static void
1903 ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
1904     u_int num_opens)
1905 {
1906 	u_int i;
1907 	int port;
1908 	char *addr, *arg, *oarg, ch;
1909 	int where = FORWARD_LOCAL;
1910 
1911 	channel_clear_permission(ssh, FORWARD_ADM, where);
1912 	if (num_opens == 0)
1913 		return; /* permit any */
1914 
1915 	/* handle keywords: "any" / "none" */
1916 	if (num_opens == 1 && strcmp(opens[0], "any") == 0)
1917 		return;
1918 	if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
1919 		channel_disable_admin(ssh, where);
1920 		return;
1921 	}
1922 	/* Otherwise treat it as a list of permitted host:port */
1923 	for (i = 0; i < num_opens; i++) {
1924 		oarg = arg = xstrdup(opens[i]);
1925 		ch = '\0';
1926 		addr = hpdelim2(&arg, &ch);
1927 		if (addr == NULL || ch == '/')
1928 			fatal_f("missing host in %s", what);
1929 		addr = cleanhostname(addr);
1930 		if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1931 			fatal_f("bad port number in %s", what);
1932 		/* Send it to channels layer */
1933 		channel_add_permission(ssh, FORWARD_ADM,
1934 		    where, addr, port);
1935 		free(oarg);
1936 	}
1937 }
1938 
1939 static void
1940 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1941 {
1942 	int success = 0;
1943 	int i;
1944 
1945 	ssh_init_forward_permissions(ssh, "permitremoteopen",
1946 	    options.permitted_remote_opens,
1947 	    options.num_permitted_remote_opens);
1948 
1949 	if (options.exit_on_forward_failure)
1950 		forward_confirms_pending = 0; /* track pending requests */
1951 	/* Initiate local TCP/IP port forwardings. */
1952 	for (i = 0; i < options.num_local_forwards; i++) {
1953 		debug("Local connections to %.200s:%d forwarded to remote "
1954 		    "address %.200s:%d",
1955 		    (options.local_forwards[i].listen_path != NULL) ?
1956 		    options.local_forwards[i].listen_path :
1957 		    (options.local_forwards[i].listen_host == NULL) ?
1958 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1959 		    options.local_forwards[i].listen_host,
1960 		    options.local_forwards[i].listen_port,
1961 		    (options.local_forwards[i].connect_path != NULL) ?
1962 		    options.local_forwards[i].connect_path :
1963 		    options.local_forwards[i].connect_host,
1964 		    options.local_forwards[i].connect_port);
1965 		success += channel_setup_local_fwd_listener(ssh,
1966 		    &options.local_forwards[i], &options.fwd_opts);
1967 	}
1968 	if (i > 0 && success != i && options.exit_on_forward_failure)
1969 		fatal("Could not request local forwarding.");
1970 	if (i > 0 && success == 0)
1971 		error("Could not request local forwarding.");
1972 
1973 	/* Initiate remote TCP/IP port forwardings. */
1974 	for (i = 0; i < options.num_remote_forwards; i++) {
1975 		debug("Remote connections from %.200s:%d forwarded to "
1976 		    "local address %.200s:%d",
1977 		    (options.remote_forwards[i].listen_path != NULL) ?
1978 		    options.remote_forwards[i].listen_path :
1979 		    (options.remote_forwards[i].listen_host == NULL) ?
1980 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1981 		    options.remote_forwards[i].listen_port,
1982 		    (options.remote_forwards[i].connect_path != NULL) ?
1983 		    options.remote_forwards[i].connect_path :
1984 		    options.remote_forwards[i].connect_host,
1985 		    options.remote_forwards[i].connect_port);
1986 		if ((options.remote_forwards[i].handle =
1987 		    channel_request_remote_forwarding(ssh,
1988 		    &options.remote_forwards[i])) >= 0) {
1989 			client_register_global_confirm(
1990 			    ssh_confirm_remote_forward,
1991 			    &options.remote_forwards[i]);
1992 			forward_confirms_pending++;
1993 		} else if (options.exit_on_forward_failure)
1994 			fatal("Could not request remote forwarding.");
1995 		else
1996 			logit("Warning: Could not request remote forwarding.");
1997 	}
1998 
1999 	/* Initiate tunnel forwarding. */
2000 	if (options.tun_open != SSH_TUNMODE_NO) {
2001 		if ((*ifname = client_request_tun_fwd(ssh,
2002 		    options.tun_open, options.tun_local,
2003 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
2004 			forward_confirms_pending++;
2005 		else if (options.exit_on_forward_failure)
2006 			fatal("Could not request tunnel forwarding.");
2007 		else
2008 			error("Could not request tunnel forwarding.");
2009 	}
2010 	if (forward_confirms_pending > 0) {
2011 		debug_f("expecting replies for %d forwards",
2012 		    forward_confirms_pending);
2013 	}
2014 }
2015 
2016 static void
2017 check_agent_present(void)
2018 {
2019 	int r;
2020 
2021 	if (options.forward_agent) {
2022 		/* Clear agent forwarding if we don't have an agent. */
2023 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2024 			options.forward_agent = 0;
2025 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
2026 				debug_r(r, "ssh_get_authentication_socket");
2027 		}
2028 	}
2029 }
2030 
2031 static void
2032 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2033 {
2034 	extern char **environ;
2035 	const char *display, *term;
2036 	int r, interactive = tty_flag;
2037 	char *proto = NULL, *data = NULL;
2038 
2039 	if (!success)
2040 		return; /* No need for error message, channels code sens one */
2041 
2042 	display = getenv("DISPLAY");
2043 	if (display == NULL && options.forward_x11)
2044 		debug("X11 forwarding requested but DISPLAY not set");
2045 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
2046 	    options.xauth_location, options.forward_x11_trusted,
2047 	    options.forward_x11_timeout, &proto, &data) == 0) {
2048 		/* Request forwarding with authentication spoofing. */
2049 		debug("Requesting X11 forwarding with authentication "
2050 		    "spoofing.");
2051 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2052 		    data, 1);
2053 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2054 		/* XXX exit_on_forward_failure */
2055 		interactive = 1;
2056 	}
2057 
2058 	check_agent_present();
2059 	if (options.forward_agent) {
2060 		debug("Requesting authentication agent forwarding.");
2061 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
2062 		if ((r = sshpkt_send(ssh)) != 0)
2063 			fatal_fr(r, "send packet");
2064 	}
2065 
2066 	/* Tell the packet module whether this is an interactive session. */
2067 	ssh_packet_set_interactive(ssh, interactive,
2068 	    options.ip_qos_interactive, options.ip_qos_bulk);
2069 
2070 	if ((term = lookup_env_in_list("TERM", options.setenv,
2071 	    options.num_setenv)) == NULL || *term == '\0')
2072 		term = getenv("TERM");
2073 	client_session2_setup(ssh, id, tty_flag,
2074 	    options.session_type == SESSION_TYPE_SUBSYSTEM, term,
2075 	    NULL, fileno(stdin), command, environ);
2076 }
2077 
2078 /* open new channel for a session */
2079 static int
2080 ssh_session2_open(struct ssh *ssh)
2081 {
2082 	Channel *c;
2083 	int window, packetmax, in, out, err;
2084 
2085 	if (options.stdin_null) {
2086 		in = open(_PATH_DEVNULL, O_RDONLY);
2087 	} else {
2088 		in = dup(STDIN_FILENO);
2089 	}
2090 	out = dup(STDOUT_FILENO);
2091 	err = dup(STDERR_FILENO);
2092 
2093 	if (in == -1 || out == -1 || err == -1)
2094 		fatal("dup() in/out/err failed");
2095 
2096 	window = CHAN_SES_WINDOW_DEFAULT;
2097 	packetmax = CHAN_SES_PACKET_DEFAULT;
2098 	if (tty_flag) {
2099 		window >>= 1;
2100 		packetmax >>= 1;
2101 	}
2102 	c = channel_new(ssh,
2103 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2104 	    window, packetmax, CHAN_EXTENDED_WRITE,
2105 	    "client-session", CHANNEL_NONBLOCK_STDIO);
2106 
2107 	debug3_f("channel_new: %d", c->self);
2108 
2109 	channel_send_open(ssh, c->self);
2110 	if (options.session_type != SESSION_TYPE_NONE)
2111 		channel_register_open_confirm(ssh, c->self,
2112 		    ssh_session2_setup, NULL);
2113 
2114 	return c->self;
2115 }
2116 
2117 static int
2118 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2119 {
2120 	int r, id = -1;
2121 	char *cp, *tun_fwd_ifname = NULL;
2122 
2123 	/* XXX should be pre-session */
2124 	if (!options.control_persist)
2125 		ssh_init_stdio_forwarding(ssh);
2126 
2127 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2128 
2129 	if (options.local_command != NULL) {
2130 		debug3("expanding LocalCommand: %s", options.local_command);
2131 		cp = options.local_command;
2132 		options.local_command = percent_expand(cp,
2133 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2134 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2135 		    (char *)NULL);
2136 		debug3("expanded LocalCommand: %s", options.local_command);
2137 		free(cp);
2138 	}
2139 
2140 	/* Start listening for multiplex clients */
2141 	if (!ssh_packet_get_mux(ssh))
2142 		muxserver_listen(ssh);
2143 
2144 	/*
2145 	 * If we are in control persist mode and have a working mux listen
2146 	 * socket, then prepare to background ourselves and have a foreground
2147 	 * client attach as a control client.
2148 	 * NB. we must save copies of the flags that we override for
2149 	 * the backgrounding, since we defer attachment of the client until
2150 	 * after the connection is fully established (in particular,
2151 	 * async rfwd replies have been received for ExitOnForwardFailure).
2152 	 */
2153 	if (options.control_persist && muxserver_sock != -1) {
2154 		ostdin_null_flag = options.stdin_null;
2155 		osession_type = options.session_type;
2156 		orequest_tty = options.request_tty;
2157 		otty_flag = tty_flag;
2158 		options.stdin_null = 1;
2159 		options.session_type = SESSION_TYPE_NONE;
2160 		tty_flag = 0;
2161 		if (!options.fork_after_authentication &&
2162 		    (osession_type != SESSION_TYPE_NONE ||
2163 		    options.stdio_forward_host != NULL))
2164 			need_controlpersist_detach = 1;
2165 		options.fork_after_authentication = 1;
2166 	}
2167 	/*
2168 	 * ControlPersist mux listen socket setup failed, attempt the
2169 	 * stdio forward setup that we skipped earlier.
2170 	 */
2171 	if (options.control_persist && muxserver_sock == -1)
2172 		ssh_init_stdio_forwarding(ssh);
2173 
2174 	if (options.session_type != SESSION_TYPE_NONE)
2175 		id = ssh_session2_open(ssh);
2176 	else {
2177 		ssh_packet_set_interactive(ssh,
2178 		    options.control_master == SSHCTL_MASTER_NO,
2179 		    options.ip_qos_interactive, options.ip_qos_bulk);
2180 	}
2181 
2182 	/* If we don't expect to open a new session, then disallow it */
2183 	if (options.control_master == SSHCTL_MASTER_NO &&
2184 	    (ssh->compat & SSH_NEW_OPENSSH)) {
2185 		debug("Requesting no-more-sessions@openssh.com");
2186 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2187 		    (r = sshpkt_put_cstring(ssh,
2188 		    "no-more-sessions@openssh.com")) != 0 ||
2189 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2190 		    (r = sshpkt_send(ssh)) != 0)
2191 			fatal_fr(r, "send packet");
2192 	}
2193 
2194 	/* Execute a local command */
2195 	if (options.local_command != NULL &&
2196 	    options.permit_local_command)
2197 		ssh_local_cmd(options.local_command);
2198 
2199 	/*
2200 	 * stdout is now owned by the session channel; clobber it here
2201 	 * so future channel closes are propagated to the local fd.
2202 	 * NB. this can only happen after LocalCommand has completed,
2203 	 * as it may want to write to stdout.
2204 	 */
2205 	if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2206 		error_f("stdfd_devnull failed");
2207 
2208 	/*
2209 	 * If requested and we are not interested in replies to remote
2210 	 * forwarding requests, then let ssh continue in the background.
2211 	 */
2212 	if (options.fork_after_authentication) {
2213 		if (options.exit_on_forward_failure &&
2214 		    options.num_remote_forwards > 0) {
2215 			debug("deferring postauth fork until remote forward "
2216 			    "confirmation received");
2217 		} else
2218 			fork_postauth();
2219 	}
2220 
2221 	return client_loop(ssh, tty_flag, tty_flag ?
2222 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2223 }
2224 
2225 /* Loads all IdentityFile and CertificateFile keys */
2226 static void
2227 load_public_identity_files(const struct ssh_conn_info *cinfo)
2228 {
2229 	char *filename, *cp;
2230 	struct sshkey *public;
2231 	int i;
2232 	u_int n_ids, n_certs;
2233 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2234 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2235 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2236 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2237 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2238 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2239 #ifdef ENABLE_PKCS11
2240 	struct sshkey **keys = NULL;
2241 	char **comments = NULL;
2242 	int nkeys;
2243 #endif /* PKCS11 */
2244 
2245 	n_ids = n_certs = 0;
2246 	memset(identity_files, 0, sizeof(identity_files));
2247 	memset(identity_keys, 0, sizeof(identity_keys));
2248 	memset(identity_file_userprovided, 0,
2249 	    sizeof(identity_file_userprovided));
2250 	memset(certificate_files, 0, sizeof(certificate_files));
2251 	memset(certificates, 0, sizeof(certificates));
2252 	memset(certificate_file_userprovided, 0,
2253 	    sizeof(certificate_file_userprovided));
2254 
2255 #ifdef ENABLE_PKCS11
2256 	if (options.pkcs11_provider != NULL &&
2257 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2258 	    (pkcs11_init(!options.batch_mode) == 0) &&
2259 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2260 	    &keys, &comments)) > 0) {
2261 		for (i = 0; i < nkeys; i++) {
2262 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2263 				sshkey_free(keys[i]);
2264 				free(comments[i]);
2265 				continue;
2266 			}
2267 			identity_keys[n_ids] = keys[i];
2268 			identity_files[n_ids] = comments[i]; /* transferred */
2269 			n_ids++;
2270 		}
2271 		free(keys);
2272 		free(comments);
2273 	}
2274 #endif /* ENABLE_PKCS11 */
2275 	for (i = 0; i < options.num_identity_files; i++) {
2276 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2277 		    strcasecmp(options.identity_files[i], "none") == 0) {
2278 			free(options.identity_files[i]);
2279 			options.identity_files[i] = NULL;
2280 			continue;
2281 		}
2282 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2283 		filename = default_client_percent_dollar_expand(cp, cinfo);
2284 		free(cp);
2285 		check_load(sshkey_load_public(filename, &public, NULL),
2286 		    filename, "pubkey");
2287 		debug("identity file %s type %d", filename,
2288 		    public ? public->type : -1);
2289 		free(options.identity_files[i]);
2290 		identity_files[n_ids] = filename;
2291 		identity_keys[n_ids] = public;
2292 		identity_file_userprovided[n_ids] =
2293 		    options.identity_file_userprovided[i];
2294 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2295 			continue;
2296 
2297 		/*
2298 		 * If no certificates have been explicitly listed then try
2299 		 * to add the default certificate variant too.
2300 		 */
2301 		if (options.num_certificate_files != 0)
2302 			continue;
2303 		xasprintf(&cp, "%s-cert", filename);
2304 		check_load(sshkey_load_public(cp, &public, NULL),
2305 		    filename, "pubkey");
2306 		debug("identity file %s type %d", cp,
2307 		    public ? public->type : -1);
2308 		if (public == NULL) {
2309 			free(cp);
2310 			continue;
2311 		}
2312 		if (!sshkey_is_cert(public)) {
2313 			debug_f("key %s type %s is not a certificate",
2314 			    cp, sshkey_type(public));
2315 			sshkey_free(public);
2316 			free(cp);
2317 			continue;
2318 		}
2319 		/* NB. leave filename pointing to private key */
2320 		identity_files[n_ids] = xstrdup(filename);
2321 		identity_keys[n_ids] = public;
2322 		identity_file_userprovided[n_ids] =
2323 		    options.identity_file_userprovided[i];
2324 		n_ids++;
2325 	}
2326 
2327 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2328 		fatal_f("too many certificates");
2329 	for (i = 0; i < options.num_certificate_files; i++) {
2330 		cp = tilde_expand_filename(options.certificate_files[i],
2331 		    getuid());
2332 		filename = default_client_percent_dollar_expand(cp, cinfo);
2333 		free(cp);
2334 
2335 		check_load(sshkey_load_public(filename, &public, NULL),
2336 		    filename, "certificate");
2337 		debug("certificate file %s type %d", filename,
2338 		    public ? public->type : -1);
2339 		free(options.certificate_files[i]);
2340 		options.certificate_files[i] = NULL;
2341 		if (public == NULL) {
2342 			free(filename);
2343 			continue;
2344 		}
2345 		if (!sshkey_is_cert(public)) {
2346 			debug_f("key %s type %s is not a certificate",
2347 			    filename, sshkey_type(public));
2348 			sshkey_free(public);
2349 			free(filename);
2350 			continue;
2351 		}
2352 		certificate_files[n_certs] = filename;
2353 		certificates[n_certs] = public;
2354 		certificate_file_userprovided[n_certs] =
2355 		    options.certificate_file_userprovided[i];
2356 		++n_certs;
2357 	}
2358 
2359 	options.num_identity_files = n_ids;
2360 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2361 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2362 	memcpy(options.identity_file_userprovided,
2363 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2364 
2365 	options.num_certificate_files = n_certs;
2366 	memcpy(options.certificate_files,
2367 	    certificate_files, sizeof(certificate_files));
2368 	memcpy(options.certificates, certificates, sizeof(certificates));
2369 	memcpy(options.certificate_file_userprovided,
2370 	    certificate_file_userprovided,
2371 	    sizeof(certificate_file_userprovided));
2372 }
2373 
2374 static void
2375 main_sigchld_handler(int sig)
2376 {
2377 	int save_errno = errno;
2378 	pid_t pid;
2379 	int status;
2380 
2381 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2382 	    (pid == -1 && errno == EINTR))
2383 		;
2384 	errno = save_errno;
2385 }
2386