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