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