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