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