xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh.c (revision 46f5119e40af2e51998f686b2fdcc76b5488f7f3)
1 /*	$NetBSD: ssh.c,v 1.5 2010/11/21 18:59:04 adam Exp $	*/
2 /* $OpenBSD: ssh.c,v 1.348 2010/08/16 04:06:06 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.5 2010/11/21 18:59:04 adam Exp $");
46 #include <sys/types.h>
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/param.h>
50 #include <sys/queue.h>
51 #include <sys/resource.h>
52 #include <sys/socket.h>
53 #include <sys/stat.h>
54 #include <sys/time.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 
69 #include <openssl/evp.h>
70 #include <openssl/err.h>
71 
72 #include "xmalloc.h"
73 #include "ssh.h"
74 #include "ssh1.h"
75 #include "ssh2.h"
76 #include "canohost.h"
77 #include "compat.h"
78 #include "cipher.h"
79 #include "packet.h"
80 #include "buffer.h"
81 #include "channels.h"
82 #include "key.h"
83 #include "authfd.h"
84 #include "authfile.h"
85 #include "pathnames.h"
86 #include "dispatch.h"
87 #include "clientloop.h"
88 #include "log.h"
89 #include "readconf.h"
90 #include "sshconnect.h"
91 #include "misc.h"
92 #include "kex.h"
93 #include "mac.h"
94 #include "sshpty.h"
95 #include "match.h"
96 #include "msg.h"
97 #include "uidswap.h"
98 #include "roaming.h"
99 #include "version.h"
100 
101 #ifdef ENABLE_PKCS11
102 #include "ssh-pkcs11.h"
103 #endif
104 
105 extern char *__progname;
106 
107 /* Flag indicating whether debug mode is on.  May be set on the command line. */
108 int debug_flag = 0;
109 
110 /* Flag indicating whether a tty should be allocated */
111 int tty_flag = 0;
112 int no_tty_flag = 0;
113 int force_tty_flag = 0;
114 
115 /* don't exec a shell */
116 int no_shell_flag = 0;
117 
118 /*
119  * Flag indicating that nothing should be read from stdin.  This can be set
120  * on the command line.
121  */
122 int stdin_null_flag = 0;
123 
124 /*
125  * Flag indicating that the current process should be backgrounded and
126  * a new slave launched in the foreground for ControlPersist.
127  */
128 int need_controlpersist_detach = 0;
129 
130 /* Copies of flags for ControlPersist foreground slave */
131 int ostdin_null_flag, ono_shell_flag, ono_tty_flag, otty_flag;
132 
133 /*
134  * Flag indicating that ssh should fork after authentication.  This is useful
135  * so that the passphrase can be entered manually, and then ssh goes to the
136  * background.
137  */
138 int fork_after_authentication_flag = 0;
139 
140 /* forward stdio to remote host and port */
141 char *stdio_forward_host = NULL;
142 int stdio_forward_port = 0;
143 
144 /*
145  * General data structure for command line options and options configurable
146  * in configuration files.  See readconf.h.
147  */
148 Options options;
149 
150 /* optional user configfile */
151 char *config = NULL;
152 
153 /*
154  * Name of the host we are connecting to.  This is the name given on the
155  * command line, or the HostName specified for the user-supplied name in a
156  * configuration file.
157  */
158 char *host;
159 
160 /* socket address the host resolves to */
161 struct sockaddr_storage hostaddr;
162 
163 /* Private host keys. */
164 Sensitive sensitive_data;
165 
166 /* Original real UID. */
167 uid_t original_real_uid;
168 uid_t original_effective_uid;
169 
170 /* command to be executed */
171 Buffer command;
172 
173 /* Should we execute a command or invoke a subsystem? */
174 int subsystem_flag = 0;
175 
176 /* # of replies received for global requests */
177 static int remote_forward_confirms_received = 0;
178 
179 /* pid of proxycommand child process */
180 pid_t proxy_command_pid = 0;
181 
182 /* mux.c */
183 extern int muxserver_sock;
184 extern u_int muxclient_command;
185 
186 
187 /* Prints a help message to the user.  This function never returns. */
188 
189 static void
190 usage(void)
191 {
192 	fprintf(stderr,
193 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
194 "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
195 "           [-I pkcs11] [-i identity_file]\n"
196 "           [-L [bind_address:]port:host:hostport]\n"
197 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
198 "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
199 "           [-W host:port] [-w local_tun[:remote_tun]]\n"
200 "           [user@]hostname [command]\n"
201 	);
202 	exit(255);
203 }
204 
205 static int ssh_session(void);
206 static int ssh_session2(void);
207 static void load_public_identity_files(void);
208 
209 /* from muxclient.c */
210 void muxclient(const char *);
211 void muxserver_listen(void);
212 
213 /*
214  * Main program for the ssh client.
215  */
216 int
217 main(int ac, char **av)
218 {
219 	int i, r, opt, exit_status, use_syslog;
220 	char *p, *cp, *line, *argv0, buf[MAXPATHLEN];
221 	struct stat st;
222 	struct passwd *pw;
223 	int dummy, timeout_ms;
224 	extern int optind, optreset;
225 	extern char *optarg;
226 	struct servent *sp;
227 	Forward fwd;
228 
229 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
230 	sanitise_stdfd();
231 
232 	/*
233 	 * Discard other fds that are hanging around. These can cause problem
234 	 * with backgrounded ssh processes started by ControlPersist.
235 	 */
236 	closefrom(STDERR_FILENO + 1);
237 
238 	/*
239 	 * Save the original real uid.  It will be needed later (uid-swapping
240 	 * may clobber the real uid).
241 	 */
242 	original_real_uid = getuid();
243 	original_effective_uid = geteuid();
244 
245 	/*
246 	 * Use uid-swapping to give up root privileges for the duration of
247 	 * option processing.  We will re-instantiate the rights when we are
248 	 * ready to create the privileged port, and will permanently drop
249 	 * them when the port has been created (actually, when the connection
250 	 * has been made, as we may need to create the port several times).
251 	 */
252 	PRIV_END;
253 
254 	/* If we are installed setuid root be careful to not drop core. */
255 	if (original_real_uid != original_effective_uid) {
256 		struct rlimit rlim;
257 		rlim.rlim_cur = rlim.rlim_max = 0;
258 		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
259 			fatal("setrlimit failed: %.100s", strerror(errno));
260 	}
261 	/* Get user data. */
262 	pw = getpwuid(original_real_uid);
263 	if (!pw) {
264 		logit("You don't exist, go away!");
265 		exit(255);
266 	}
267 	/* Take a copy of the returned structure. */
268 	pw = pwcopy(pw);
269 
270 	/*
271 	 * Set our umask to something reasonable, as some files are created
272 	 * with the default umask.  This will make them world-readable but
273 	 * writable only by the owner, which is ok for all files for which we
274 	 * don't set the modes explicitly.
275 	 */
276 	umask(022);
277 
278 	/*
279 	 * Initialize option structure to indicate that no values have been
280 	 * set.
281 	 */
282 	initialize_options(&options);
283 
284 	/* Parse command-line arguments. */
285 	host = NULL;
286 	use_syslog = 0;
287 	argv0 = av[0];
288 
289  again:
290 	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
291 	    "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
292 		switch (opt) {
293 		case '1':
294 			options.protocol = SSH_PROTO_1;
295 			break;
296 		case '2':
297 			options.protocol = SSH_PROTO_2;
298 			break;
299 		case '4':
300 			options.address_family = AF_INET;
301 			break;
302 		case '6':
303 			options.address_family = AF_INET6;
304 			break;
305 		case 'n':
306 			stdin_null_flag = 1;
307 			break;
308 		case 'f':
309 			fork_after_authentication_flag = 1;
310 			stdin_null_flag = 1;
311 			break;
312 		case 'x':
313 			options.forward_x11 = 0;
314 			break;
315 		case 'X':
316 			options.forward_x11 = 1;
317 			break;
318 		case 'y':
319 			use_syslog = 1;
320 			break;
321 		case 'Y':
322 			options.forward_x11 = 1;
323 			options.forward_x11_trusted = 1;
324 			break;
325 		case 'g':
326 			options.gateway_ports = 1;
327 			break;
328 		case 'O':
329 			if (stdio_forward_host != NULL)
330 				fatal("Cannot specify multiplexing "
331 				    "command with -W");
332 			else if (muxclient_command != 0)
333 				fatal("Multiplexing command already specified");
334 			if (strcmp(optarg, "check") == 0)
335 				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
336 			else if (strcmp(optarg, "forward") == 0)
337 				muxclient_command = SSHMUX_COMMAND_FORWARD;
338 			else if (strcmp(optarg, "exit") == 0)
339 				muxclient_command = SSHMUX_COMMAND_TERMINATE;
340 			else
341 				fatal("Invalid multiplex command.");
342 			break;
343 		case 'P':	/* deprecated */
344 			options.use_privileged_port = 0;
345 			break;
346 		case 'a':
347 			options.forward_agent = 0;
348 			break;
349 		case 'A':
350 			options.forward_agent = 1;
351 			break;
352 		case 'k':
353 			options.gss_deleg_creds = 0;
354 			break;
355 		case 'K':
356 			options.gss_authentication = 1;
357 			options.gss_deleg_creds = 1;
358 			break;
359 		case 'i':
360 			if (stat(optarg, &st) < 0) {
361 				fprintf(stderr, "Warning: Identity file %s "
362 				    "not accessible: %s.\n", optarg,
363 				    strerror(errno));
364 				break;
365 			}
366 			if (options.num_identity_files >=
367 			    SSH_MAX_IDENTITY_FILES)
368 				fatal("Too many identity files specified "
369 				    "(max %d)", SSH_MAX_IDENTITY_FILES);
370 			options.identity_files[options.num_identity_files++] =
371 			    xstrdup(optarg);
372 			break;
373 		case 'I':
374 #ifdef ENABLE_PKCS11
375 			options.pkcs11_provider = xstrdup(optarg);
376 #else
377 			fprintf(stderr, "no support for PKCS#11.\n");
378 #endif
379 			break;
380 		case 't':
381 			if (tty_flag)
382 				force_tty_flag = 1;
383 			tty_flag = 1;
384 			break;
385 		case 'v':
386 			if (debug_flag == 0) {
387 				debug_flag = 1;
388 				options.log_level = SYSLOG_LEVEL_DEBUG1;
389 			} else {
390 				if (options.log_level < SYSLOG_LEVEL_DEBUG3)
391 					options.log_level++;
392 				break;
393 			}
394 			/* FALLTHROUGH */
395 		case 'V':
396 			fprintf(stderr, "%s, %s\n",
397 			    SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
398 			if (opt == 'V')
399 				exit(0);
400 			break;
401 		case 'w':
402 			if (options.tun_open == -1)
403 				options.tun_open = SSH_TUNMODE_DEFAULT;
404 			options.tun_local = a2tun(optarg, &options.tun_remote);
405 			if (options.tun_local == SSH_TUNID_ERR) {
406 				fprintf(stderr,
407 				    "Bad tun device '%s'\n", optarg);
408 				exit(255);
409 			}
410 			break;
411 		case 'W':
412 			if (stdio_forward_host != NULL)
413 				fatal("stdio forward already specified");
414 			if (muxclient_command != 0)
415 				fatal("Cannot specify stdio forward with -O");
416 			if (parse_forward(&fwd, optarg, 1, 0)) {
417 				stdio_forward_host = fwd.listen_host;
418 				stdio_forward_port = fwd.listen_port;
419 				xfree(fwd.connect_host);
420 			} else {
421 				fprintf(stderr,
422 				    "Bad stdio forwarding specification '%s'\n",
423 				    optarg);
424 				exit(255);
425 			}
426 			no_tty_flag = 1;
427 			no_shell_flag = 1;
428 			options.clear_forwardings = 1;
429 			options.exit_on_forward_failure = 1;
430 			break;
431 		case 'q':
432 			options.log_level = SYSLOG_LEVEL_QUIET;
433 			break;
434 		case 'e':
435 			if (optarg[0] == '^' && optarg[2] == 0 &&
436 			    (u_char) optarg[1] >= 64 &&
437 			    (u_char) optarg[1] < 128)
438 				options.escape_char = (u_char) optarg[1] & 31;
439 			else if (strlen(optarg) == 1)
440 				options.escape_char = (u_char) optarg[0];
441 			else if (strcmp(optarg, "none") == 0)
442 				options.escape_char = SSH_ESCAPECHAR_NONE;
443 			else {
444 				fprintf(stderr, "Bad escape character '%s'.\n",
445 				    optarg);
446 				exit(255);
447 			}
448 			break;
449 		case 'c':
450 			if (ciphers_valid(optarg)) {
451 				/* SSH2 only */
452 				options.ciphers = xstrdup(optarg);
453 				options.cipher = SSH_CIPHER_INVALID;
454 			} else {
455 				/* SSH1 only */
456 				options.cipher = cipher_number(optarg);
457 				if (options.cipher == -1) {
458 					fprintf(stderr,
459 					    "Unknown cipher type '%s'\n",
460 					    optarg);
461 					exit(255);
462 				}
463 				if (options.cipher == SSH_CIPHER_3DES)
464 					options.ciphers = "3des-cbc";
465 				else if (options.cipher == SSH_CIPHER_BLOWFISH)
466 					options.ciphers = "blowfish-cbc";
467 				else
468 					options.ciphers = (char *)-1;
469 			}
470 			break;
471 		case 'm':
472 			if (mac_valid(optarg))
473 				options.macs = xstrdup(optarg);
474 			else {
475 				fprintf(stderr, "Unknown mac type '%s'\n",
476 				    optarg);
477 				exit(255);
478 			}
479 			break;
480 		case 'M':
481 			if (options.control_master == SSHCTL_MASTER_YES)
482 				options.control_master = SSHCTL_MASTER_ASK;
483 			else
484 				options.control_master = SSHCTL_MASTER_YES;
485 			break;
486 		case 'p':
487 			options.port = a2port(optarg);
488 			if (options.port <= 0) {
489 				fprintf(stderr, "Bad port '%s'\n", optarg);
490 				exit(255);
491 			}
492 			break;
493 		case 'l':
494 			options.user = optarg;
495 			break;
496 
497 		case 'L':
498 			if (parse_forward(&fwd, optarg, 0, 0))
499 				add_local_forward(&options, &fwd);
500 			else {
501 				fprintf(stderr,
502 				    "Bad local forwarding specification '%s'\n",
503 				    optarg);
504 				exit(255);
505 			}
506 			break;
507 
508 		case 'R':
509 			if (parse_forward(&fwd, optarg, 0, 1)) {
510 				add_remote_forward(&options, &fwd);
511 			} else {
512 				fprintf(stderr,
513 				    "Bad remote forwarding specification "
514 				    "'%s'\n", optarg);
515 				exit(255);
516 			}
517 			break;
518 
519 		case 'D':
520 			if (parse_forward(&fwd, optarg, 1, 0)) {
521 				add_local_forward(&options, &fwd);
522 			} else {
523 				fprintf(stderr,
524 				    "Bad dynamic forwarding specification "
525 				    "'%s'\n", optarg);
526 				exit(255);
527 			}
528 			break;
529 
530 		case 'C':
531 			options.compression = 1;
532 			break;
533 		case 'N':
534 			no_shell_flag = 1;
535 			no_tty_flag = 1;
536 			break;
537 		case 'T':
538 			no_tty_flag = 1;
539 			/* ensure that the user doesn't try to backdoor a */
540 			/* null cipher switch on an interactive session */
541 			/* so explicitly disable it no matter what */
542 			options.none_switch=0;
543 			break;
544 		case 'o':
545 			dummy = 1;
546 			line = xstrdup(optarg);
547 			if (process_config_line(&options, host ? host : "",
548 			    line, "command-line", 0, &dummy) != 0)
549 				exit(255);
550 			xfree(line);
551 			break;
552 		case 's':
553 			subsystem_flag = 1;
554 			break;
555 		case 'S':
556 			if (options.control_path != NULL)
557 				free(options.control_path);
558 			options.control_path = xstrdup(optarg);
559 			break;
560 		case 'b':
561 			options.bind_address = optarg;
562 			break;
563 		case 'F':
564 			config = optarg;
565 			break;
566 		default:
567 			usage();
568 		}
569 	}
570 
571 	ac -= optind;
572 	av += optind;
573 
574 	if (ac > 0 && !host) {
575 		if (strrchr(*av, '@')) {
576 			p = xstrdup(*av);
577 			cp = strrchr(p, '@');
578 			if (cp == NULL || cp == p)
579 				usage();
580 			options.user = p;
581 			*cp = '\0';
582 			host = ++cp;
583 		} else
584 			host = *av;
585 		if (ac > 1) {
586 			optind = optreset = 1;
587 			goto again;
588 		}
589 		ac--, av++;
590 	}
591 
592 	/* Check that we got a host name. */
593 	if (!host)
594 		usage();
595 
596 	SSLeay_add_all_algorithms();
597 	ERR_load_crypto_strings();
598 
599 	/* Initialize the command to execute on remote host. */
600 	buffer_init(&command);
601 
602 	/*
603 	 * Save the command to execute on the remote host in a buffer. There
604 	 * is no limit on the length of the command, except by the maximum
605 	 * packet size.  Also sets the tty flag if there is no command.
606 	 */
607 	if (!ac) {
608 		/* No command specified - execute shell on a tty. */
609 		tty_flag = 1;
610 		if (subsystem_flag) {
611 			fprintf(stderr,
612 			    "You must specify a subsystem to invoke.\n");
613 			usage();
614 		}
615 	} else {
616 		/* A command has been specified.  Store it into the buffer. */
617 		for (i = 0; i < ac; i++) {
618 			if (i)
619 				buffer_append(&command, " ", 1);
620 			buffer_append(&command, av[i], strlen(av[i]));
621 		}
622 	}
623 
624 	/* Cannot fork to background if no command. */
625 	if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
626 	    !no_shell_flag)
627 		fatal("Cannot fork into background without a command "
628 		    "to execute.");
629 
630 	/* Allocate a tty by default if no command specified. */
631 	if (buffer_len(&command) == 0)
632 		tty_flag = 1;
633 
634 	/* Force no tty */
635 	if (no_tty_flag || muxclient_command != 0)
636 		tty_flag = 0;
637 	/* Do not allocate a tty if stdin is not a tty. */
638 	if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
639 		if (tty_flag)
640 			logit("Pseudo-terminal will not be allocated because "
641 			    "stdin is not a terminal.");
642 		tty_flag = 0;
643 	}
644 
645 	/*
646 	 * Initialize "log" output.  Since we are the client all output
647 	 * actually goes to stderr.
648 	 */
649 	log_init(argv0,
650 	    options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
651 	    SYSLOG_FACILITY_USER, !use_syslog);
652 
653 	/*
654 	 * Read per-user configuration file.  Ignore the system wide config
655 	 * file if the user specifies a config file on the command line.
656 	 */
657 	if (config != NULL) {
658 		if (!read_config_file(config, host, &options, 0))
659 			fatal("Can't open user config file %.100s: "
660 			    "%.100s", config, strerror(errno));
661 	} else {
662 		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
663 		    _PATH_SSH_USER_CONFFILE);
664 		if (r > 0 && (size_t)r < sizeof(buf))
665 			(void)read_config_file(buf, host, &options, 1);
666 
667 		/* Read systemwide configuration file after use config. */
668 		(void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
669 		    &options, 0);
670 	}
671 
672 	/* Fill configuration defaults. */
673 	fill_default_options(&options);
674 
675 	channel_set_af(options.address_family);
676 
677 	/* reinit */
678 	log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
679 
680 	if (options.user == NULL)
681 		options.user = xstrdup(pw->pw_name);
682 
683 	/* Get default port if port has not been set. */
684 	if (options.port == 0) {
685 		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
686 		options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
687 	}
688 
689 	if (options.hostname != NULL) {
690 		host = percent_expand(options.hostname,
691 		    "h", host, (char *)NULL);
692 	}
693 
694 	if (options.local_command != NULL) {
695 		char thishost[NI_MAXHOST];
696 
697 		if (gethostname(thishost, sizeof(thishost)) == -1)
698 			fatal("gethostname: %s", strerror(errno));
699 		snprintf(buf, sizeof(buf), "%d", options.port);
700 		debug3("expanding LocalCommand: %s", options.local_command);
701 		cp = options.local_command;
702 		options.local_command = percent_expand(cp, "d", pw->pw_dir,
703 		    "h", host, "l", thishost, "n", host, "r", options.user,
704 		    "p", buf, "u", pw->pw_name, (char *)NULL);
705 		debug3("expanded LocalCommand: %s", options.local_command);
706 		xfree(cp);
707 	}
708 
709 	/* force lowercase for hostkey matching */
710 	if (options.host_key_alias != NULL) {
711 		for (p = options.host_key_alias; *p; p++)
712 			if (isupper((unsigned char)*p))
713 				*p = (char)tolower((unsigned char)*p);
714 	}
715 
716 	if (options.proxy_command != NULL &&
717 	    strcmp(options.proxy_command, "none") == 0) {
718 		xfree(options.proxy_command);
719 		options.proxy_command = NULL;
720 	}
721 	if (options.control_path != NULL &&
722 	    strcmp(options.control_path, "none") == 0) {
723 		xfree(options.control_path);
724 		options.control_path = NULL;
725 	}
726 
727 	if (options.control_path != NULL) {
728 		char thishost[NI_MAXHOST];
729 
730 		if (gethostname(thishost, sizeof(thishost)) == -1)
731 			fatal("gethostname: %s", strerror(errno));
732 		snprintf(buf, sizeof(buf), "%d", options.port);
733 		cp = tilde_expand_filename(options.control_path,
734 		    original_real_uid);
735 		xfree(options.control_path);
736 		options.control_path = percent_expand(cp, "p", buf, "h", host,
737 		    "r", options.user, "l", thishost, (char *)NULL);
738 		xfree(cp);
739 	}
740 	if (muxclient_command != 0 && options.control_path == NULL)
741 		fatal("No ControlPath specified for \"-O\" command");
742 	if (options.control_path != NULL)
743 		muxclient(options.control_path);
744 
745 	timeout_ms = options.connection_timeout * 1000;
746 
747 	/* Open a connection to the remote host. */
748 	if (ssh_connect(host, &hostaddr, options.port,
749 	    options.address_family, options.connection_attempts, &timeout_ms,
750 	    options.tcp_keep_alive,
751 	    original_effective_uid == 0 && options.use_privileged_port,
752 	    options.proxy_command) != 0)
753 		exit(255);
754 
755 	if (timeout_ms > 0)
756 		debug3("timeout: %d ms remain after connect", timeout_ms);
757 
758 	/*
759 	 * If we successfully made the connection, load the host private key
760 	 * in case we will need it later for combined rsa-rhosts
761 	 * authentication. This must be done before releasing extra
762 	 * privileges, because the file is only readable by root.
763 	 * If we cannot access the private keys, load the public keys
764 	 * instead and try to execute the ssh-keysign helper instead.
765 	 */
766 	sensitive_data.nkeys = 0;
767 	sensitive_data.keys = NULL;
768 	sensitive_data.external_keysign = 0;
769 	if (options.rhosts_rsa_authentication ||
770 	    options.hostbased_authentication) {
771 		sensitive_data.nkeys = 5;
772 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
773 		    sizeof(Key));
774 
775 		PRIV_START;
776 		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
777 		    _PATH_HOST_KEY_FILE, "", NULL, NULL);
778 		sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
779 		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
780 		sensitive_data.keys[2] = key_load_private_cert(KEY_RSA,
781 		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
782 		sensitive_data.keys[3] = key_load_private_type(KEY_DSA,
783 		    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
784 		sensitive_data.keys[4] = key_load_private_type(KEY_RSA,
785 		    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
786 		PRIV_END;
787 
788 		if (options.hostbased_authentication == 1 &&
789 		    sensitive_data.keys[0] == NULL &&
790 		    sensitive_data.keys[3] == NULL &&
791 		    sensitive_data.keys[4] == NULL) {
792 			sensitive_data.keys[1] = key_load_cert(
793 			    _PATH_HOST_DSA_KEY_FILE);
794 			sensitive_data.keys[2] = key_load_cert(
795 			    _PATH_HOST_RSA_KEY_FILE);
796 			sensitive_data.keys[3] = key_load_public(
797 			    _PATH_HOST_DSA_KEY_FILE, NULL);
798 			sensitive_data.keys[4] = key_load_public(
799 			    _PATH_HOST_RSA_KEY_FILE, NULL);
800 			sensitive_data.external_keysign = 1;
801 		}
802 	}
803 	/*
804 	 * Get rid of any extra privileges that we may have.  We will no
805 	 * longer need them.  Also, extra privileges could make it very hard
806 	 * to read identity files and other non-world-readable files from the
807 	 * user's home directory if it happens to be on a NFS volume where
808 	 * root is mapped to nobody.
809 	 */
810 	if (original_effective_uid == 0) {
811 		PRIV_START;
812 		permanently_set_uid(pw);
813 	}
814 
815 	/*
816 	 * Now that we are back to our own permissions, create ~/.ssh
817 	 * directory if it doesn't already exist.
818 	 */
819 	r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
820 	    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
821 	if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
822 		if (mkdir(buf, 0700) < 0)
823 			error("Could not create directory '%.200s'.", buf);
824 
825 	/* load options.identity_files */
826 	load_public_identity_files();
827 
828 	/* Expand ~ in known host file names. */
829 	/* XXX mem-leaks: */
830 	options.system_hostfile =
831 	    tilde_expand_filename(options.system_hostfile, original_real_uid);
832 	options.user_hostfile =
833 	    tilde_expand_filename(options.user_hostfile, original_real_uid);
834 	options.system_hostfile2 =
835 	    tilde_expand_filename(options.system_hostfile2, original_real_uid);
836 	options.user_hostfile2 =
837 	    tilde_expand_filename(options.user_hostfile2, original_real_uid);
838 
839 	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
840 
841 	/* Log into the remote system.  Never returns if the login fails. */
842 	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
843 	    pw, timeout_ms);
844 
845 	if (packet_connection_is_on_socket()) {
846 		verbose("Authenticated to %s ([%s]:%d).", host,
847 		    get_remote_ipaddr(), get_remote_port());
848 	} else {
849 		verbose("Authenticated to %s (via proxy).", host);
850 	}
851 
852 	/* We no longer need the private host keys.  Clear them now. */
853 	if (sensitive_data.nkeys != 0) {
854 		for (i = 0; i < sensitive_data.nkeys; i++) {
855 			if (sensitive_data.keys[i] != NULL) {
856 				/* Destroys contents safely */
857 				debug3("clear hostkey %d", i);
858 				key_free(sensitive_data.keys[i]);
859 				sensitive_data.keys[i] = NULL;
860 			}
861 		}
862 		xfree(sensitive_data.keys);
863 	}
864 	for (i = 0; i < options.num_identity_files; i++) {
865 		if (options.identity_files[i]) {
866 			xfree(options.identity_files[i]);
867 			options.identity_files[i] = NULL;
868 		}
869 		if (options.identity_keys[i]) {
870 			key_free(options.identity_keys[i]);
871 			options.identity_keys[i] = NULL;
872 		}
873 	}
874 
875 	exit_status = compat20 ? ssh_session2() : ssh_session();
876 	packet_close();
877 
878 	if (options.control_path != NULL && muxserver_sock != -1)
879 		unlink(options.control_path);
880 
881 	/*
882 	 * Send SIGHUP to proxy command if used. We don't wait() in
883 	 * case it hangs and instead rely on init to reap the child
884 	 */
885 	if (proxy_command_pid > 1)
886 		kill(proxy_command_pid, SIGHUP);
887 
888 	return exit_status;
889 }
890 
891 static void
892 control_persist_detach(void)
893 {
894 	pid_t pid;
895 	int devnull;
896 
897 	debug("%s: backgrounding master process", __func__);
898 
899  	/*
900  	 * master (current process) into the background, and make the
901  	 * foreground process a client of the backgrounded master.
902  	 */
903 	switch ((pid = fork())) {
904 	case -1:
905 		fatal("%s: fork: %s", __func__, strerror(errno));
906 	case 0:
907 		/* Child: master process continues mainloop */
908  		break;
909  	default:
910 		/* Parent: set up mux slave to connect to backgrounded master */
911 		debug2("%s: background process is %ld", __func__, (long)pid);
912 		stdin_null_flag = ostdin_null_flag;
913 		no_shell_flag = ono_shell_flag;
914 		no_tty_flag = ono_tty_flag;
915 		tty_flag = otty_flag;
916  		close(muxserver_sock);
917  		muxserver_sock = -1;
918  		muxclient(options.control_path);
919 		/* muxclient() doesn't return on success. */
920  		fatal("Failed to connect to new control master");
921  	}
922 	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
923 		error("%s: open(\"/dev/null\"): %s", __func__,
924 		    strerror(errno));
925 	} else {
926 		if (dup2(devnull, STDIN_FILENO) == -1 ||
927 		    dup2(devnull, STDOUT_FILENO) == -1)
928 			error("%s: dup2: %s", __func__, strerror(errno));
929 		if (devnull > STDERR_FILENO)
930 			close(devnull);
931 	}
932 }
933 
934 /* Do fork() after authentication. Used by "ssh -f" */
935 static void
936 fork_postauth(void)
937 {
938 	if (need_controlpersist_detach)
939 		control_persist_detach();
940 	debug("forking to background");
941 	fork_after_authentication_flag = 0;
942 	if (daemon(1, 1) < 0)
943 		fatal("daemon() failed: %.200s", strerror(errno));
944 }
945 
946 /* Callback for remote forward global requests */
947 static void
948 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
949 {
950 	Forward *rfwd = (Forward *)ctxt;
951 
952 	/* XXX verbose() on failure? */
953 	debug("remote forward %s for: listen %d, connect %s:%d",
954 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
955 	    rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
956 	if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
957 		rfwd->allocated_port = packet_get_int();
958 		logit("Allocated port %u for remote forward to %s:%d",
959 		    rfwd->allocated_port,
960 		    rfwd->connect_host, rfwd->connect_port);
961 	}
962 
963 	if (type == SSH2_MSG_REQUEST_FAILURE) {
964 		if (options.exit_on_forward_failure)
965 			fatal("Error: remote port forwarding failed for "
966 			    "listen port %d", rfwd->listen_port);
967 		else
968 			logit("Warning: remote port forwarding failed for "
969 			    "listen port %d", rfwd->listen_port);
970 	}
971 	if (++remote_forward_confirms_received == options.num_remote_forwards) {
972 		debug("All remote forwarding requests processed");
973 		if (fork_after_authentication_flag)
974 			fork_postauth();
975 	}
976 }
977 
978 static void
979 client_cleanup_stdio_fwd(int id, void *arg)
980 {
981 	debug("stdio forwarding: done");
982 	cleanup_exit(0);
983 }
984 
985 static int
986 client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
987 {
988 	Channel *c;
989 	int in, out;
990 
991 	debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
992 	    port_to_connect);
993 
994 	in = dup(STDIN_FILENO);
995 	out = dup(STDOUT_FILENO);
996 	if (in < 0 || out < 0)
997 		fatal("channel_connect_stdio_fwd: dup() in/out failed");
998 
999 	if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
1000 	    in, out)) == NULL)
1001 		return 0;
1002 	channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1003 	return 1;
1004 }
1005 
1006 static void
1007 ssh_init_forwarding(void)
1008 {
1009 	int success = 0;
1010 	int i;
1011 
1012 	if (stdio_forward_host != NULL) {
1013 		if (!compat20) {
1014 			fatal("stdio forwarding require Protocol 2");
1015 		}
1016 		if (!client_setup_stdio_fwd(stdio_forward_host,
1017 		    stdio_forward_port))
1018 			fatal("Failed to connect in stdio forward mode.");
1019 	}
1020 
1021 	/* Initiate local TCP/IP port forwardings. */
1022 	for (i = 0; i < options.num_local_forwards; i++) {
1023 		debug("Local connections to %.200s:%d forwarded to remote "
1024 		    "address %.200s:%d",
1025 		    (options.local_forwards[i].listen_host == NULL) ?
1026 		    (options.gateway_ports ? "*" : "LOCALHOST") :
1027 		    options.local_forwards[i].listen_host,
1028 		    options.local_forwards[i].listen_port,
1029 		    options.local_forwards[i].connect_host,
1030 		    options.local_forwards[i].connect_port);
1031 		success += channel_setup_local_fwd_listener(
1032 		    options.local_forwards[i].listen_host,
1033 		    options.local_forwards[i].listen_port,
1034 		    options.local_forwards[i].connect_host,
1035 		    options.local_forwards[i].connect_port,
1036 		    options.gateway_ports);
1037 	}
1038 	if (i > 0 && success != i && options.exit_on_forward_failure)
1039 		fatal("Could not request local forwarding.");
1040 	if (i > 0 && success == 0)
1041 		error("Could not request local forwarding.");
1042 
1043 	/* Initiate remote TCP/IP port forwardings. */
1044 	for (i = 0; i < options.num_remote_forwards; i++) {
1045 		debug("Remote connections from %.200s:%d forwarded to "
1046 		    "local address %.200s:%d",
1047 		    (options.remote_forwards[i].listen_host == NULL) ?
1048 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1049 		    options.remote_forwards[i].listen_port,
1050 		    options.remote_forwards[i].connect_host,
1051 		    options.remote_forwards[i].connect_port);
1052 		if (channel_request_remote_forwarding(
1053 		    options.remote_forwards[i].listen_host,
1054 		    options.remote_forwards[i].listen_port,
1055 		    options.remote_forwards[i].connect_host,
1056 		    options.remote_forwards[i].connect_port) < 0) {
1057 			if (options.exit_on_forward_failure)
1058 				fatal("Could not request remote forwarding.");
1059 			else
1060 				logit("Warning: Could not request remote "
1061 				    "forwarding.");
1062 		}
1063 		client_register_global_confirm(ssh_confirm_remote_forward,
1064 		    &options.remote_forwards[i]);
1065 	}
1066 
1067 	/* Initiate tunnel forwarding. */
1068 	if (options.tun_open != SSH_TUNMODE_NO) {
1069 		if (client_request_tun_fwd(options.tun_open,
1070 		    options.tun_local, options.tun_remote) == -1) {
1071 			if (options.exit_on_forward_failure)
1072 				fatal("Could not request tunnel forwarding.");
1073 			else
1074 				error("Could not request tunnel forwarding.");
1075 		}
1076 	}
1077 }
1078 
1079 static void
1080 check_agent_present(void)
1081 {
1082 	if (options.forward_agent) {
1083 		/* Clear agent forwarding if we don't have an agent. */
1084 		if (!ssh_agent_present())
1085 			options.forward_agent = 0;
1086 	}
1087 }
1088 
1089 static int
1090 ssh_session(void)
1091 {
1092 	int type;
1093 	int interactive = 0;
1094 	int have_tty = 0;
1095 	struct winsize ws;
1096 	char *cp;
1097 	const char *display;
1098 
1099 	/* Enable compression if requested. */
1100 	if (options.compression) {
1101 		debug("Requesting compression at level %d.",
1102 		    options.compression_level);
1103 
1104 		if (options.compression_level < 1 ||
1105 		    options.compression_level > 9)
1106 			fatal("Compression level must be from 1 (fast) to "
1107 			    "9 (slow, best).");
1108 
1109 		/* Send the request. */
1110 		packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1111 		packet_put_int(options.compression_level);
1112 		packet_send();
1113 		packet_write_wait();
1114 		type = packet_read();
1115 		if (type == SSH_SMSG_SUCCESS)
1116 			packet_start_compression(options.compression_level);
1117 		else if (type == SSH_SMSG_FAILURE)
1118 			logit("Warning: Remote host refused compression.");
1119 		else
1120 			packet_disconnect("Protocol error waiting for "
1121 			    "compression response.");
1122 	}
1123 	/* Allocate a pseudo tty if appropriate. */
1124 	if (tty_flag) {
1125 		debug("Requesting pty.");
1126 
1127 		/* Start the packet. */
1128 		packet_start(SSH_CMSG_REQUEST_PTY);
1129 
1130 		/* Store TERM in the packet.  There is no limit on the
1131 		   length of the string. */
1132 		cp = getenv("TERM");
1133 		if (!cp)
1134 			cp = "";
1135 		packet_put_cstring(cp);
1136 
1137 		/* Store window size in the packet. */
1138 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1139 			memset(&ws, 0, sizeof(ws));
1140 		packet_put_int((u_int)ws.ws_row);
1141 		packet_put_int((u_int)ws.ws_col);
1142 		packet_put_int((u_int)ws.ws_xpixel);
1143 		packet_put_int((u_int)ws.ws_ypixel);
1144 
1145 		/* Store tty modes in the packet. */
1146 		tty_make_modes(fileno(stdin), NULL);
1147 
1148 		/* Send the packet, and wait for it to leave. */
1149 		packet_send();
1150 		packet_write_wait();
1151 
1152 		/* Read response from the server. */
1153 		type = packet_read();
1154 		if (type == SSH_SMSG_SUCCESS) {
1155 			interactive = 1;
1156 			have_tty = 1;
1157 		} else if (type == SSH_SMSG_FAILURE)
1158 			logit("Warning: Remote host failed or refused to "
1159 			    "allocate a pseudo tty.");
1160 		else
1161 			packet_disconnect("Protocol error waiting for pty "
1162 			    "request response.");
1163 	}
1164 	/* Request X11 forwarding if enabled and DISPLAY is set. */
1165 	display = getenv("DISPLAY");
1166 	if (options.forward_x11 && display != NULL) {
1167 		char *proto, *data;
1168 		/* Get reasonable local authentication information. */
1169 		client_x11_get_proto(display, options.xauth_location,
1170 		    options.forward_x11_trusted,
1171 		    options.forward_x11_timeout,
1172 		    &proto, &data);
1173 		/* Request forwarding with authentication spoofing. */
1174 		debug("Requesting X11 forwarding with authentication "
1175 		    "spoofing.");
1176 		x11_request_forwarding_with_spoofing(0, display, proto, data);
1177 
1178 		/* Read response from the server. */
1179 		type = packet_read();
1180 		if (type == SSH_SMSG_SUCCESS) {
1181 			interactive = 1;
1182 		} else if (type == SSH_SMSG_FAILURE) {
1183 			logit("Warning: Remote host denied X11 forwarding.");
1184 		} else {
1185 			packet_disconnect("Protocol error waiting for X11 "
1186 			    "forwarding");
1187 		}
1188 	}
1189 	/* Tell the packet module whether this is an interactive session. */
1190 	packet_set_interactive(interactive);
1191 
1192 	/* Request authentication agent forwarding if appropriate. */
1193 	check_agent_present();
1194 
1195 	if (options.forward_agent) {
1196 		debug("Requesting authentication agent forwarding.");
1197 		auth_request_forwarding();
1198 
1199 		/* Read response from the server. */
1200 		type = packet_read();
1201 		packet_check_eom();
1202 		if (type != SSH_SMSG_SUCCESS)
1203 			logit("Warning: Remote host denied authentication agent forwarding.");
1204 	}
1205 
1206 	/* Initiate port forwardings. */
1207 	ssh_init_forwarding();
1208 
1209 	/* Execute a local command */
1210 	if (options.local_command != NULL &&
1211 	    options.permit_local_command)
1212 		ssh_local_cmd(options.local_command);
1213 
1214 	/*
1215 	 * If requested and we are not interested in replies to remote
1216 	 * forwarding requests, then let ssh continue in the background.
1217 	 */
1218 	if (fork_after_authentication_flag) {
1219 		if (options.exit_on_forward_failure &&
1220 		    options.num_remote_forwards > 0) {
1221 			debug("deferring postauth fork until remote forward "
1222 			    "confirmation received");
1223 		} else
1224 			fork_postauth();
1225 	}
1226 
1227 	/*
1228 	 * If a command was specified on the command line, execute the
1229 	 * command now. Otherwise request the server to start a shell.
1230 	 */
1231 	if (buffer_len(&command) > 0) {
1232 		int len = buffer_len(&command);
1233 		if (len > 900)
1234 			len = 900;
1235 		debug("Sending command: %.*s", len,
1236 		    (u_char *)buffer_ptr(&command));
1237 		packet_start(SSH_CMSG_EXEC_CMD);
1238 		packet_put_string(buffer_ptr(&command), buffer_len(&command));
1239 		packet_send();
1240 		packet_write_wait();
1241 	} else {
1242 		debug("Requesting shell.");
1243 		packet_start(SSH_CMSG_EXEC_SHELL);
1244 		packet_send();
1245 		packet_write_wait();
1246 	}
1247 
1248 	/* Enter the interactive session. */
1249 	return client_loop(have_tty, tty_flag ?
1250 	    options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1251 }
1252 
1253 /* request pty/x11/agent/tcpfwd/shell for channel */
1254 static void
1255 ssh_session2_setup(int id, int success, void *arg)
1256 {
1257 	extern char **environ;
1258 	const char *display;
1259 	int interactive = tty_flag;
1260 
1261 	if (!success)
1262 		return; /* No need for error message, channels code sens one */
1263 
1264 	display = getenv("DISPLAY");
1265 	if (options.forward_x11 && display != NULL) {
1266 		char *proto, *data;
1267 		/* Get reasonable local authentication information. */
1268 		client_x11_get_proto(display, options.xauth_location,
1269 		    options.forward_x11_trusted,
1270 		    options.forward_x11_timeout, &proto, &data);
1271 		/* Request forwarding with authentication spoofing. */
1272 		debug("Requesting X11 forwarding with authentication "
1273 		    "spoofing.");
1274 		x11_request_forwarding_with_spoofing(id, display, proto, data);
1275 		interactive = 1;
1276 		/* XXX wait for reply */
1277 	}
1278 
1279 	check_agent_present();
1280 	if (options.forward_agent) {
1281 		debug("Requesting authentication agent forwarding.");
1282 		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1283 		packet_send();
1284 	}
1285 
1286 	client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1287 	    NULL, fileno(stdin), &command, environ);
1288 
1289 	packet_set_interactive(interactive);
1290 }
1291 
1292 /* open new channel for a session */
1293 static int
1294 ssh_session2_open(void)
1295 {
1296 	Channel *c;
1297 	int window, packetmax, in, out, err;
1298 	int sock;
1299 	int socksize;
1300 	socklen_t socksizelen = sizeof(int);
1301 
1302 	if (stdin_null_flag) {
1303 		in = open(_PATH_DEVNULL, O_RDONLY);
1304 	} else {
1305 		in = dup(STDIN_FILENO);
1306 	}
1307 	out = dup(STDOUT_FILENO);
1308 	err = dup(STDERR_FILENO);
1309 
1310 	if (in < 0 || out < 0 || err < 0)
1311 		fatal("dup() in/out/err failed");
1312 
1313 	/* enable nonblocking unless tty */
1314 	if (!isatty(in))
1315 		set_nonblock(in);
1316 	if (!isatty(out))
1317 		set_nonblock(out);
1318 	if (!isatty(err))
1319 		set_nonblock(err);
1320 
1321 	/* we need to check to see if what they want to do about buffer */
1322 	/* sizes here. In a hpn to nonhpn connection we want to limit */
1323 	/* the window size to something reasonable in case the far side */
1324 	/* has the large window bug. In hpn to hpn connection we want to */
1325 	/* use the max window size but allow the user to override it */
1326 	/* lastly if they disabled hpn then use the ssh std window size */
1327 
1328 	/* so why don't we just do a getsockopt() here and set the */
1329 	/* ssh window to that? In the case of a autotuning receive */
1330 	/* window the window would get stuck at the initial buffer */
1331 	/* size generally less than 96k. Therefore we need to set the */
1332 	/* maximum ssh window size to the maximum hpn buffer size */
1333 	/* unless the user has specifically set the tcprcvbufpoll */
1334 	/* to no. In which case we *can* just set the window to the */
1335 	/* minimum of the hpn buffer size and tcp receive buffer size */
1336 
1337 	if (tty_flag)
1338 		options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1339 	else
1340 		options.hpn_buffer_size = 2*1024*1024;
1341 
1342 	if (datafellows & SSH_BUG_LARGEWINDOW)
1343 	{
1344 		debug("HPN to Non-HPN Connection");
1345 	}
1346 	else
1347 	{
1348 		if (options.tcp_rcv_buf_poll <= 0)
1349 		{
1350 			sock = socket(AF_INET, SOCK_STREAM, 0);
1351 			getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1352 				   &socksize, &socksizelen);
1353 			close(sock);
1354 			debug("socksize %d", socksize);
1355 			options.hpn_buffer_size = socksize;
1356 			debug ("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size);
1357 		}
1358 		else
1359 		{
1360 			if (options.tcp_rcv_buf > 0)
1361 			{
1362 				/*create a socket but don't connect it */
1363 				/* we use that the get the rcv socket size */
1364 				sock = socket(AF_INET, SOCK_STREAM, 0);
1365 				/* if they are using the tcp_rcv_buf option */
1366 				/* attempt to set the buffer size to that */
1367 				if (options.tcp_rcv_buf)
1368 					setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf,
1369 						   sizeof(options.tcp_rcv_buf));
1370 				getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1371 					   &socksize, &socksizelen);
1372 				close(sock);
1373 				debug("socksize %d", socksize);
1374 				options.hpn_buffer_size = socksize;
1375 				debug ("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size);
1376 			}
1377  		}
1378 
1379 	}
1380 
1381 	debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1382 
1383 	window = options.hpn_buffer_size;
1384 
1385 	channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1386 
1387 	packetmax = CHAN_SES_PACKET_DEFAULT;
1388 	if (tty_flag) {
1389 		window = 4*CHAN_SES_PACKET_DEFAULT;
1390 		window >>= 1;
1391 		packetmax >>= 1;
1392 	}
1393 	c = channel_new(
1394 	    "session", SSH_CHANNEL_OPENING, in, out, err,
1395 	    window, packetmax, CHAN_EXTENDED_WRITE,
1396 	    "client-session", /*nonblock*/0);
1397 
1398 	if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1399 		c->dynamic_window = 1;
1400 		debug ("Enabled Dynamic Window Scaling\n");
1401 	}
1402 	debug3("ssh_session2_open: channel_new: %d", c->self);
1403 
1404 	channel_send_open(c->self);
1405 	if (!no_shell_flag)
1406 		channel_register_open_confirm(c->self,
1407 		    ssh_session2_setup, NULL);
1408 
1409 	return c->self;
1410 }
1411 
1412 static int
1413 ssh_session2(void)
1414 {
1415 	int id = -1;
1416 
1417 	/* XXX should be pre-session */
1418 	ssh_init_forwarding();
1419 
1420 	/* Start listening for multiplex clients */
1421 	muxserver_listen();
1422 
1423  	/*
1424 	 * If we are in control persist mode, then prepare to background
1425 	 * ourselves and have a foreground client attach as a control
1426 	 * slave. NB. we must save copies of the flags that we override for
1427 	 * the backgrounding, since we defer attachment of the slave until
1428 	 * after the connection is fully established (in particular,
1429 	 * async rfwd replies have been received for ExitOnForwardFailure).
1430 	 */
1431  	if (options.control_persist && muxserver_sock != -1) {
1432 		ostdin_null_flag = stdin_null_flag;
1433 		ono_shell_flag = no_shell_flag;
1434 		ono_tty_flag = no_tty_flag;
1435 		otty_flag = tty_flag;
1436  		stdin_null_flag = 1;
1437  		no_shell_flag = 1;
1438  		no_tty_flag = 1;
1439  		tty_flag = 0;
1440 		if (!fork_after_authentication_flag)
1441 			need_controlpersist_detach = 1;
1442 		fork_after_authentication_flag = 1;
1443  	}
1444 
1445 	if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1446 		id = ssh_session2_open();
1447 
1448 	/* If we don't expect to open a new session, then disallow it */
1449 	if (options.control_master == SSHCTL_MASTER_NO &&
1450 	    (datafellows & SSH_NEW_OPENSSH)) {
1451 		debug("Requesting no-more-sessions@openssh.com");
1452 		packet_start(SSH2_MSG_GLOBAL_REQUEST);
1453 		packet_put_cstring("no-more-sessions@openssh.com");
1454 		packet_put_char(0);
1455 		packet_send();
1456 	}
1457 
1458 	/* Execute a local command */
1459 	if (options.local_command != NULL &&
1460 	    options.permit_local_command)
1461 		ssh_local_cmd(options.local_command);
1462 
1463 	/*
1464 	 * If requested and we are not interested in replies to remote
1465 	 * forwarding requests, then let ssh continue in the background.
1466 	 */
1467 	if (fork_after_authentication_flag) {
1468 		if (options.exit_on_forward_failure &&
1469 		    options.num_remote_forwards > 0) {
1470 			debug("deferring postauth fork until remote forward "
1471 			    "confirmation received");
1472 		} else
1473 			fork_postauth();
1474 	}
1475 
1476 	if (options.use_roaming)
1477 		request_roaming();
1478 
1479 	return client_loop(tty_flag, tty_flag ?
1480 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1481 }
1482 
1483 static void
1484 load_public_identity_files(void)
1485 {
1486 	char *filename, *cp, thishost[NI_MAXHOST];
1487 	char *pwdir = NULL, *pwname = NULL;
1488 	int i = 0;
1489 	Key *public;
1490 	struct passwd *pw;
1491 	u_int n_ids;
1492 	char *identity_files[SSH_MAX_IDENTITY_FILES];
1493 	Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1494 #ifdef ENABLE_PKCS11
1495 	Key **keys;
1496 	int nkeys;
1497 #endif /* PKCS11 */
1498 
1499 	n_ids = 0;
1500 	bzero(identity_files, sizeof(identity_files));
1501 	bzero(identity_keys, sizeof(identity_keys));
1502 
1503 #ifdef ENABLE_PKCS11
1504 	if (options.pkcs11_provider != NULL &&
1505 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1506 	    (pkcs11_init(!options.batch_mode) == 0) &&
1507 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1508 	    &keys)) > 0) {
1509 		for (i = 0; i < nkeys; i++) {
1510 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1511 				key_free(keys[i]);
1512 				continue;
1513 			}
1514 			identity_keys[n_ids] = keys[i];
1515 			identity_files[n_ids] =
1516 			    xstrdup(options.pkcs11_provider); /* XXX */
1517 			n_ids++;
1518 		}
1519 		xfree(keys);
1520 	}
1521 #endif /* ENABLE_PKCS11 */
1522 	if ((pw = getpwuid(original_real_uid)) == NULL)
1523 		fatal("load_public_identity_files: getpwuid failed");
1524 	pwname = xstrdup(pw->pw_name);
1525 	pwdir = xstrdup(pw->pw_dir);
1526 	if (gethostname(thishost, sizeof(thishost)) == -1)
1527 		fatal("load_public_identity_files: gethostname: %s",
1528 		    strerror(errno));
1529 	for (i = 0; i < options.num_identity_files; i++) {
1530 		if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1531 			xfree(options.identity_files[i]);
1532 			continue;
1533 		}
1534 		cp = tilde_expand_filename(options.identity_files[i],
1535 		    original_real_uid);
1536 		filename = percent_expand(cp, "d", pwdir,
1537 		    "u", pwname, "l", thishost, "h", host,
1538 		    "r", options.user, (char *)NULL);
1539 		xfree(cp);
1540 		public = key_load_public(filename, NULL);
1541 		debug("identity file %s type %d", filename,
1542 		    public ? public->type : -1);
1543 		xfree(options.identity_files[i]);
1544 		identity_files[n_ids] = filename;
1545 		identity_keys[n_ids] = public;
1546 
1547 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1548 			continue;
1549 
1550 		/* Try to add the certificate variant too */
1551 		xasprintf(&cp, "%s-cert", filename);
1552 		public = key_load_public(cp, NULL);
1553 		debug("identity file %s type %d", cp,
1554 		    public ? public->type : -1);
1555 		if (public == NULL) {
1556 			xfree(cp);
1557 			continue;
1558 		}
1559 		if (!key_is_cert(public)) {
1560 			debug("%s: key %s type %s is not a certificate",
1561 			    __func__, cp, key_type(public));
1562 			key_free(public);
1563 			xfree(cp);
1564 			continue;
1565 		}
1566 		identity_keys[n_ids] = public;
1567 		/* point to the original path, most likely the private key */
1568 		identity_files[n_ids] = xstrdup(filename);
1569 		n_ids++;
1570 	}
1571 	options.num_identity_files = n_ids;
1572 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
1573 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1574 
1575 	bzero(pwname, strlen(pwname));
1576 	xfree(pwname);
1577 	bzero(pwdir, strlen(pwdir));
1578 	xfree(pwdir);
1579 }
1580