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