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