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