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