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