xref: /openbsd-src/usr.bin/ssh/ssh.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /* $OpenBSD: ssh.c,v 1.325 2009/03/17 21:37:00 markus 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/queue.h>
46 #include <sys/resource.h>
47 #include <sys/socket.h>
48 #include <sys/stat.h>
49 #include <sys/types.h>
50 #include <sys/time.h>
51 
52 #include <ctype.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <netdb.h>
56 #include <paths.h>
57 #include <pwd.h>
58 #include <signal.h>
59 #include <stddef.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 
65 #include <openssl/evp.h>
66 #include <openssl/err.h>
67 
68 #include "xmalloc.h"
69 #include "ssh.h"
70 #include "ssh1.h"
71 #include "ssh2.h"
72 #include "compat.h"
73 #include "cipher.h"
74 #include "packet.h"
75 #include "buffer.h"
76 #include "channels.h"
77 #include "key.h"
78 #include "authfd.h"
79 #include "authfile.h"
80 #include "pathnames.h"
81 #include "dispatch.h"
82 #include "clientloop.h"
83 #include "log.h"
84 #include "readconf.h"
85 #include "sshconnect.h"
86 #include "misc.h"
87 #include "kex.h"
88 #include "mac.h"
89 #include "sshpty.h"
90 #include "match.h"
91 #include "msg.h"
92 #include "uidswap.h"
93 #include "version.h"
94 
95 #ifdef SMARTCARD
96 #include "scard.h"
97 #endif
98 
99 extern char *__progname;
100 
101 /* Flag indicating whether debug mode is on.  May be set on the command line. */
102 int debug_flag = 0;
103 
104 /* Flag indicating whether a tty should be allocated */
105 int tty_flag = 0;
106 int no_tty_flag = 0;
107 int force_tty_flag = 0;
108 
109 /* don't exec a shell */
110 int no_shell_flag = 0;
111 
112 /*
113  * Flag indicating that nothing should be read from stdin.  This can be set
114  * on the command line.
115  */
116 int stdin_null_flag = 0;
117 
118 /*
119  * Flag indicating that ssh should fork after authentication.  This is useful
120  * so that the passphrase can be entered manually, and then ssh goes to the
121  * background.
122  */
123 int fork_after_authentication_flag = 0;
124 
125 /*
126  * General data structure for command line options and options configurable
127  * in configuration files.  See readconf.h.
128  */
129 Options options;
130 
131 /* optional user configfile */
132 char *config = NULL;
133 
134 /*
135  * Name of the host we are connecting to.  This is the name given on the
136  * command line, or the HostName specified for the user-supplied name in a
137  * configuration file.
138  */
139 char *host;
140 
141 /* socket address the host resolves to */
142 struct sockaddr_storage hostaddr;
143 
144 /* Private host keys. */
145 Sensitive sensitive_data;
146 
147 /* Original real UID. */
148 uid_t original_real_uid;
149 uid_t original_effective_uid;
150 
151 /* command to be executed */
152 Buffer command;
153 
154 /* Should we execute a command or invoke a subsystem? */
155 int subsystem_flag = 0;
156 
157 /* # of replies received for global requests */
158 static int remote_forward_confirms_received = 0;
159 
160 /* pid of proxycommand child process */
161 pid_t proxy_command_pid = 0;
162 
163 /* mux.c */
164 extern int muxserver_sock;
165 extern u_int muxclient_command;
166 
167 
168 /* Prints a help message to the user.  This function never returns. */
169 
170 static void
171 usage(void)
172 {
173 	fprintf(stderr,
174 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
175 "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
176 "           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
177 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
178 "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
179 "           [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
180 	);
181 	exit(255);
182 }
183 
184 static int ssh_session(void);
185 static int ssh_session2(void);
186 static void load_public_identity_files(void);
187 
188 /* from muxclient.c */
189 void muxclient(const char *);
190 void muxserver_listen(void);
191 
192 /*
193  * Main program for the ssh client.
194  */
195 int
196 main(int ac, char **av)
197 {
198 	int i, opt, exit_status, use_syslog;
199 	char *p, *cp, *line, *argv0, buf[256];
200 	struct stat st;
201 	struct passwd *pw;
202 	int dummy, timeout_ms;
203 	extern int optind, optreset;
204 	extern char *optarg;
205 	struct servent *sp;
206 	Forward fwd;
207 
208 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
209 	sanitise_stdfd();
210 
211 	/*
212 	 * Save the original real uid.  It will be needed later (uid-swapping
213 	 * may clobber the real uid).
214 	 */
215 	original_real_uid = getuid();
216 	original_effective_uid = geteuid();
217 
218 	/*
219 	 * Use uid-swapping to give up root privileges for the duration of
220 	 * option processing.  We will re-instantiate the rights when we are
221 	 * ready to create the privileged port, and will permanently drop
222 	 * them when the port has been created (actually, when the connection
223 	 * has been made, as we may need to create the port several times).
224 	 */
225 	PRIV_END;
226 
227 	/* If we are installed setuid root be careful to not drop core. */
228 	if (original_real_uid != original_effective_uid) {
229 		struct rlimit rlim;
230 		rlim.rlim_cur = rlim.rlim_max = 0;
231 		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
232 			fatal("setrlimit failed: %.100s", strerror(errno));
233 	}
234 	/* Get user data. */
235 	pw = getpwuid(original_real_uid);
236 	if (!pw) {
237 		logit("You don't exist, go away!");
238 		exit(255);
239 	}
240 	/* Take a copy of the returned structure. */
241 	pw = pwcopy(pw);
242 
243 	/*
244 	 * Set our umask to something reasonable, as some files are created
245 	 * with the default umask.  This will make them world-readable but
246 	 * writable only by the owner, which is ok for all files for which we
247 	 * don't set the modes explicitly.
248 	 */
249 	umask(022);
250 
251 	/*
252 	 * Initialize option structure to indicate that no values have been
253 	 * set.
254 	 */
255 	initialize_options(&options);
256 
257 	/* Parse command-line arguments. */
258 	host = NULL;
259 	use_syslog = 0;
260 	argv0 = av[0];
261 
262  again:
263 	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
264 	    "ACD:F:I:KL:MNO:PR:S:TVw:XYy")) != -1) {
265 		switch (opt) {
266 		case '1':
267 			options.protocol = SSH_PROTO_1;
268 			break;
269 		case '2':
270 			options.protocol = SSH_PROTO_2;
271 			break;
272 		case '4':
273 			options.address_family = AF_INET;
274 			break;
275 		case '6':
276 			options.address_family = AF_INET6;
277 			break;
278 		case 'n':
279 			stdin_null_flag = 1;
280 			break;
281 		case 'f':
282 			fork_after_authentication_flag = 1;
283 			stdin_null_flag = 1;
284 			break;
285 		case 'x':
286 			options.forward_x11 = 0;
287 			break;
288 		case 'X':
289 			options.forward_x11 = 1;
290 			break;
291 		case 'y':
292 			use_syslog = 1;
293 			break;
294 		case 'Y':
295 			options.forward_x11 = 1;
296 			options.forward_x11_trusted = 1;
297 			break;
298 		case 'g':
299 			options.gateway_ports = 1;
300 			break;
301 		case 'O':
302 			if (strcmp(optarg, "check") == 0)
303 				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
304 			else if (strcmp(optarg, "exit") == 0)
305 				muxclient_command = SSHMUX_COMMAND_TERMINATE;
306 			else
307 				fatal("Invalid multiplex command.");
308 			break;
309 		case 'P':	/* deprecated */
310 			options.use_privileged_port = 0;
311 			break;
312 		case 'a':
313 			options.forward_agent = 0;
314 			break;
315 		case 'A':
316 			options.forward_agent = 1;
317 			break;
318 		case 'k':
319 			options.gss_deleg_creds = 0;
320 			break;
321 		case 'K':
322 			options.gss_authentication = 1;
323 			options.gss_deleg_creds = 1;
324 			break;
325 		case 'i':
326 			if (stat(optarg, &st) < 0) {
327 				fprintf(stderr, "Warning: Identity file %s "
328 				    "not accessible: %s.\n", optarg,
329 				    strerror(errno));
330 				break;
331 			}
332 			if (options.num_identity_files >=
333 			    SSH_MAX_IDENTITY_FILES)
334 				fatal("Too many identity files specified "
335 				    "(max %d)", SSH_MAX_IDENTITY_FILES);
336 			options.identity_files[options.num_identity_files++] =
337 			    xstrdup(optarg);
338 			break;
339 		case 'I':
340 #ifdef SMARTCARD
341 			options.smartcard_device = xstrdup(optarg);
342 #else
343 			fprintf(stderr, "no support for smartcards.\n");
344 #endif
345 			break;
346 		case 't':
347 			if (tty_flag)
348 				force_tty_flag = 1;
349 			tty_flag = 1;
350 			break;
351 		case 'v':
352 			if (debug_flag == 0) {
353 				debug_flag = 1;
354 				options.log_level = SYSLOG_LEVEL_DEBUG1;
355 			} else {
356 				if (options.log_level < SYSLOG_LEVEL_DEBUG3)
357 					options.log_level++;
358 				break;
359 			}
360 			/* FALLTHROUGH */
361 		case 'V':
362 			fprintf(stderr, "%s, %s\n",
363 			    SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
364 			if (opt == 'V')
365 				exit(0);
366 			break;
367 		case 'w':
368 			if (options.tun_open == -1)
369 				options.tun_open = SSH_TUNMODE_DEFAULT;
370 			options.tun_local = a2tun(optarg, &options.tun_remote);
371 			if (options.tun_local == SSH_TUNID_ERR) {
372 				fprintf(stderr,
373 				    "Bad tun device '%s'\n", optarg);
374 				exit(255);
375 			}
376 			break;
377 		case 'q':
378 			options.log_level = SYSLOG_LEVEL_QUIET;
379 			break;
380 		case 'e':
381 			if (optarg[0] == '^' && optarg[2] == 0 &&
382 			    (u_char) optarg[1] >= 64 &&
383 			    (u_char) optarg[1] < 128)
384 				options.escape_char = (u_char) optarg[1] & 31;
385 			else if (strlen(optarg) == 1)
386 				options.escape_char = (u_char) optarg[0];
387 			else if (strcmp(optarg, "none") == 0)
388 				options.escape_char = SSH_ESCAPECHAR_NONE;
389 			else {
390 				fprintf(stderr, "Bad escape character '%s'.\n",
391 				    optarg);
392 				exit(255);
393 			}
394 			break;
395 		case 'c':
396 			if (ciphers_valid(optarg)) {
397 				/* SSH2 only */
398 				options.ciphers = xstrdup(optarg);
399 				options.cipher = SSH_CIPHER_INVALID;
400 			} else {
401 				/* SSH1 only */
402 				options.cipher = cipher_number(optarg);
403 				if (options.cipher == -1) {
404 					fprintf(stderr,
405 					    "Unknown cipher type '%s'\n",
406 					    optarg);
407 					exit(255);
408 				}
409 				if (options.cipher == SSH_CIPHER_3DES)
410 					options.ciphers = "3des-cbc";
411 				else if (options.cipher == SSH_CIPHER_BLOWFISH)
412 					options.ciphers = "blowfish-cbc";
413 				else
414 					options.ciphers = (char *)-1;
415 			}
416 			break;
417 		case 'm':
418 			if (mac_valid(optarg))
419 				options.macs = xstrdup(optarg);
420 			else {
421 				fprintf(stderr, "Unknown mac type '%s'\n",
422 				    optarg);
423 				exit(255);
424 			}
425 			break;
426 		case 'M':
427 			if (options.control_master == SSHCTL_MASTER_YES)
428 				options.control_master = SSHCTL_MASTER_ASK;
429 			else
430 				options.control_master = SSHCTL_MASTER_YES;
431 			break;
432 		case 'p':
433 			options.port = a2port(optarg);
434 			if (options.port <= 0) {
435 				fprintf(stderr, "Bad port '%s'\n", optarg);
436 				exit(255);
437 			}
438 			break;
439 		case 'l':
440 			options.user = optarg;
441 			break;
442 
443 		case 'L':
444 			if (parse_forward(&fwd, optarg, 0, 0))
445 				add_local_forward(&options, &fwd);
446 			else {
447 				fprintf(stderr,
448 				    "Bad local forwarding specification '%s'\n",
449 				    optarg);
450 				exit(255);
451 			}
452 			break;
453 
454 		case 'R':
455 			if (parse_forward(&fwd, optarg, 0, 1)) {
456 				add_remote_forward(&options, &fwd);
457 			} else {
458 				fprintf(stderr,
459 				    "Bad remote forwarding specification "
460 				    "'%s'\n", optarg);
461 				exit(255);
462 			}
463 			break;
464 
465 		case 'D':
466 			if (parse_forward(&fwd, optarg, 1, 0)) {
467 				add_local_forward(&options, &fwd);
468 			} else {
469 				fprintf(stderr,
470 				    "Bad dynamic forwarding specification "
471 				    "'%s'\n", optarg);
472 				exit(255);
473 			}
474 			break;
475 
476 		case 'C':
477 			options.compression = 1;
478 			break;
479 		case 'N':
480 			no_shell_flag = 1;
481 			no_tty_flag = 1;
482 			break;
483 		case 'T':
484 			no_tty_flag = 1;
485 			break;
486 		case 'o':
487 			dummy = 1;
488 			line = xstrdup(optarg);
489 			if (process_config_line(&options, host ? host : "",
490 			    line, "command-line", 0, &dummy) != 0)
491 				exit(255);
492 			xfree(line);
493 			break;
494 		case 's':
495 			subsystem_flag = 1;
496 			break;
497 		case 'S':
498 			if (options.control_path != NULL)
499 				free(options.control_path);
500 			options.control_path = xstrdup(optarg);
501 			break;
502 		case 'b':
503 			options.bind_address = optarg;
504 			break;
505 		case 'F':
506 			config = optarg;
507 			break;
508 		default:
509 			usage();
510 		}
511 	}
512 
513 	ac -= optind;
514 	av += optind;
515 
516 	if (ac > 0 && !host && **av != '-') {
517 		if (strrchr(*av, '@')) {
518 			p = xstrdup(*av);
519 			cp = strrchr(p, '@');
520 			if (cp == NULL || cp == p)
521 				usage();
522 			options.user = p;
523 			*cp = '\0';
524 			host = ++cp;
525 		} else
526 			host = *av;
527 		if (ac > 1) {
528 			optind = optreset = 1;
529 			goto again;
530 		}
531 		ac--, av++;
532 	}
533 
534 	/* Check that we got a host name. */
535 	if (!host)
536 		usage();
537 
538 	SSLeay_add_all_algorithms();
539 	ERR_load_crypto_strings();
540 
541 	/* Initialize the command to execute on remote host. */
542 	buffer_init(&command);
543 
544 	/*
545 	 * Save the command to execute on the remote host in a buffer. There
546 	 * is no limit on the length of the command, except by the maximum
547 	 * packet size.  Also sets the tty flag if there is no command.
548 	 */
549 	if (!ac) {
550 		/* No command specified - execute shell on a tty. */
551 		tty_flag = 1;
552 		if (subsystem_flag) {
553 			fprintf(stderr,
554 			    "You must specify a subsystem to invoke.\n");
555 			usage();
556 		}
557 	} else {
558 		/* A command has been specified.  Store it into the buffer. */
559 		for (i = 0; i < ac; i++) {
560 			if (i)
561 				buffer_append(&command, " ", 1);
562 			buffer_append(&command, av[i], strlen(av[i]));
563 		}
564 	}
565 
566 	/* Cannot fork to background if no command. */
567 	if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
568 	    !no_shell_flag)
569 		fatal("Cannot fork into background without a command "
570 		    "to execute.");
571 
572 	/* Allocate a tty by default if no command specified. */
573 	if (buffer_len(&command) == 0)
574 		tty_flag = 1;
575 
576 	/* Force no tty */
577 	if (no_tty_flag)
578 		tty_flag = 0;
579 	/* Do not allocate a tty if stdin is not a tty. */
580 	if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
581 		if (tty_flag)
582 			logit("Pseudo-terminal will not be allocated because "
583 			    "stdin is not a terminal.");
584 		tty_flag = 0;
585 	}
586 
587 	/*
588 	 * Initialize "log" output.  Since we are the client all output
589 	 * actually goes to stderr.
590 	 */
591 	log_init(argv0,
592 	    options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
593 	    SYSLOG_FACILITY_USER, !use_syslog);
594 
595 	/*
596 	 * Read per-user configuration file.  Ignore the system wide config
597 	 * file if the user specifies a config file on the command line.
598 	 */
599 	if (config != NULL) {
600 		if (!read_config_file(config, host, &options, 0))
601 			fatal("Can't open user config file %.100s: "
602 			    "%.100s", config, strerror(errno));
603 	} else {
604 		snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
605 		    _PATH_SSH_USER_CONFFILE);
606 		(void)read_config_file(buf, host, &options, 1);
607 
608 		/* Read systemwide configuration file after use config. */
609 		(void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
610 		    &options, 0);
611 	}
612 
613 	/* Fill configuration defaults. */
614 	fill_default_options(&options);
615 
616 	channel_set_af(options.address_family);
617 
618 	/* reinit */
619 	log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
620 
621 	if (options.user == NULL)
622 		options.user = xstrdup(pw->pw_name);
623 
624 	/* Get default port if port has not been set. */
625 	if (options.port == 0) {
626 		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
627 		options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
628 	}
629 
630 	if (options.local_command != NULL) {
631 		char thishost[NI_MAXHOST];
632 
633 		if (gethostname(thishost, sizeof(thishost)) == -1)
634 			fatal("gethostname: %s", strerror(errno));
635 		snprintf(buf, sizeof(buf), "%d", options.port);
636 		debug3("expanding LocalCommand: %s", options.local_command);
637 		cp = options.local_command;
638 		options.local_command = percent_expand(cp, "d", pw->pw_dir,
639 		    "h", options.hostname? options.hostname : host,
640                     "l", thishost, "n", host, "r", options.user, "p", buf,
641                     "u", pw->pw_name, (char *)NULL);
642 		debug3("expanded LocalCommand: %s", options.local_command);
643 		xfree(cp);
644 	}
645 
646 	if (options.hostname != NULL)
647 		host = options.hostname;
648 
649 	/* force lowercase for hostkey matching */
650 	if (options.host_key_alias != NULL) {
651 		for (p = options.host_key_alias; *p; p++)
652 			if (isupper(*p))
653 				*p = (char)tolower(*p);
654 	}
655 
656 	if (options.proxy_command != NULL &&
657 	    strcmp(options.proxy_command, "none") == 0) {
658 		xfree(options.proxy_command);
659 		options.proxy_command = NULL;
660 	}
661 	if (options.control_path != NULL &&
662 	    strcmp(options.control_path, "none") == 0) {
663 		xfree(options.control_path);
664 		options.control_path = NULL;
665 	}
666 
667 	if (options.control_path != NULL) {
668 		char thishost[NI_MAXHOST];
669 
670 		if (gethostname(thishost, sizeof(thishost)) == -1)
671 			fatal("gethostname: %s", strerror(errno));
672 		snprintf(buf, sizeof(buf), "%d", options.port);
673 		cp = tilde_expand_filename(options.control_path,
674 		    original_real_uid);
675 		xfree(options.control_path);
676 		options.control_path = percent_expand(cp, "p", buf, "h", host,
677 		    "r", options.user, "l", thishost, (char *)NULL);
678 		xfree(cp);
679 	}
680 	if (muxclient_command != 0 && options.control_path == NULL)
681 		fatal("No ControlPath specified for \"-O\" command");
682 	if (options.control_path != NULL)
683 		muxclient(options.control_path);
684 
685 	timeout_ms = options.connection_timeout * 1000;
686 
687 	/* Open a connection to the remote host. */
688 	if (ssh_connect(host, &hostaddr, options.port,
689 	    options.address_family, options.connection_attempts, &timeout_ms,
690 	    options.tcp_keep_alive,
691 	    original_effective_uid == 0 && options.use_privileged_port,
692 	    options.proxy_command) != 0)
693 		exit(255);
694 
695 	if (timeout_ms > 0)
696 		debug3("timeout: %d ms remain after connect", timeout_ms);
697 
698 	/*
699 	 * If we successfully made the connection, load the host private key
700 	 * in case we will need it later for combined rsa-rhosts
701 	 * authentication. This must be done before releasing extra
702 	 * privileges, because the file is only readable by root.
703 	 * If we cannot access the private keys, load the public keys
704 	 * instead and try to execute the ssh-keysign helper instead.
705 	 */
706 	sensitive_data.nkeys = 0;
707 	sensitive_data.keys = NULL;
708 	sensitive_data.external_keysign = 0;
709 	if (options.rhosts_rsa_authentication ||
710 	    options.hostbased_authentication) {
711 		sensitive_data.nkeys = 3;
712 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
713 		    sizeof(Key));
714 
715 		PRIV_START;
716 		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
717 		    _PATH_HOST_KEY_FILE, "", NULL, NULL);
718 		sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
719 		    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
720 		sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
721 		    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
722 		PRIV_END;
723 
724 		if (options.hostbased_authentication == 1 &&
725 		    sensitive_data.keys[0] == NULL &&
726 		    sensitive_data.keys[1] == NULL &&
727 		    sensitive_data.keys[2] == NULL) {
728 			sensitive_data.keys[1] = key_load_public(
729 			    _PATH_HOST_DSA_KEY_FILE, NULL);
730 			sensitive_data.keys[2] = key_load_public(
731 			    _PATH_HOST_RSA_KEY_FILE, NULL);
732 			sensitive_data.external_keysign = 1;
733 		}
734 	}
735 	/*
736 	 * Get rid of any extra privileges that we may have.  We will no
737 	 * longer need them.  Also, extra privileges could make it very hard
738 	 * to read identity files and other non-world-readable files from the
739 	 * user's home directory if it happens to be on a NFS volume where
740 	 * root is mapped to nobody.
741 	 */
742 	if (original_effective_uid == 0) {
743 		PRIV_START;
744 		permanently_set_uid(pw);
745 	}
746 
747 	/*
748 	 * Now that we are back to our own permissions, create ~/.ssh
749 	 * directory if it doesn't already exist.
750 	 */
751 	snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir,
752 	    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
753 	if (stat(buf, &st) < 0)
754 		if (mkdir(buf, 0700) < 0)
755 			error("Could not create directory '%.200s'.", buf);
756 
757 	/* load options.identity_files */
758 	load_public_identity_files();
759 
760 	/* Expand ~ in known host file names. */
761 	/* XXX mem-leaks: */
762 	options.system_hostfile =
763 	    tilde_expand_filename(options.system_hostfile, original_real_uid);
764 	options.user_hostfile =
765 	    tilde_expand_filename(options.user_hostfile, original_real_uid);
766 	options.system_hostfile2 =
767 	    tilde_expand_filename(options.system_hostfile2, original_real_uid);
768 	options.user_hostfile2 =
769 	    tilde_expand_filename(options.user_hostfile2, original_real_uid);
770 
771 	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
772 
773 	/* Log into the remote system.  Never returns if the login fails. */
774 	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
775 	    pw, timeout_ms);
776 
777 	/* We no longer need the private host keys.  Clear them now. */
778 	if (sensitive_data.nkeys != 0) {
779 		for (i = 0; i < sensitive_data.nkeys; i++) {
780 			if (sensitive_data.keys[i] != NULL) {
781 				/* Destroys contents safely */
782 				debug3("clear hostkey %d", i);
783 				key_free(sensitive_data.keys[i]);
784 				sensitive_data.keys[i] = NULL;
785 			}
786 		}
787 		xfree(sensitive_data.keys);
788 	}
789 	for (i = 0; i < options.num_identity_files; i++) {
790 		if (options.identity_files[i]) {
791 			xfree(options.identity_files[i]);
792 			options.identity_files[i] = NULL;
793 		}
794 		if (options.identity_keys[i]) {
795 			key_free(options.identity_keys[i]);
796 			options.identity_keys[i] = NULL;
797 		}
798 	}
799 
800 	exit_status = compat20 ? ssh_session2() : ssh_session();
801 	packet_close();
802 
803 	if (options.control_path != NULL && muxserver_sock != -1)
804 		unlink(options.control_path);
805 
806 	/*
807 	 * Send SIGHUP to proxy command if used. We don't wait() in
808 	 * case it hangs and instead rely on init to reap the child
809 	 */
810 	if (proxy_command_pid > 1)
811 		kill(proxy_command_pid, SIGHUP);
812 
813 	return exit_status;
814 }
815 
816 /* Callback for remote forward global requests */
817 static void
818 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
819 {
820 	Forward *rfwd = (Forward *)ctxt;
821 
822 	/* XXX verbose() on failure? */
823 	debug("remote forward %s for: listen %d, connect %s:%d",
824 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
825 	    rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
826 	if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
827 		logit("Allocated port %u for remote forward to %s:%d",
828 			packet_get_int(),
829 			rfwd->connect_host, rfwd->connect_port);
830 	}
831 
832 	if (type == SSH2_MSG_REQUEST_FAILURE) {
833 		if (options.exit_on_forward_failure)
834 			fatal("Error: remote port forwarding failed for "
835 			    "listen port %d", rfwd->listen_port);
836 		else
837 			logit("Warning: remote port forwarding failed for "
838 			    "listen port %d", rfwd->listen_port);
839 	}
840 	if (++remote_forward_confirms_received == options.num_remote_forwards) {
841 		debug("All remote forwarding requests processed");
842 		if (fork_after_authentication_flag) {
843 			fork_after_authentication_flag = 0;
844 			if (daemon(1, 1) < 0)
845 				fatal("daemon() failed: %.200s",
846 				    strerror(errno));
847 		}
848 	}
849 }
850 
851 static void
852 ssh_init_forwarding(void)
853 {
854 	int success = 0;
855 	int i;
856 
857 	/* Initiate local TCP/IP port forwardings. */
858 	for (i = 0; i < options.num_local_forwards; i++) {
859 		debug("Local connections to %.200s:%d forwarded to remote "
860 		    "address %.200s:%d",
861 		    (options.local_forwards[i].listen_host == NULL) ?
862 		    (options.gateway_ports ? "*" : "LOCALHOST") :
863 		    options.local_forwards[i].listen_host,
864 		    options.local_forwards[i].listen_port,
865 		    options.local_forwards[i].connect_host,
866 		    options.local_forwards[i].connect_port);
867 		success += channel_setup_local_fwd_listener(
868 		    options.local_forwards[i].listen_host,
869 		    options.local_forwards[i].listen_port,
870 		    options.local_forwards[i].connect_host,
871 		    options.local_forwards[i].connect_port,
872 		    options.gateway_ports);
873 	}
874 	if (i > 0 && success != i && options.exit_on_forward_failure)
875 		fatal("Could not request local forwarding.");
876 	if (i > 0 && success == 0)
877 		error("Could not request local forwarding.");
878 
879 	/* Initiate remote TCP/IP port forwardings. */
880 	for (i = 0; i < options.num_remote_forwards; i++) {
881 		debug("Remote connections from %.200s:%d forwarded to "
882 		    "local address %.200s:%d",
883 		    (options.remote_forwards[i].listen_host == NULL) ?
884 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
885 		    options.remote_forwards[i].listen_port,
886 		    options.remote_forwards[i].connect_host,
887 		    options.remote_forwards[i].connect_port);
888 		if (channel_request_remote_forwarding(
889 		    options.remote_forwards[i].listen_host,
890 		    options.remote_forwards[i].listen_port,
891 		    options.remote_forwards[i].connect_host,
892 		    options.remote_forwards[i].connect_port) < 0) {
893 			if (options.exit_on_forward_failure)
894 				fatal("Could not request remote forwarding.");
895 			else
896 				logit("Warning: Could not request remote "
897 				    "forwarding.");
898 		}
899 		client_register_global_confirm(ssh_confirm_remote_forward,
900 		    &options.remote_forwards[i]);
901 	}
902 
903 	/* Initiate tunnel forwarding. */
904 	if (options.tun_open != SSH_TUNMODE_NO) {
905 		if (client_request_tun_fwd(options.tun_open,
906 		    options.tun_local, options.tun_remote) == -1) {
907 			if (options.exit_on_forward_failure)
908 				fatal("Could not request tunnel forwarding.");
909 			else
910 				error("Could not request tunnel forwarding.");
911 		}
912 	}
913 }
914 
915 static void
916 check_agent_present(void)
917 {
918 	if (options.forward_agent) {
919 		/* Clear agent forwarding if we don't have an agent. */
920 		if (!ssh_agent_present())
921 			options.forward_agent = 0;
922 	}
923 }
924 
925 static int
926 ssh_session(void)
927 {
928 	int type;
929 	int interactive = 0;
930 	int have_tty = 0;
931 	struct winsize ws;
932 	char *cp;
933 	const char *display;
934 
935 	/* Enable compression if requested. */
936 	if (options.compression) {
937 		debug("Requesting compression at level %d.",
938 		    options.compression_level);
939 
940 		if (options.compression_level < 1 ||
941 		    options.compression_level > 9)
942 			fatal("Compression level must be from 1 (fast) to "
943 			    "9 (slow, best).");
944 
945 		/* Send the request. */
946 		packet_start(SSH_CMSG_REQUEST_COMPRESSION);
947 		packet_put_int(options.compression_level);
948 		packet_send();
949 		packet_write_wait();
950 		type = packet_read();
951 		if (type == SSH_SMSG_SUCCESS)
952 			packet_start_compression(options.compression_level);
953 		else if (type == SSH_SMSG_FAILURE)
954 			logit("Warning: Remote host refused compression.");
955 		else
956 			packet_disconnect("Protocol error waiting for "
957 			    "compression response.");
958 	}
959 	/* Allocate a pseudo tty if appropriate. */
960 	if (tty_flag) {
961 		debug("Requesting pty.");
962 
963 		/* Start the packet. */
964 		packet_start(SSH_CMSG_REQUEST_PTY);
965 
966 		/* Store TERM in the packet.  There is no limit on the
967 		   length of the string. */
968 		cp = getenv("TERM");
969 		if (!cp)
970 			cp = "";
971 		packet_put_cstring(cp);
972 
973 		/* Store window size in the packet. */
974 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
975 			memset(&ws, 0, sizeof(ws));
976 		packet_put_int((u_int)ws.ws_row);
977 		packet_put_int((u_int)ws.ws_col);
978 		packet_put_int((u_int)ws.ws_xpixel);
979 		packet_put_int((u_int)ws.ws_ypixel);
980 
981 		/* Store tty modes in the packet. */
982 		tty_make_modes(fileno(stdin), NULL);
983 
984 		/* Send the packet, and wait for it to leave. */
985 		packet_send();
986 		packet_write_wait();
987 
988 		/* Read response from the server. */
989 		type = packet_read();
990 		if (type == SSH_SMSG_SUCCESS) {
991 			interactive = 1;
992 			have_tty = 1;
993 		} else if (type == SSH_SMSG_FAILURE)
994 			logit("Warning: Remote host failed or refused to "
995 			    "allocate a pseudo tty.");
996 		else
997 			packet_disconnect("Protocol error waiting for pty "
998 			    "request response.");
999 	}
1000 	/* Request X11 forwarding if enabled and DISPLAY is set. */
1001 	display = getenv("DISPLAY");
1002 	if (options.forward_x11 && display != NULL) {
1003 		char *proto, *data;
1004 		/* Get reasonable local authentication information. */
1005 		client_x11_get_proto(display, options.xauth_location,
1006 		    options.forward_x11_trusted, &proto, &data);
1007 		/* Request forwarding with authentication spoofing. */
1008 		debug("Requesting X11 forwarding with authentication "
1009 		    "spoofing.");
1010 		x11_request_forwarding_with_spoofing(0, display, proto, data);
1011 
1012 		/* Read response from the server. */
1013 		type = packet_read();
1014 		if (type == SSH_SMSG_SUCCESS) {
1015 			interactive = 1;
1016 		} else if (type == SSH_SMSG_FAILURE) {
1017 			logit("Warning: Remote host denied X11 forwarding.");
1018 		} else {
1019 			packet_disconnect("Protocol error waiting for X11 "
1020 			    "forwarding");
1021 		}
1022 	}
1023 	/* Tell the packet module whether this is an interactive session. */
1024 	packet_set_interactive(interactive);
1025 
1026 	/* Request authentication agent forwarding if appropriate. */
1027 	check_agent_present();
1028 
1029 	if (options.forward_agent) {
1030 		debug("Requesting authentication agent forwarding.");
1031 		auth_request_forwarding();
1032 
1033 		/* Read response from the server. */
1034 		type = packet_read();
1035 		packet_check_eom();
1036 		if (type != SSH_SMSG_SUCCESS)
1037 			logit("Warning: Remote host denied authentication agent forwarding.");
1038 	}
1039 
1040 	/* Initiate port forwardings. */
1041 	ssh_init_forwarding();
1042 
1043 	/* Execute a local command */
1044 	if (options.local_command != NULL &&
1045 	    options.permit_local_command)
1046 		ssh_local_cmd(options.local_command);
1047 
1048 	/*
1049 	 * If requested and we are not interested in replies to remote
1050 	 * forwarding requests, then let ssh continue in the background.
1051 	 */
1052 	if (fork_after_authentication_flag &&
1053 	    (!options.exit_on_forward_failure ||
1054 	    options.num_remote_forwards == 0)) {
1055 		fork_after_authentication_flag = 0;
1056 		if (daemon(1, 1) < 0)
1057 			fatal("daemon() failed: %.200s", strerror(errno));
1058 	}
1059 
1060 	/*
1061 	 * If a command was specified on the command line, execute the
1062 	 * command now. Otherwise request the server to start a shell.
1063 	 */
1064 	if (buffer_len(&command) > 0) {
1065 		int len = buffer_len(&command);
1066 		if (len > 900)
1067 			len = 900;
1068 		debug("Sending command: %.*s", len,
1069 		    (u_char *)buffer_ptr(&command));
1070 		packet_start(SSH_CMSG_EXEC_CMD);
1071 		packet_put_string(buffer_ptr(&command), buffer_len(&command));
1072 		packet_send();
1073 		packet_write_wait();
1074 	} else {
1075 		debug("Requesting shell.");
1076 		packet_start(SSH_CMSG_EXEC_SHELL);
1077 		packet_send();
1078 		packet_write_wait();
1079 	}
1080 
1081 	/* Enter the interactive session. */
1082 	return client_loop(have_tty, tty_flag ?
1083 	    options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1084 }
1085 
1086 /* request pty/x11/agent/tcpfwd/shell for channel */
1087 static void
1088 ssh_session2_setup(int id, void *arg)
1089 {
1090 	extern char **environ;
1091 	const char *display;
1092 	int interactive = tty_flag;
1093 
1094 	display = getenv("DISPLAY");
1095 	if (options.forward_x11 && display != NULL) {
1096 		char *proto, *data;
1097 		/* Get reasonable local authentication information. */
1098 		client_x11_get_proto(display, options.xauth_location,
1099 		    options.forward_x11_trusted, &proto, &data);
1100 		/* Request forwarding with authentication spoofing. */
1101 		debug("Requesting X11 forwarding with authentication "
1102 		    "spoofing.");
1103 		x11_request_forwarding_with_spoofing(id, display, proto, data);
1104 		interactive = 1;
1105 		/* XXX wait for reply */
1106 	}
1107 
1108 	check_agent_present();
1109 	if (options.forward_agent) {
1110 		debug("Requesting authentication agent forwarding.");
1111 		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1112 		packet_send();
1113 	}
1114 
1115 	client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1116 	    NULL, fileno(stdin), &command, environ);
1117 
1118 	packet_set_interactive(interactive);
1119 }
1120 
1121 /* open new channel for a session */
1122 static int
1123 ssh_session2_open(void)
1124 {
1125 	Channel *c;
1126 	int window, packetmax, in, out, err;
1127 
1128 	if (stdin_null_flag) {
1129 		in = open(_PATH_DEVNULL, O_RDONLY);
1130 	} else {
1131 		in = dup(STDIN_FILENO);
1132 	}
1133 	out = dup(STDOUT_FILENO);
1134 	err = dup(STDERR_FILENO);
1135 
1136 	if (in < 0 || out < 0 || err < 0)
1137 		fatal("dup() in/out/err failed");
1138 
1139 	/* enable nonblocking unless tty */
1140 	if (!isatty(in))
1141 		set_nonblock(in);
1142 	if (!isatty(out))
1143 		set_nonblock(out);
1144 	if (!isatty(err))
1145 		set_nonblock(err);
1146 
1147 	window = CHAN_SES_WINDOW_DEFAULT;
1148 	packetmax = CHAN_SES_PACKET_DEFAULT;
1149 	if (tty_flag) {
1150 		window >>= 1;
1151 		packetmax >>= 1;
1152 	}
1153 	c = channel_new(
1154 	    "session", SSH_CHANNEL_OPENING, in, out, err,
1155 	    window, packetmax, CHAN_EXTENDED_WRITE,
1156 	    "client-session", /*nonblock*/0);
1157 
1158 	debug3("ssh_session2_open: channel_new: %d", c->self);
1159 
1160 	channel_send_open(c->self);
1161 	if (!no_shell_flag)
1162 		channel_register_open_confirm(c->self,
1163 		    ssh_session2_setup, NULL);
1164 
1165 	return c->self;
1166 }
1167 
1168 static int
1169 ssh_session2(void)
1170 {
1171 	int id = -1;
1172 
1173 	/* XXX should be pre-session */
1174 	ssh_init_forwarding();
1175 
1176 	if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1177 		id = ssh_session2_open();
1178 
1179 	/* If we don't expect to open a new session, then disallow it */
1180 	if (options.control_master == SSHCTL_MASTER_NO &&
1181 	    (datafellows & SSH_NEW_OPENSSH)) {
1182 		debug("Requesting no-more-sessions@openssh.com");
1183 		packet_start(SSH2_MSG_GLOBAL_REQUEST);
1184 		packet_put_cstring("no-more-sessions@openssh.com");
1185 		packet_put_char(0);
1186 		packet_send();
1187 	}
1188 
1189 	/* Execute a local command */
1190 	if (options.local_command != NULL &&
1191 	    options.permit_local_command)
1192 		ssh_local_cmd(options.local_command);
1193 
1194 	/* Start listening for multiplex clients */
1195 	muxserver_listen();
1196 
1197 	/* If requested, let ssh continue in the background. */
1198 	if (fork_after_authentication_flag) {
1199 		fork_after_authentication_flag = 0;
1200 		if (daemon(1, 1) < 0)
1201 			fatal("daemon() failed: %.200s", strerror(errno));
1202 	}
1203 
1204 	return client_loop(tty_flag, tty_flag ?
1205 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1206 }
1207 
1208 static void
1209 load_public_identity_files(void)
1210 {
1211 	char *filename, *cp, thishost[NI_MAXHOST];
1212 	char *pwdir = NULL, *pwname = NULL;
1213 	int i = 0;
1214 	Key *public;
1215 	struct passwd *pw;
1216 #ifdef SMARTCARD
1217 	Key **keys;
1218 
1219 	if (options.smartcard_device != NULL &&
1220 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1221 	    (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1222 		int count = 0;
1223 		for (i = 0; keys[i] != NULL; i++) {
1224 			count++;
1225 			memmove(&options.identity_files[1],
1226 			    &options.identity_files[0],
1227 			    sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1228 			memmove(&options.identity_keys[1],
1229 			    &options.identity_keys[0],
1230 			    sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1231 			options.num_identity_files++;
1232 			options.identity_keys[0] = keys[i];
1233 			options.identity_files[0] = sc_get_key_label(keys[i]);
1234 		}
1235 		if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1236 			options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1237 		i = count;
1238 		xfree(keys);
1239 	}
1240 #endif /* SMARTCARD */
1241 	if ((pw = getpwuid(original_real_uid)) == NULL)
1242 		fatal("load_public_identity_files: getpwuid failed");
1243 	pwname = xstrdup(pw->pw_name);
1244 	pwdir = xstrdup(pw->pw_dir);
1245 	if (gethostname(thishost, sizeof(thishost)) == -1)
1246 		fatal("load_public_identity_files: gethostname: %s",
1247 		    strerror(errno));
1248 	for (; i < options.num_identity_files; i++) {
1249 		cp = tilde_expand_filename(options.identity_files[i],
1250 		    original_real_uid);
1251 		filename = percent_expand(cp, "d", pwdir,
1252 		    "u", pwname, "l", thishost, "h", host,
1253 		    "r", options.user, (char *)NULL);
1254 		xfree(cp);
1255 		public = key_load_public(filename, NULL);
1256 		debug("identity file %s type %d", filename,
1257 		    public ? public->type : -1);
1258 		xfree(options.identity_files[i]);
1259 		options.identity_files[i] = filename;
1260 		options.identity_keys[i] = public;
1261 	}
1262 	bzero(pwname, strlen(pwname));
1263 	xfree(pwname);
1264 	bzero(pwdir, strlen(pwdir));
1265 	xfree(pwdir);
1266 }
1267