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