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