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