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