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