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