xref: /openbsd-src/usr.bin/ssh/ssh.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * Ssh client program.  This program can be used to log into a remote machine.
6  * The software supports strong authentication, encryption, and forwarding
7  * of X11, TCP/IP, and authentication connections.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  * Copyright (c) 1999 Niels Provos.  All rights reserved.
16  *
17  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
18  * in Canada (German citizen).
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 #include "includes.h"
42 RCSID("$OpenBSD: ssh.c,v 1.138 2001/08/11 22:51:27 jakob Exp $");
43 
44 #include <openssl/evp.h>
45 #include <openssl/err.h>
46 
47 #include "ssh.h"
48 #include "ssh1.h"
49 #include "ssh2.h"
50 #include "compat.h"
51 #include "cipher.h"
52 #include "xmalloc.h"
53 #include "packet.h"
54 #include "buffer.h"
55 #include "uidswap.h"
56 #include "channels.h"
57 #include "key.h"
58 #include "authfd.h"
59 #include "authfile.h"
60 #include "pathnames.h"
61 #include "clientloop.h"
62 #include "log.h"
63 #include "readconf.h"
64 #include "sshconnect.h"
65 #include "tildexpand.h"
66 #include "dispatch.h"
67 #include "misc.h"
68 #include "kex.h"
69 #include "mac.h"
70 #include "sshtty.h"
71 
72 #ifdef SMARTCARD
73 #include <openssl/engine.h>
74 #include "scard.h"
75 #endif
76 
77 extern char *__progname;
78 
79 /* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
80    Default value is AF_UNSPEC means both IPv4 and IPv6. */
81 int IPv4or6 = AF_UNSPEC;
82 
83 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
84 int debug_flag = 0;
85 
86 /* Flag indicating whether a tty should be allocated */
87 int tty_flag = 0;
88 int no_tty_flag = 0;
89 int force_tty_flag = 0;
90 
91 /* don't exec a shell */
92 int no_shell_flag = 0;
93 
94 /*
95  * Flag indicating that nothing should be read from stdin.  This can be set
96  * on the command line.
97  */
98 int stdin_null_flag = 0;
99 
100 /*
101  * Flag indicating that ssh should fork after authentication.  This is useful
102  * so that the pasphrase can be entered manually, and then ssh goes to the
103  * background.
104  */
105 int fork_after_authentication_flag = 0;
106 
107 /*
108  * General data structure for command line options and options configurable
109  * in configuration files.  See readconf.h.
110  */
111 Options options;
112 
113 /*
114  * Name of the host we are connecting to.  This is the name given on the
115  * command line, or the HostName specified for the user-supplied name in a
116  * configuration file.
117  */
118 char *host;
119 
120 /* socket address the host resolves to */
121 struct sockaddr_storage hostaddr;
122 
123 /*
124  * Flag to indicate that we have received a window change signal which has
125  * not yet been processed.  This will cause a message indicating the new
126  * window size to be sent to the server a little later.  This is volatile
127  * because this is updated in a signal handler.
128  */
129 volatile int received_window_change_signal = 0;
130 
131 /* Private host keys. */
132 struct {
133 	Key     **keys;
134 	int	nkeys;
135 } sensitive_data;
136 
137 /* Original real UID. */
138 uid_t original_real_uid;
139 
140 /* command to be executed */
141 Buffer command;
142 
143 /* Should we execute a command or invoke a subsystem? */
144 int subsystem_flag = 0;
145 
146 /* Prints a help message to the user.  This function never returns. */
147 
148 static void
149 usage(void)
150 {
151 	fprintf(stderr, "Usage: %s [options] host [command]\n", __progname);
152 	fprintf(stderr, "Options:\n");
153 	fprintf(stderr, "  -l user     Log in using this user name.\n");
154 	fprintf(stderr, "  -n          Redirect input from " _PATH_DEVNULL ".\n");
155 	fprintf(stderr, "  -A          Enable authentication agent forwarding.\n");
156 	fprintf(stderr, "  -a          Disable authentication agent forwarding (default).\n");
157 #ifdef AFS
158 	fprintf(stderr, "  -k          Disable Kerberos ticket and AFS token forwarding.\n");
159 #endif				/* AFS */
160 	fprintf(stderr, "  -X          Enable X11 connection forwarding.\n");
161 	fprintf(stderr, "  -x          Disable X11 connection forwarding (default).\n");
162 	fprintf(stderr, "  -i file     Identity for public key authentication "
163 	    "(default: ~/.ssh/identity)\n");
164 #ifdef SMARTCARD
165 	fprintf(stderr, "  -I reader   Set smartcard reader.\n");
166 #endif
167 	fprintf(stderr, "  -t          Tty; allocate a tty even if command is given.\n");
168 	fprintf(stderr, "  -T          Do not allocate a tty.\n");
169 	fprintf(stderr, "  -v          Verbose; display verbose debugging messages.\n");
170 	fprintf(stderr, "              Multiple -v increases verbosity.\n");
171 	fprintf(stderr, "  -V          Display version number only.\n");
172 	fprintf(stderr, "  -P          Don't allocate a privileged port.\n");
173 	fprintf(stderr, "  -q          Quiet; don't display any warning messages.\n");
174 	fprintf(stderr, "  -f          Fork into background after authentication.\n");
175 	fprintf(stderr, "  -e char     Set escape character; ``none'' = disable (default: ~).\n");
176 
177 	fprintf(stderr, "  -c cipher   Select encryption algorithm\n");
178 	fprintf(stderr, "  -m macs     Specify MAC algorithms for protocol version 2.\n");
179 	fprintf(stderr, "  -p port     Connect to this port.  Server must be on the same port.\n");
180 	fprintf(stderr, "  -L listen-port:host:port   Forward local port to remote address\n");
181 	fprintf(stderr, "  -R listen-port:host:port   Forward remote port to local address\n");
182 	fprintf(stderr, "              These cause %s to listen for connections on a port, and\n", __progname);
183 	fprintf(stderr, "              forward them to the other side by connecting to host:port.\n");
184 	fprintf(stderr, "  -C          Enable compression.\n");
185 	fprintf(stderr, "  -N          Do not execute a shell or command.\n");
186 	fprintf(stderr, "  -g          Allow remote hosts to connect to forwarded ports.\n");
187 	fprintf(stderr, "  -1          Force protocol version 1.\n");
188 	fprintf(stderr, "  -2          Force protocol version 2.\n");
189 	fprintf(stderr, "  -4          Use IPv4 only.\n");
190 	fprintf(stderr, "  -6          Use IPv6 only.\n");
191 	fprintf(stderr, "  -o 'option' Process the option as if it was read from a configuration file.\n");
192 	fprintf(stderr, "  -s          Invoke command (mandatory) as SSH2 subsystem.\n");
193 	fprintf(stderr, "  -b addr     Local IP address.\n");
194 	exit(1);
195 }
196 
197 /*
198  * Connects to the given host using rsh (or prints an error message and exits
199  * if rsh is not available).  This function never returns.
200  */
201 static void
202 rsh_connect(char *host, char *user, Buffer * command)
203 {
204 	char *args[10];
205 	int i;
206 
207 	log("Using rsh.  WARNING: Connection will not be encrypted.");
208 	/* Build argument list for rsh. */
209 	i = 0;
210 	args[i++] = _PATH_RSH;
211 	/* host may have to come after user on some systems */
212 	args[i++] = host;
213 	if (user) {
214 		args[i++] = "-l";
215 		args[i++] = user;
216 	}
217 	if (buffer_len(command) > 0) {
218 		buffer_append(command, "\0", 1);
219 		args[i++] = buffer_ptr(command);
220 	}
221 	args[i++] = NULL;
222 	if (debug_flag) {
223 		for (i = 0; args[i]; i++) {
224 			if (i != 0)
225 				fprintf(stderr, " ");
226 			fprintf(stderr, "%s", args[i]);
227 		}
228 		fprintf(stderr, "\n");
229 	}
230 	execv(_PATH_RSH, args);
231 	perror(_PATH_RSH);
232 	exit(1);
233 }
234 
235 static int ssh_session(void);
236 static int ssh_session2(void);
237 static void load_public_identity_files(void);
238 
239 /*
240  * Main program for the ssh client.
241  */
242 int
243 main(int ac, char **av)
244 {
245 	int i, opt, exit_status, cerr;
246 	u_short fwd_port, fwd_host_port;
247 	char *p, *cp, buf[256];
248 	struct stat st;
249 	struct passwd *pw;
250 	int dummy;
251 	uid_t original_effective_uid;
252 
253 	/*
254 	 * Save the original real uid.  It will be needed later (uid-swapping
255 	 * may clobber the real uid).
256 	 */
257 	original_real_uid = getuid();
258 	original_effective_uid = geteuid();
259 
260 	/* If we are installed setuid root be careful to not drop core. */
261 	if (original_real_uid != original_effective_uid) {
262 		struct rlimit rlim;
263 		rlim.rlim_cur = rlim.rlim_max = 0;
264 		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
265 			fatal("setrlimit failed: %.100s", strerror(errno));
266 	}
267 	/* Get user data. */
268 	pw = getpwuid(original_real_uid);
269 	if (!pw) {
270 		log("You don't exist, go away!");
271 		exit(1);
272 	}
273 	/* Take a copy of the returned structure. */
274 	pw = pwcopy(pw);
275 
276 	/*
277 	 * Use uid-swapping to give up root privileges for the duration of
278 	 * option processing.  We will re-instantiate the rights when we are
279 	 * ready to create the privileged port, and will permanently drop
280 	 * them when the port has been created (actually, when the connection
281 	 * has been made, as we may need to create the port several times).
282 	 */
283 	temporarily_use_uid(pw);
284 
285 	/*
286 	 * Set our umask to something reasonable, as some files are created
287 	 * with the default umask.  This will make them world-readable but
288 	 * writable only by the owner, which is ok for all files for which we
289 	 * don't set the modes explicitly.
290 	 */
291 	umask(022);
292 
293 	/* Initialize option structure to indicate that no values have been set. */
294 	initialize_options(&options);
295 
296 	/* Parse command-line arguments. */
297 	host = NULL;
298 
299 again:
300 	while ((opt = getopt(ac, av,
301 	    "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:I:L:NPR:TVX")) != -1) {
302 		switch (opt) {
303 		case '1':
304 			options.protocol = SSH_PROTO_1;
305 			break;
306 		case '2':
307 			options.protocol = SSH_PROTO_2;
308 			break;
309 		case '4':
310 			IPv4or6 = AF_INET;
311 			break;
312 		case '6':
313 			IPv4or6 = AF_INET6;
314 			break;
315 		case 'n':
316 			stdin_null_flag = 1;
317 			break;
318 		case 'f':
319 			fork_after_authentication_flag = 1;
320 			stdin_null_flag = 1;
321 			break;
322 		case 'x':
323 			options.forward_x11 = 0;
324 			break;
325 		case 'X':
326 			options.forward_x11 = 1;
327 			break;
328 		case 'g':
329 			options.gateway_ports = 1;
330 			break;
331 		case 'P':
332 			options.use_privileged_port = 0;
333 			break;
334 		case 'a':
335 			options.forward_agent = 0;
336 			break;
337 		case 'A':
338 			options.forward_agent = 1;
339 			break;
340 #ifdef AFS
341 		case 'k':
342 			options.kerberos_tgt_passing = 0;
343 			options.afs_token_passing = 0;
344 			break;
345 #endif
346 		case 'i':
347 			if (stat(optarg, &st) < 0) {
348 				fprintf(stderr, "Warning: Identity file %s "
349 				    "does not exist.\n", optarg);
350 				break;
351 			}
352 			if (options.num_identity_files >=
353 			    SSH_MAX_IDENTITY_FILES)
354 				fatal("Too many identity files specified "
355 				    "(max %d)", SSH_MAX_IDENTITY_FILES);
356 			options.identity_files[options.num_identity_files++] =
357 			    xstrdup(optarg);
358 			break;
359 		case 'I':
360 #ifdef SMARTCARD
361 			options.smartcard_device = xstrdup(optarg);
362 #else
363 			fprintf(stderr, "no support for smartcards.\n");
364 #endif
365 			break;
366 		case 't':
367 			if (tty_flag)
368 				force_tty_flag = 1;
369 			tty_flag = 1;
370 			break;
371 		case 'v':
372 			if (0 == debug_flag) {
373 				debug_flag = 1;
374 				options.log_level = SYSLOG_LEVEL_DEBUG1;
375 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
376 				options.log_level++;
377 				break;
378 			} else
379 				fatal("Too high debugging level.");
380 			/* fallthrough */
381 		case 'V':
382 			fprintf(stderr,
383 			    "%s, SSH protocols %d.%d/%d.%d, OpenSSL 0x%8.8lx\n",
384 			    SSH_VERSION,
385 			    PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
386 			    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2,
387 			    SSLeay());
388 			if (opt == 'V')
389 				exit(0);
390 			break;
391 		case 'q':
392 			options.log_level = SYSLOG_LEVEL_QUIET;
393 			break;
394 		case 'e':
395 			if (optarg[0] == '^' && optarg[2] == 0 &&
396 			    (u_char) optarg[1] >= 64 &&
397 			    (u_char) optarg[1] < 128)
398 				options.escape_char = (u_char) optarg[1] & 31;
399 			else if (strlen(optarg) == 1)
400 				options.escape_char = (u_char) optarg[0];
401 			else if (strcmp(optarg, "none") == 0)
402 				options.escape_char = SSH_ESCAPECHAR_NONE;
403 			else {
404 				fprintf(stderr, "Bad escape character '%s'.\n",
405 				    optarg);
406 				exit(1);
407 			}
408 			break;
409 		case 'c':
410 			if (ciphers_valid(optarg)) {
411 				/* SSH2 only */
412 				options.ciphers = xstrdup(optarg);
413 				options.cipher = SSH_CIPHER_ILLEGAL;
414 			} else {
415 				/* SSH1 only */
416 				options.cipher = cipher_number(optarg);
417 				if (options.cipher == -1) {
418 					fprintf(stderr,
419 					    "Unknown cipher type '%s'\n",
420 					    optarg);
421 					exit(1);
422 				}
423 				if (options.cipher == SSH_CIPHER_3DES)
424 					options.ciphers = "3des-cbc";
425 				else if (options.cipher == SSH_CIPHER_BLOWFISH)
426 					options.ciphers = "blowfish-cbc";
427 				else
428 					options.ciphers = (char *)-1;
429 			}
430 			break;
431 		case 'm':
432 			if (mac_valid(optarg))
433 				options.macs = xstrdup(optarg);
434 			else {
435 				fprintf(stderr, "Unknown mac type '%s'\n",
436 				    optarg);
437 				exit(1);
438 			}
439 			break;
440 		case 'p':
441 			options.port = a2port(optarg);
442 			if (options.port == 0) {
443 				fprintf(stderr, "Bad port '%s'\n", optarg);
444 				exit(1);
445 			}
446 			break;
447 		case 'l':
448 			options.user = optarg;
449 			break;
450 		case 'R':
451 			if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
452 			    &fwd_host_port) != 3 &&
453 			    sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
454 			    &fwd_host_port) != 3) {
455 				fprintf(stderr,
456 				    "Bad forwarding specification '%s'.\n",
457 				    optarg);
458 				usage();
459 				/* NOTREACHED */
460 			}
461 			add_remote_forward(&options, fwd_port, buf,
462 			     fwd_host_port);
463 			break;
464 		case 'L':
465 			if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
466 			    &fwd_host_port) != 3 &&
467 			    sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
468 			    &fwd_host_port) != 3) {
469 				fprintf(stderr,
470 				    "Bad forwarding specification '%s'.\n",
471 				    optarg);
472 				usage();
473 				/* NOTREACHED */
474 			}
475 			add_local_forward(&options, fwd_port, buf,
476 			    fwd_host_port);
477 			break;
478 
479 		case 'D':
480 			fwd_port = a2port(optarg);
481 			if (fwd_port == 0) {
482 				fprintf(stderr, "Bad dynamic port '%s'\n",
483 				    optarg);
484 				exit(1);
485 			}
486 			add_local_forward(&options, fwd_port, "socks4", 0);
487 			break;
488 
489 		case 'C':
490 			options.compression = 1;
491 			break;
492 		case 'N':
493 			no_shell_flag = 1;
494 			no_tty_flag = 1;
495 			break;
496 		case 'T':
497 			no_tty_flag = 1;
498 			break;
499 		case 'o':
500 			dummy = 1;
501 			if (process_config_line(&options, host ? host : "",
502 			    optarg, "command-line", 0, &dummy) != 0)
503 				exit(1);
504 			break;
505 		case 's':
506 			subsystem_flag = 1;
507 			break;
508 		case 'b':
509 			options.bind_address = optarg;
510 			break;
511 		default:
512 			usage();
513 		}
514 	}
515 
516 	ac -= optind;
517 	av += optind;
518 
519 	if (ac > 0 && !host && **av != '-') {
520 		if (strchr(*av, '@')) {
521 			p = xstrdup(*av);
522 			cp = strchr(p, '@');
523 			if (cp == NULL || cp == p)
524 				usage();
525 			options.user = p;
526 			*cp = '\0';
527 			host = ++cp;
528 		} else
529 			host = *av;
530 		ac--, av++;
531 		if (ac > 0) {
532 			optind = 0;
533 			optreset = 1;
534 			goto again;
535 		}
536 	}
537 
538 	/* Check that we got a host name. */
539 	if (!host)
540 		usage();
541 
542 	SSLeay_add_all_algorithms();
543 	ERR_load_crypto_strings();
544 
545 	/* Initialize the command to execute on remote host. */
546 	buffer_init(&command);
547 
548 	/*
549 	 * Save the command to execute on the remote host in a buffer. There
550 	 * is no limit on the length of the command, except by the maximum
551 	 * packet size.  Also sets the tty flag if there is no command.
552 	 */
553 	if (!ac) {
554 		/* No command specified - execute shell on a tty. */
555 		tty_flag = 1;
556 		if (subsystem_flag) {
557 			fprintf(stderr,
558 			    "You must specify a subsystem to invoke.\n");
559 			usage();
560 		}
561 	} else {
562 		/* A command has been specified.  Store it into the buffer. */
563 		for (i = 0; i < ac; i++) {
564 			if (i)
565 				buffer_append(&command, " ", 1);
566 			buffer_append(&command, av[i], strlen(av[i]));
567 		}
568 	}
569 
570 	/* Cannot fork to background if no command. */
571 	if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
572 		fatal("Cannot fork into background without a command 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)) && !force_tty_flag) {
583 		if (tty_flag)
584 			log("Pseudo-terminal will not be allocated because stdin is not a terminal.");
585 		tty_flag = 0;
586 	}
587 
588 	/*
589 	 * Initialize "log" output.  Since we are the client all output
590 	 * actually goes to stderr.
591 	 */
592 	log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
593 	    SYSLOG_FACILITY_USER, 1);
594 
595 	/* Read per-user configuration file. */
596 	snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, _PATH_SSH_USER_CONFFILE);
597 	read_config_file(buf, host, &options);
598 
599 	/* Read systemwide configuration file. */
600 	read_config_file(_PATH_HOST_CONFIG_FILE, host, &options);
601 
602 	/* Fill configuration defaults. */
603 	fill_default_options(&options);
604 
605 	/* reinit */
606 	log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
607 
608 	if (options.user == NULL)
609 		options.user = xstrdup(pw->pw_name);
610 
611 	if (options.hostname != NULL)
612 		host = options.hostname;
613 
614 	/* Disable rhosts authentication if not running as root. */
615 	if (original_effective_uid != 0 || !options.use_privileged_port) {
616 		debug("Rhosts Authentication disabled, "
617 		    "originating port will not be trusted.");
618 		options.rhosts_authentication = 0;
619 	}
620 	/*
621 	 * If using rsh has been selected, exec it now (without trying
622 	 * anything else).  Note that we must release privileges first.
623 	 */
624 	if (options.use_rsh) {
625 		/*
626 		 * Restore our superuser privileges.  This must be done
627 		 * before permanently setting the uid.
628 		 */
629 		restore_uid();
630 
631 		/* Switch to the original uid permanently. */
632 		permanently_set_uid(pw);
633 
634 		/* Execute rsh. */
635 		rsh_connect(host, options.user, &command);
636 		fatal("rsh_connect returned");
637 	}
638 	/* Restore our superuser privileges. */
639 	restore_uid();
640 
641 	/* Open a connection to the remote host. */
642 
643 	cerr = ssh_connect(host, &hostaddr, options.port,
644 	    options.connection_attempts,
645 	    original_effective_uid != 0 || !options.use_privileged_port,
646 	    pw, options.proxy_command);
647 
648 	/*
649 	 * If we successfully made the connection, load the host private key
650 	 * in case we will need it later for combined rsa-rhosts
651 	 * authentication. This must be done before releasing extra
652 	 * privileges, because the file is only readable by root.
653 	 */
654 	sensitive_data.nkeys = 0;
655 	sensitive_data.keys = NULL;
656 	if (!cerr && (options.rhosts_rsa_authentication ||
657 	    options.hostbased_authentication)) {
658 		sensitive_data.nkeys = 3;
659 		sensitive_data.keys = xmalloc(sensitive_data.nkeys*sizeof(Key));
660 		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
661 		    _PATH_HOST_KEY_FILE, "", NULL);
662 		sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
663 		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
664 		sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
665 		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
666 	}
667 	/*
668 	 * Get rid of any extra privileges that we may have.  We will no
669 	 * longer need them.  Also, extra privileges could make it very hard
670 	 * to read identity files and other non-world-readable files from the
671 	 * user's home directory if it happens to be on a NFS volume where
672 	 * root is mapped to nobody.
673 	 */
674 
675 	/*
676 	 * Note that some legacy systems need to postpone the following call
677 	 * to permanently_set_uid() until the private hostkey is destroyed
678 	 * with RSA_free().  Otherwise the calling user could ptrace() the
679 	 * process, read the private hostkey and impersonate the host.
680 	 * OpenBSD does not allow ptracing of setuid processes.
681 	 */
682 	permanently_set_uid(pw);
683 
684 	/*
685 	 * Now that we are back to our own permissions, create ~/.ssh
686 	 * directory if it doesn\'t already exist.
687 	 */
688 	snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
689 	if (stat(buf, &st) < 0)
690 		if (mkdir(buf, 0700) < 0)
691 			error("Could not create directory '%.200s'.", buf);
692 
693 	/* Check if the connection failed, and try "rsh" if appropriate. */
694 	if (cerr) {
695 		if (!options.fallback_to_rsh)
696 			exit(1);
697 		if (options.port != 0)
698 			log("Secure connection to %.100s on port %hu refused; "
699 			    "reverting to insecure method",
700 			    host, options.port);
701 		else
702 			log("Secure connection to %.100s refused; "
703 			    "reverting to insecure method.", host);
704 
705 		rsh_connect(host, options.user, &command);
706 		fatal("rsh_connect returned");
707 	}
708 	/* load options.identity_files */
709 	load_public_identity_files();
710 
711 	/* Expand ~ in known host file names. */
712 	/* XXX mem-leaks: */
713 	options.system_hostfile =
714 	    tilde_expand_filename(options.system_hostfile, original_real_uid);
715 	options.user_hostfile =
716 	    tilde_expand_filename(options.user_hostfile, original_real_uid);
717 	options.system_hostfile2 =
718 	    tilde_expand_filename(options.system_hostfile2, original_real_uid);
719 	options.user_hostfile2 =
720 	    tilde_expand_filename(options.user_hostfile2, original_real_uid);
721 
722 	/* Log into the remote system.  This never returns if the login fails. */
723 	ssh_login(sensitive_data.keys, sensitive_data.nkeys,
724 	    host, (struct sockaddr *)&hostaddr, pw);
725 
726 	/* We no longer need the private host keys.  Clear them now. */
727 	if (sensitive_data.nkeys != 0) {
728 		for (i = 0; i < sensitive_data.nkeys; i++) {
729 			if (sensitive_data.keys[i] != NULL) {
730 				/* Destroys contents safely */
731 				debug3("clear hostkey %d", i);
732 				key_free(sensitive_data.keys[i]);
733 				sensitive_data.keys[i] = NULL;
734 			}
735 		}
736 		xfree(sensitive_data.keys);
737 	}
738 	for (i = 0; i < options.num_identity_files; i++) {
739 		if (options.identity_files[i]) {
740 			xfree(options.identity_files[i]);
741 			options.identity_files[i] = NULL;
742 		}
743 		if (options.identity_keys[i]) {
744 			key_free(options.identity_keys[i]);
745 			options.identity_keys[i] = NULL;
746 		}
747 	}
748 
749 	exit_status = compat20 ? ssh_session2() : ssh_session();
750 	packet_close();
751 	return exit_status;
752 }
753 
754 static void
755 x11_get_proto(char *proto, int proto_len, char *data, int data_len)
756 {
757 	char line[512];
758 	FILE *f;
759 	int got_data = 0, i;
760 
761 	if (options.xauth_location) {
762 		/* Try to get Xauthority information for the display. */
763 		snprintf(line, sizeof line, "%.100s list %.200s 2>" _PATH_DEVNULL,
764 		    options.xauth_location, getenv("DISPLAY"));
765 		f = popen(line, "r");
766 		if (f && fgets(line, sizeof(line), f) &&
767 		    sscanf(line, "%*s %s %s", proto, data) == 2)
768 			got_data = 1;
769 		if (f)
770 			pclose(f);
771 	}
772 	/*
773 	 * If we didn't get authentication data, just make up some
774 	 * data.  The forwarding code will check the validity of the
775 	 * response anyway, and substitute this data.  The X11
776 	 * server, however, will ignore this fake data and use
777 	 * whatever authentication mechanisms it was using otherwise
778 	 * for the local connection.
779 	 */
780 	if (!got_data) {
781 		u_int32_t rand = 0;
782 
783 		strlcpy(proto, "MIT-MAGIC-COOKIE-1", proto_len);
784 		for (i = 0; i < 16; i++) {
785 			if (i % 4 == 0)
786 				rand = arc4random();
787 			snprintf(data + 2 * i, data_len - 2 * i, "%02x", rand & 0xff);
788 			rand >>= 8;
789 		}
790 	}
791 }
792 
793 static void
794 ssh_init_forwarding(void)
795 {
796 	int success = 0;
797 	int i;
798 
799 	/* Initiate local TCP/IP port forwardings. */
800 	for (i = 0; i < options.num_local_forwards; i++) {
801 		debug("Connections to local port %d forwarded to remote address %.200s:%d",
802 		    options.local_forwards[i].port,
803 		    options.local_forwards[i].host,
804 		    options.local_forwards[i].host_port);
805 		success += channel_request_local_forwarding(
806 		    options.local_forwards[i].port,
807 		    options.local_forwards[i].host,
808 		    options.local_forwards[i].host_port,
809 		    options.gateway_ports);
810 	}
811 	if (i > 0 && success == 0)
812 		error("Could not request local forwarding.");
813 
814 	/* Initiate remote TCP/IP port forwardings. */
815 	for (i = 0; i < options.num_remote_forwards; i++) {
816 		debug("Connections to remote port %d forwarded to local address %.200s:%d",
817 		    options.remote_forwards[i].port,
818 		    options.remote_forwards[i].host,
819 		    options.remote_forwards[i].host_port);
820 		channel_request_remote_forwarding(
821 		    options.remote_forwards[i].port,
822 		    options.remote_forwards[i].host,
823 		    options.remote_forwards[i].host_port);
824 	}
825 }
826 
827 static void
828 check_agent_present(void)
829 {
830 	if (options.forward_agent) {
831 		/* Clear agent forwarding if we don\'t have an agent. */
832 		int authfd = ssh_get_authentication_socket();
833 		if (authfd < 0)
834 			options.forward_agent = 0;
835 		else
836 			ssh_close_authentication_socket(authfd);
837 	}
838 }
839 
840 static int
841 ssh_session(void)
842 {
843 	int type;
844 	int plen;
845 	int interactive = 0;
846 	int have_tty = 0;
847 	struct winsize ws;
848 	char *cp;
849 
850 	/* Enable compression if requested. */
851 	if (options.compression) {
852 		debug("Requesting compression at level %d.", options.compression_level);
853 
854 		if (options.compression_level < 1 || options.compression_level > 9)
855 			fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
856 
857 		/* Send the request. */
858 		packet_start(SSH_CMSG_REQUEST_COMPRESSION);
859 		packet_put_int(options.compression_level);
860 		packet_send();
861 		packet_write_wait();
862 		type = packet_read(&plen);
863 		if (type == SSH_SMSG_SUCCESS)
864 			packet_start_compression(options.compression_level);
865 		else if (type == SSH_SMSG_FAILURE)
866 			log("Warning: Remote host refused compression.");
867 		else
868 			packet_disconnect("Protocol error waiting for compression response.");
869 	}
870 	/* Allocate a pseudo tty if appropriate. */
871 	if (tty_flag) {
872 		debug("Requesting pty.");
873 
874 		/* Start the packet. */
875 		packet_start(SSH_CMSG_REQUEST_PTY);
876 
877 		/* Store TERM in the packet.  There is no limit on the
878 		   length of the string. */
879 		cp = getenv("TERM");
880 		if (!cp)
881 			cp = "";
882 		packet_put_cstring(cp);
883 
884 		/* Store window size in the packet. */
885 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
886 			memset(&ws, 0, sizeof(ws));
887 		packet_put_int(ws.ws_row);
888 		packet_put_int(ws.ws_col);
889 		packet_put_int(ws.ws_xpixel);
890 		packet_put_int(ws.ws_ypixel);
891 
892 		/* Store tty modes in the packet. */
893 		tty_make_modes(fileno(stdin), NULL);
894 
895 		/* Send the packet, and wait for it to leave. */
896 		packet_send();
897 		packet_write_wait();
898 
899 		/* Read response from the server. */
900 		type = packet_read(&plen);
901 		if (type == SSH_SMSG_SUCCESS) {
902 			interactive = 1;
903 			have_tty = 1;
904 		} else if (type == SSH_SMSG_FAILURE)
905 			log("Warning: Remote host failed or refused to allocate a pseudo tty.");
906 		else
907 			packet_disconnect("Protocol error waiting for pty request response.");
908 	}
909 	/* Request X11 forwarding if enabled and DISPLAY is set. */
910 	if (options.forward_x11 && getenv("DISPLAY") != NULL) {
911 		char proto[512], data[512];
912 		/* Get reasonable local authentication information. */
913 		x11_get_proto(proto, sizeof proto, data, sizeof data);
914 		/* Request forwarding with authentication spoofing. */
915 		debug("Requesting X11 forwarding with authentication spoofing.");
916 		x11_request_forwarding_with_spoofing(0, proto, data);
917 
918 		/* Read response from the server. */
919 		type = packet_read(&plen);
920 		if (type == SSH_SMSG_SUCCESS) {
921 			interactive = 1;
922 		} else if (type == SSH_SMSG_FAILURE) {
923 			log("Warning: Remote host denied X11 forwarding.");
924 		} else {
925 			packet_disconnect("Protocol error waiting for X11 forwarding");
926 		}
927 	}
928 	/* Tell the packet module whether this is an interactive session. */
929 	packet_set_interactive(interactive);
930 
931 	/* Request authentication agent forwarding if appropriate. */
932 	check_agent_present();
933 
934 	if (options.forward_agent) {
935 		debug("Requesting authentication agent forwarding.");
936 		auth_request_forwarding();
937 
938 		/* Read response from the server. */
939 		type = packet_read(&plen);
940 		packet_integrity_check(plen, 0, type);
941 		if (type != SSH_SMSG_SUCCESS)
942 			log("Warning: Remote host denied authentication agent forwarding.");
943 	}
944 
945 	/* Initiate port forwardings. */
946 	ssh_init_forwarding();
947 
948 	/* If requested, let ssh continue in the background. */
949 	if (fork_after_authentication_flag)
950 		if (daemon(1, 1) < 0)
951 			fatal("daemon() failed: %.200s", strerror(errno));
952 
953 	/*
954 	 * If a command was specified on the command line, execute the
955 	 * command now. Otherwise request the server to start a shell.
956 	 */
957 	if (buffer_len(&command) > 0) {
958 		int len = buffer_len(&command);
959 		if (len > 900)
960 			len = 900;
961 		debug("Sending command: %.*s", len, buffer_ptr(&command));
962 		packet_start(SSH_CMSG_EXEC_CMD);
963 		packet_put_string(buffer_ptr(&command), buffer_len(&command));
964 		packet_send();
965 		packet_write_wait();
966 	} else {
967 		debug("Requesting shell.");
968 		packet_start(SSH_CMSG_EXEC_SHELL);
969 		packet_send();
970 		packet_write_wait();
971 	}
972 
973 	/* Enter the interactive session. */
974 	return client_loop(have_tty, tty_flag ?
975 	    options.escape_char : SSH_ESCAPECHAR_NONE, 0);
976 }
977 
978 static void
979 client_subsystem_reply(int type, int plen, void *ctxt)
980 {
981 	int id, len;
982 
983 	id = packet_get_int();
984 	len = buffer_len(&command);
985 	if (len > 900)
986 		len = 900;
987 	packet_done();
988 	if (type == SSH2_MSG_CHANNEL_FAILURE)
989 		fatal("Request for subsystem '%.*s' failed on channel %d",
990 		    len, buffer_ptr(&command), id);
991 }
992 
993 static void
994 ssh_session2_callback(int id, void *arg)
995 {
996 	int len;
997 	int interactive = 0;
998 	struct termios tio;
999 
1000 	debug("client_init id %d arg %ld", id, (long)arg);
1001 
1002 	if (tty_flag) {
1003 		struct winsize ws;
1004 		char *cp;
1005 		cp = getenv("TERM");
1006 		if (!cp)
1007 			cp = "";
1008 		/* Store window size in the packet. */
1009 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1010 			memset(&ws, 0, sizeof(ws));
1011 
1012 		channel_request_start(id, "pty-req", 0);
1013 		packet_put_cstring(cp);
1014 		packet_put_int(ws.ws_col);
1015 		packet_put_int(ws.ws_row);
1016 		packet_put_int(ws.ws_xpixel);
1017 		packet_put_int(ws.ws_ypixel);
1018 		tio = get_saved_tio();
1019 		tty_make_modes(/*ignored*/ 0, &tio);
1020 		packet_send();
1021 		interactive = 1;
1022 		/* XXX wait for reply */
1023 	}
1024 	if (options.forward_x11 &&
1025 	    getenv("DISPLAY") != NULL) {
1026 		char proto[512], data[512];
1027 		/* Get reasonable local authentication information. */
1028 		x11_get_proto(proto, sizeof proto, data, sizeof data);
1029 		/* Request forwarding with authentication spoofing. */
1030 		debug("Requesting X11 forwarding with authentication spoofing.");
1031 		x11_request_forwarding_with_spoofing(id, proto, data);
1032 		interactive = 1;
1033 		/* XXX wait for reply */
1034 	}
1035 
1036 	check_agent_present();
1037 	if (options.forward_agent) {
1038 		debug("Requesting authentication agent forwarding.");
1039 		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1040 		packet_send();
1041 	}
1042 
1043 	len = buffer_len(&command);
1044 	if (len > 0) {
1045 		if (len > 900)
1046 			len = 900;
1047 		if (subsystem_flag) {
1048 			debug("Sending subsystem: %.*s", len, buffer_ptr(&command));
1049 			channel_request_start(id, "subsystem", /*want reply*/ 1);
1050 			/* register callback for reply */
1051 			/* XXX we asume that client_loop has already been called */
1052 			dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &client_subsystem_reply);
1053 			dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &client_subsystem_reply);
1054 		} else {
1055 			debug("Sending command: %.*s", len, buffer_ptr(&command));
1056 			channel_request_start(id, "exec", 0);
1057 		}
1058 		packet_put_string(buffer_ptr(&command), buffer_len(&command));
1059 		packet_send();
1060 	} else {
1061 		channel_request(id, "shell", 0);
1062 	}
1063 	/* channel_callback(id, SSH2_MSG_OPEN_CONFIGMATION, client_init, 0); */
1064 
1065 	/* register different callback, etc. XXX */
1066 	packet_set_interactive(interactive);
1067 }
1068 
1069 static int
1070 ssh_session2_command(void)
1071 {
1072 	Channel *c;
1073 	int window, packetmax, in, out, err;
1074 
1075 	if (stdin_null_flag) {
1076 		in = open(_PATH_DEVNULL, O_RDONLY);
1077 	} else {
1078 		in = dup(STDIN_FILENO);
1079 	}
1080 	out = dup(STDOUT_FILENO);
1081 	err = dup(STDERR_FILENO);
1082 
1083 	if (in < 0 || out < 0 || err < 0)
1084 		fatal("dup() in/out/err failed");
1085 
1086 	/* enable nonblocking unless tty */
1087 	if (!isatty(in))
1088 		set_nonblock(in);
1089 	if (!isatty(out))
1090 		set_nonblock(out);
1091 	if (!isatty(err))
1092 		set_nonblock(err);
1093 
1094 	window = CHAN_SES_WINDOW_DEFAULT;
1095 	packetmax = CHAN_SES_PACKET_DEFAULT;
1096 	if (!tty_flag) {
1097 		window *= 2;
1098 		packetmax *=2;
1099 	}
1100 	c = channel_new(
1101 	    "session", SSH_CHANNEL_OPENING, in, out, err,
1102 	    window, packetmax, CHAN_EXTENDED_WRITE,
1103 	    xstrdup("client-session"), /*nonblock*/0);
1104 	if (c == NULL)
1105 		fatal("ssh_session2_command: channel_new failed");
1106 
1107 	debug3("ssh_session2_command: channel_new: %d", c->self);
1108 
1109 	channel_send_open(c->self);
1110 	channel_register_callback(c->self, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION,
1111 	     ssh_session2_callback, (void *)0);
1112 
1113 	return c->self;
1114 }
1115 
1116 static int
1117 ssh_session2(void)
1118 {
1119 	int id;
1120 
1121 	/* XXX should be pre-session */
1122 	ssh_init_forwarding();
1123 
1124 	id = no_shell_flag ? -1 : ssh_session2_command();
1125 
1126 	/* If requested, let ssh continue in the background. */
1127 	if (fork_after_authentication_flag)
1128 		if (daemon(1, 1) < 0)
1129 			fatal("daemon() failed: %.200s", strerror(errno));
1130 
1131 	return client_loop(tty_flag, tty_flag ?
1132 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1133 }
1134 
1135 static void
1136 load_public_identity_files(void)
1137 {
1138 	char *filename;
1139 	Key *public;
1140 	int i = 0;
1141 
1142 #ifdef SMARTCARD
1143 	if (options.smartcard_device != NULL &&
1144 	    options.num_identity_files + 1 < SSH_MAX_IDENTITY_FILES &&
1145 	    (public = sc_get_key(options.smartcard_device)) != NULL ) {
1146 		Key *new;
1147 
1148 		if (options.num_identity_files + 2 > SSH_MAX_IDENTITY_FILES)
1149 			options.num_identity_files = SSH_MAX_IDENTITY_FILES - 2;
1150 		memmove(&options.identity_files[2], &options.identity_files[0],
1151 		    sizeof(char *) * options.num_identity_files);
1152 		options.num_identity_files += 2;
1153 		i = 2;
1154 
1155 		/* XXX ssh1 vs ssh2 */
1156 		new = key_new(KEY_RSA);
1157 		new->flags = KEY_FLAG_EXT;
1158 		BN_copy(new->rsa->n, public->rsa->n);
1159 		BN_copy(new->rsa->e, public->rsa->e);
1160 		RSA_set_method(new->rsa, sc_get_engine());
1161 		options.identity_keys[0] = new;
1162 		options.identity_files[0] = xstrdup("smartcard rsa key");;
1163 
1164 		new = key_new(KEY_RSA1);
1165 		new->flags = KEY_FLAG_EXT;
1166 		BN_copy(new->rsa->n, public->rsa->n);
1167 		BN_copy(new->rsa->e, public->rsa->e);
1168 		RSA_set_method(new->rsa, sc_get_engine());
1169 		options.identity_keys[1] = new;
1170 		options.identity_files[1] = xstrdup("smartcard rsa1 key");
1171 
1172 		key_free(public);
1173 	}
1174 #endif /* SMARTCARD */
1175 	for (; i < options.num_identity_files; i++) {
1176 		filename = tilde_expand_filename(options.identity_files[i],
1177 		    original_real_uid);
1178 		public = key_load_public(filename, NULL);
1179 		debug("identity file %s type %d", filename,
1180 		    public ? public->type : -1);
1181 		xfree(options.identity_files[i]);
1182 		options.identity_files[i] = filename;
1183 		options.identity_keys[i] = public;
1184 	}
1185 }
1186