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