xref: /freebsd/crypto/openssh/ssh.c (revision a79b71281cd63ad7a6cc43a6d5673a2510b51630)
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  * Created: Sat Mar 18 16:36:11 1995 ylo
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  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu> in Canada.
11  *
12  * $FreeBSD$
13  */
14 
15 #include "includes.h"
16 RCSID("$Id: ssh.c,v 1.54 2000/05/30 17:32:06 markus Exp $");
17 
18 #include <openssl/evp.h>
19 #include <openssl/dsa.h>
20 #include <openssl/rsa.h>
21 
22 #include "xmalloc.h"
23 #include "ssh.h"
24 #include "packet.h"
25 #include "buffer.h"
26 #include "authfd.h"
27 #include "readconf.h"
28 #include "uidswap.h"
29 
30 #include "ssh2.h"
31 #include "compat.h"
32 #include "channels.h"
33 #include "key.h"
34 #include "authfile.h"
35 
36 extern char *__progname;
37 
38 /* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
39    Default value is AF_UNSPEC means both IPv4 and IPv6. */
40 int IPv4or6 = AF_UNSPEC;
41 
42 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
43 int debug_flag = 0;
44 
45 /* Flag indicating whether a tty should be allocated */
46 int tty_flag = 0;
47 
48 /* don't exec a shell */
49 int no_shell_flag = 0;
50 int no_tty_flag = 0;
51 
52 /*
53  * Flag indicating that nothing should be read from stdin.  This can be set
54  * on the command line.
55  */
56 int stdin_null_flag = 0;
57 
58 /*
59  * Flag indicating that ssh should fork after authentication.  This is useful
60  * so that the pasphrase can be entered manually, and then ssh goes to the
61  * background.
62  */
63 int fork_after_authentication_flag = 0;
64 
65 /*
66  * General data structure for command line options and options configurable
67  * in configuration files.  See readconf.h.
68  */
69 Options options;
70 
71 /*
72  * Name of the host we are connecting to.  This is the name given on the
73  * command line, or the HostName specified for the user-supplied name in a
74  * configuration file.
75  */
76 char *host;
77 
78 /* socket address the host resolves to */
79 struct sockaddr_storage hostaddr;
80 
81 /*
82  * Flag to indicate that we have received a window change signal which has
83  * not yet been processed.  This will cause a message indicating the new
84  * window size to be sent to the server a little later.  This is volatile
85  * because this is updated in a signal handler.
86  */
87 volatile int received_window_change_signal = 0;
88 
89 /* Value of argv[0] (set in the main program). */
90 char *av0;
91 
92 /* Flag indicating whether we have a valid host private key loaded. */
93 int host_private_key_loaded = 0;
94 
95 /* Host private key. */
96 RSA *host_private_key = NULL;
97 
98 /* Original real UID. */
99 uid_t original_real_uid;
100 
101 /* command to be executed */
102 Buffer command;
103 
104 /* Prints a help message to the user.  This function never returns. */
105 
106 void
107 usage()
108 {
109 	fprintf(stderr, "Usage: %s [options] host [command]\n", av0);
110 	fprintf(stderr, "Options:\n");
111 	fprintf(stderr, "  -l user     Log in using this user name.\n");
112 	fprintf(stderr, "  -n          Redirect input from /dev/null.\n");
113 	fprintf(stderr, "  -A          Enable authentication agent forwarding.\n");
114 	fprintf(stderr, "  -a          Disable authentication agent forwarding.\n");
115 #ifdef AFS
116 	fprintf(stderr, "  -k          Disable Kerberos ticket and AFS token forwarding.\n");
117 #endif				/* AFS */
118         fprintf(stderr, "  -X          Enable X11 connection forwarding.\n");
119 	fprintf(stderr, "  -x          Disable X11 connection forwarding.\n");
120 	fprintf(stderr, "  -X          Enable X11 connection forwarding.\n");
121 	fprintf(stderr, "  -i file     Identity for RSA authentication (default: ~/.ssh/identity).\n");
122 	fprintf(stderr, "  -t          Tty; allocate a tty even if command is given.\n");
123 	fprintf(stderr, "  -T          Do not allocate a tty.\n");
124 	fprintf(stderr, "  -v          Verbose; display verbose debugging messages.\n");
125 	fprintf(stderr, "  -V          Display version number only.\n");
126 	fprintf(stderr, "  -P          Don't allocate a privileged port.\n");
127 	fprintf(stderr, "  -q          Quiet; don't display any warning messages.\n");
128 	fprintf(stderr, "  -f          Fork into background after authentication.\n");
129 	fprintf(stderr, "  -e char     Set escape character; ``none'' = disable (default: ~).\n");
130 
131 	fprintf(stderr, "  -c cipher   Select encryption algorithm: "
132 			"``3des'', "
133 			"``blowfish''\n");
134 	fprintf(stderr, "  -p port     Connect to this port.  Server must be on the same port.\n");
135 	fprintf(stderr, "  -L listen-port:host:port   Forward local port to remote address\n");
136 	fprintf(stderr, "  -R listen-port:host:port   Forward remote port to local address\n");
137 	fprintf(stderr, "              These cause %s to listen for connections on a port, and\n", av0);
138 	fprintf(stderr, "              forward them to the other side by connecting to host:port.\n");
139 	fprintf(stderr, "  -C          Enable compression.\n");
140 	fprintf(stderr, "  -N          Do not execute a shell or command.\n");
141 	fprintf(stderr, "  -g          Allow remote hosts to connect to forwarded ports.\n");
142 	fprintf(stderr, "  -4          Use IPv4 only.\n");
143 	fprintf(stderr, "  -6          Use IPv6 only.\n");
144 	fprintf(stderr, "  -2          Force protocol version 2.\n");
145 	fprintf(stderr, "  -o 'option' Process the option as if it was read from a configuration file.\n");
146 	exit(1);
147 }
148 
149 /*
150  * Connects to the given host using rsh (or prints an error message and exits
151  * if rsh is not available).  This function never returns.
152  */
153 void
154 rsh_connect(char *host, char *user, Buffer * command)
155 {
156 	char *args[10];
157 	int i;
158 
159 	log("Using rsh.  WARNING: Connection will not be encrypted.");
160 	/* Build argument list for rsh. */
161 	i = 0;
162 #ifndef	_PATH_RSH
163 #define	_PATH_RSH	"/usr/bin/rsh"
164 #endif
165 	args[i++] = _PATH_RSH;
166 	/* host may have to come after user on some systems */
167 	args[i++] = host;
168 	if (user) {
169 		args[i++] = "-l";
170 		args[i++] = user;
171 	}
172 	if (buffer_len(command) > 0) {
173 		buffer_append(command, "\0", 1);
174 		args[i++] = buffer_ptr(command);
175 	}
176 	args[i++] = NULL;
177 	if (debug_flag) {
178 		for (i = 0; args[i]; i++) {
179 			if (i != 0)
180 				fprintf(stderr, " ");
181 			fprintf(stderr, "%s", args[i]);
182 		}
183 		fprintf(stderr, "\n");
184 	}
185 	execv(_PATH_RSH, args);
186 	perror(_PATH_RSH);
187 	exit(1);
188 }
189 
190 int ssh_session(void);
191 int ssh_session2(void);
192 
193 /*
194  * Main program for the ssh client.
195  */
196 int
197 main(int ac, char **av)
198 {
199 	int i, opt, optind, exit_status, ok;
200 	u_short fwd_port, fwd_host_port;
201 	char *optarg, *cp, buf[256];
202 	struct stat st;
203 	struct passwd *pw, pwcopy;
204 	int dummy;
205 	uid_t original_effective_uid;
206 
207 	/*
208 	 * Save the original real uid.  It will be needed later (uid-swapping
209 	 * may clobber the real uid).
210 	 */
211 	original_real_uid = getuid();
212 	original_effective_uid = geteuid();
213 
214 	/* If we are installed setuid root be careful to not drop core. */
215 	if (original_real_uid != original_effective_uid) {
216 		struct rlimit rlim;
217 		rlim.rlim_cur = rlim.rlim_max = 0;
218 		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
219 			fatal("setrlimit failed: %.100s", strerror(errno));
220 	}
221 	/*
222 	 * Use uid-swapping to give up root privileges for the duration of
223 	 * option processing.  We will re-instantiate the rights when we are
224 	 * ready to create the privileged port, and will permanently drop
225 	 * them when the port has been created (actually, when the connection
226 	 * has been made, as we may need to create the port several times).
227 	 */
228 	temporarily_use_uid(original_real_uid);
229 
230 	/*
231 	 * Set our umask to something reasonable, as some files are created
232 	 * with the default umask.  This will make them world-readable but
233 	 * writable only by the owner, which is ok for all files for which we
234 	 * don't set the modes explicitly.
235 	 */
236 	umask(022);
237 
238 	/* Save our own name. */
239 	av0 = av[0];
240 
241 	/* Initialize option structure to indicate that no values have been set. */
242 	initialize_options(&options);
243 
244 	/* Parse command-line arguments. */
245 	host = NULL;
246 
247 	/* If program name is not one of the standard names, use it as host name. */
248 	if (strchr(av0, '/'))
249 		cp = strrchr(av0, '/') + 1;
250 	else
251 		cp = av0;
252 	if (strcmp(cp, "rsh") != 0 && strcmp(cp, "ssh") != 0 &&
253 	    strcmp(cp, "rlogin") != 0 && strcmp(cp, "slogin") != 0)
254 		host = cp;
255 
256 	for (optind = 1; optind < ac; optind++) {
257 		if (av[optind][0] != '-') {
258 			if (host)
259 				break;
260 			if ((cp = strchr(av[optind], '@'))) {
261 				if(cp == av[optind])
262 					usage();
263 				options.user = av[optind];
264 				*cp = '\0';
265 				host = ++cp;
266 			} else
267 				host = av[optind];
268 			continue;
269 		}
270 		opt = av[optind][1];
271 		if (!opt)
272 			usage();
273 		if (strchr("eilcpLRo", opt)) {	/* options with arguments */
274 			optarg = av[optind] + 2;
275 			if (strcmp(optarg, "") == 0) {
276 				if (optind >= ac - 1)
277 					usage();
278 				optarg = av[++optind];
279 			}
280 		} else {
281 			if (av[optind][2])
282 				usage();
283 			optarg = NULL;
284 		}
285 		switch (opt) {
286 		case '2':
287 			options.protocol = SSH_PROTO_2;
288 			break;
289 		case '4':
290 			IPv4or6 = AF_INET;
291 			break;
292 		case '6':
293 			IPv4or6 = AF_INET6;
294 			break;
295 		case 'n':
296 			stdin_null_flag = 1;
297 			break;
298 		case 'f':
299 			fork_after_authentication_flag = 1;
300 			stdin_null_flag = 1;
301 			break;
302 		case 'x':
303 			options.forward_x11 = 0;
304 			break;
305 		case 'X':
306 			options.forward_x11 = 1;
307 			break;
308 		case 'g':
309 			options.gateway_ports = 1;
310 			break;
311 		case 'P':
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 #ifdef AFS
321 		case 'k':
322 			options.krb4_tgt_passing = 0;
323 			options.krb5_tgt_passing = 0;
324 			options.afs_token_passing = 0;
325 			break;
326 #endif
327 		case 'i':
328 			if (stat(optarg, &st) < 0) {
329 				fprintf(stderr, "Warning: Identity file %s does not exist.\n",
330 					optarg);
331 				break;
332 			}
333 			if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES)
334 				fatal("Too many identity files specified (max %d)",
335 				      SSH_MAX_IDENTITY_FILES);
336 			options.identity_files[options.num_identity_files++] =
337 				xstrdup(optarg);
338 			break;
339 		case 't':
340 			tty_flag = 1;
341 			break;
342 		case 'v':
343 		case 'V':
344 			fprintf(stderr, "SSH Version %s, protocol versions %d.%d/%d.%d.\n",
345 			    SSH_VERSION,
346 			    PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
347 			    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
348 			fprintf(stderr, "Compiled with SSL (0x%8.8lx).\n", SSLeay());
349 			if (opt == 'V')
350 				exit(0);
351 			debug_flag = 1;
352 			options.log_level = SYSLOG_LEVEL_DEBUG;
353 			break;
354 		case 'q':
355 			options.log_level = SYSLOG_LEVEL_QUIET;
356 			break;
357 		case 'e':
358 			if (optarg[0] == '^' && optarg[2] == 0 &&
359 			    (unsigned char) optarg[1] >= 64 && (unsigned char) optarg[1] < 128)
360 				options.escape_char = (unsigned char) optarg[1] & 31;
361 			else if (strlen(optarg) == 1)
362 				options.escape_char = (unsigned char) optarg[0];
363 			else if (strcmp(optarg, "none") == 0)
364 				options.escape_char = -2;
365 			else {
366 				fprintf(stderr, "Bad escape character '%s'.\n", optarg);
367 				exit(1);
368 			}
369 			break;
370 		case 'c':
371 			if (ciphers_valid(optarg)) {
372 				/* SSH2 only */
373 				options.ciphers = xstrdup(optarg);
374 				options.cipher = SSH_CIPHER_ILLEGAL;
375 			} else {
376 				/* SSH1 only */
377 				options.cipher = cipher_number(optarg);
378 				if (options.cipher == -1) {
379 					fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
380 					exit(1);
381 				}
382 			}
383 			break;
384 		case 'p':
385 			options.port = atoi(optarg);
386 			break;
387 		case 'l':
388 			options.user = optarg;
389 			break;
390 		case 'R':
391 			if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
392 			    &fwd_host_port) != 3 &&
393 			    sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
394 			    &fwd_host_port) != 3) {
395 				fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
396 				usage();
397 				/* NOTREACHED */
398 			}
399 			add_remote_forward(&options, fwd_port, buf, fwd_host_port);
400 			break;
401 		case 'L':
402 			if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
403 			    &fwd_host_port) != 3 &&
404 			    sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
405 			    &fwd_host_port) != 3) {
406 				fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
407 				usage();
408 				/* NOTREACHED */
409 			}
410 			add_local_forward(&options, fwd_port, buf, fwd_host_port);
411 			break;
412 		case 'C':
413 			options.compression = 1;
414 			break;
415 		case 'N':
416 			no_shell_flag = 1;
417 			no_tty_flag = 1;
418 			break;
419 		case 'T':
420 			no_tty_flag = 1;
421 			break;
422 		case 'o':
423 			dummy = 1;
424 			if (process_config_line(&options, host ? host : "", optarg,
425 					 "command-line", 0, &dummy) != 0)
426 				exit(1);
427 			break;
428 		default:
429 			usage();
430 		}
431 	}
432 
433 	/* Check that we got a host name. */
434 	if (!host)
435 		usage();
436 
437 	SSLeay_add_all_algorithms();
438 
439 	/* Initialize the command to execute on remote host. */
440 	buffer_init(&command);
441 
442 	/*
443 	 * Save the command to execute on the remote host in a buffer. There
444 	 * is no limit on the length of the command, except by the maximum
445 	 * packet size.  Also sets the tty flag if there is no command.
446 	 */
447 	if (optind == ac) {
448 		/* No command specified - execute shell on a tty. */
449 		tty_flag = 1;
450 	} else {
451 		/* A command has been specified.  Store it into the
452 		   buffer. */
453 		for (i = optind; i < ac; i++) {
454 			if (i > optind)
455 				buffer_append(&command, " ", 1);
456 			buffer_append(&command, av[i], strlen(av[i]));
457 		}
458 	}
459 
460 	/* Cannot fork to background if no command. */
461 	if (fork_after_authentication_flag && buffer_len(&command) == 0)
462 		fatal("Cannot fork into background without a command to execute.");
463 
464 	/* Allocate a tty by default if no command specified. */
465 	if (buffer_len(&command) == 0)
466 		tty_flag = 1;
467 
468 	/* Do not allocate a tty if stdin is not a tty. */
469 	if (!isatty(fileno(stdin))) {
470 		if (tty_flag)
471 			fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
472 		tty_flag = 0;
473 	}
474 	/* force */
475 	if (no_tty_flag)
476 		tty_flag = 0;
477 
478 	/* Get user data. */
479 	pw = getpwuid(original_real_uid);
480 	if (!pw) {
481 		fprintf(stderr, "You don't exist, go away!\n");
482 		exit(1);
483 	}
484 	/* Take a copy of the returned structure. */
485 	memset(&pwcopy, 0, sizeof(pwcopy));
486 	pwcopy.pw_name = xstrdup(pw->pw_name);
487 	pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
488 	pwcopy.pw_uid = pw->pw_uid;
489 	pwcopy.pw_gid = pw->pw_gid;
490 	pwcopy.pw_dir = xstrdup(pw->pw_dir);
491 	pwcopy.pw_shell = xstrdup(pw->pw_shell);
492 	pw = &pwcopy;
493 
494 	/* Initialize "log" output.  Since we are the client all output
495 	   actually goes to the terminal. */
496 	log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
497 
498 	/* Read per-user configuration file. */
499 	snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
500 	read_config_file(buf, host, &options);
501 
502 	/* Read systemwide configuration file. */
503 	read_config_file(HOST_CONFIG_FILE, host, &options);
504 
505 	/* Fill configuration defaults. */
506 	fill_default_options(&options);
507 
508 	/* reinit */
509 	log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
510 
511 	/* check if RSA support exists */
512 	if ((options.protocol & SSH_PROTO_1) &&
513 	    rsa_alive() == 0) {
514 		log("%s: no RSA support in libssl and libcrypto.  See ssl(8).",
515 		    __progname);
516 		log("Disabling protocol version 1");
517 		options.protocol &= ~ (SSH_PROTO_1|SSH_PROTO_1_PREFERRED);
518 	}
519 	if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) {
520 		fprintf(stderr, "%s: No protocol version available.\n",
521 		    __progname);
522  		exit(1);
523 	}
524 
525 	if (options.user == NULL)
526 		options.user = xstrdup(pw->pw_name);
527 
528 	if (options.hostname != NULL)
529 		host = options.hostname;
530 
531 	/* Find canonic host name. */
532 	if (strchr(host, '.') == 0) {
533 		struct addrinfo hints;
534 		struct addrinfo *ai = NULL;
535 		int errgai;
536 		memset(&hints, 0, sizeof(hints));
537 		hints.ai_family = IPv4or6;
538 		hints.ai_flags = AI_CANONNAME;
539 		hints.ai_socktype = SOCK_STREAM;
540 		errgai = getaddrinfo(host, NULL, &hints, &ai);
541 		if (errgai == 0) {
542 			if (ai->ai_canonname != NULL)
543 				host = xstrdup(ai->ai_canonname);
544 			freeaddrinfo(ai);
545 		}
546 	}
547 	/* Disable rhosts authentication if not running as root. */
548 	if (original_effective_uid != 0 || !options.use_privileged_port) {
549 		options.rhosts_authentication = 0;
550 		options.rhosts_rsa_authentication = 0;
551 	}
552 	/*
553 	 * If using rsh has been selected, exec it now (without trying
554 	 * anything else).  Note that we must release privileges first.
555 	 */
556 	if (options.use_rsh) {
557 		/*
558 		 * Restore our superuser privileges.  This must be done
559 		 * before permanently setting the uid.
560 		 */
561 		restore_uid();
562 
563 		/* Switch to the original uid permanently. */
564 		permanently_set_uid(original_real_uid);
565 
566 		/* Execute rsh. */
567 		rsh_connect(host, options.user, &command);
568 		fatal("rsh_connect returned");
569 	}
570 	/* Restore our superuser privileges. */
571 	restore_uid();
572 
573 	/*
574 	 * Open a connection to the remote host.  This needs root privileges
575 	 * if rhosts_{rsa_}authentication is enabled.
576 	 */
577 
578 	ok = ssh_connect(host, &hostaddr, options.port,
579 			 options.connection_attempts,
580 			 !options.rhosts_authentication &&
581 			 !options.rhosts_rsa_authentication,
582 			 original_real_uid,
583 			 options.proxy_command);
584 
585 	/*
586 	 * If we successfully made the connection, load the host private key
587 	 * in case we will need it later for combined rsa-rhosts
588 	 * authentication. This must be done before releasing extra
589 	 * privileges, because the file is only readable by root.
590 	 */
591 	if (ok && (options.protocol & SSH_PROTO_1)) {
592 		Key k;
593 		host_private_key = RSA_new();
594 		k.type = KEY_RSA;
595 		k.rsa = host_private_key;
596 		if (load_private_key(HOST_KEY_FILE, "", &k, NULL))
597 			host_private_key_loaded = 1;
598 	}
599 	/*
600 	 * Get rid of any extra privileges that we may have.  We will no
601 	 * longer need them.  Also, extra privileges could make it very hard
602 	 * to read identity files and other non-world-readable files from the
603 	 * user's home directory if it happens to be on a NFS volume where
604 	 * root is mapped to nobody.
605 	 */
606 
607 	/*
608 	 * Note that some legacy systems need to postpone the following call
609 	 * to permanently_set_uid() until the private hostkey is destroyed
610 	 * with RSA_free().  Otherwise the calling user could ptrace() the
611 	 * process, read the private hostkey and impersonate the host.
612 	 * OpenBSD does not allow ptracing of setuid processes.
613 	 */
614 	permanently_set_uid(original_real_uid);
615 
616 	/*
617 	 * Now that we are back to our own permissions, create ~/.ssh
618 	 * directory if it doesn\'t already exist.
619 	 */
620 	snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
621 	if (stat(buf, &st) < 0)
622 		if (mkdir(buf, 0755) < 0)
623 			error("Could not create directory '%.200s'.", buf);
624 
625 	/* Check if the connection failed, and try "rsh" if appropriate. */
626 	if (!ok) {
627 		if (options.port != 0)
628 			log("Secure connection to %.100s on port %hu refused%.100s.",
629 			    host, options.port,
630 			    options.fallback_to_rsh ? "; reverting to insecure method" : "");
631 		else
632 			log("Secure connection to %.100s refused%.100s.", host,
633 			    options.fallback_to_rsh ? "; reverting to insecure method" : "");
634 
635 		if (options.fallback_to_rsh) {
636 			rsh_connect(host, options.user, &command);
637 			fatal("rsh_connect returned");
638 		}
639 		exit(1);
640 	}
641 	/* Expand ~ in options.identity_files. */
642 	/* XXX mem-leaks */
643 	for (i = 0; i < options.num_identity_files; i++)
644 		options.identity_files[i] =
645 			tilde_expand_filename(options.identity_files[i], original_real_uid);
646 	for (i = 0; i < options.num_identity_files2; i++)
647 		options.identity_files2[i] =
648 			tilde_expand_filename(options.identity_files2[i], original_real_uid);
649 	/* Expand ~ in known host file names. */
650 	options.system_hostfile = tilde_expand_filename(options.system_hostfile,
651 	    original_real_uid);
652 	options.user_hostfile = tilde_expand_filename(options.user_hostfile,
653 	    original_real_uid);
654 	options.system_hostfile2 = tilde_expand_filename(options.system_hostfile2,
655 	    original_real_uid);
656 	options.user_hostfile2 = tilde_expand_filename(options.user_hostfile2,
657 	    original_real_uid);
658 
659 	/* Log into the remote system.  This never returns if the login fails. */
660 	ssh_login(host_private_key_loaded, host_private_key,
661 		  host, (struct sockaddr *)&hostaddr, original_real_uid);
662 
663 	/* We no longer need the host private key.  Clear it now. */
664 	if (host_private_key_loaded)
665 		RSA_free(host_private_key);	/* Destroys contents safely */
666 
667 	exit_status = compat20 ? ssh_session2() : ssh_session();
668 	packet_close();
669 	return exit_status;
670 }
671 
672 void
673 x11_get_proto(char *proto, int proto_len, char *data, int data_len)
674 {
675 	char line[512];
676 	FILE *f;
677 	int got_data = 0, i;
678 
679 #ifdef XAUTH_PATH
680 	/* Try to get Xauthority information for the display. */
681 	snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
682 		 XAUTH_PATH, getenv("DISPLAY"));
683 	f = popen(line, "r");
684 	if (f && fgets(line, sizeof(line), f) &&
685 	    sscanf(line, "%*s %s %s", proto, data) == 2)
686 		got_data = 1;
687 	if (f)
688 		pclose(f);
689 #endif /* XAUTH_PATH */
690 	/*
691 	 * If we didn't get authentication data, just make up some
692 	 * data.  The forwarding code will check the validity of the
693 	 * response anyway, and substitute this data.  The X11
694 	 * server, however, will ignore this fake data and use
695 	 * whatever authentication mechanisms it was using otherwise
696 	 * for the local connection.
697 	 */
698 	if (!got_data) {
699 		u_int32_t rand = 0;
700 
701 		strlcpy(proto, "MIT-MAGIC-COOKIE-1", proto_len);
702 		for (i = 0; i < 16; i++) {
703 			if (i % 4 == 0)
704 				rand = arc4random();
705 			snprintf(data + 2 * i, data_len - 2 * i, "%02x", rand & 0xff);
706 			rand >>= 8;
707 		}
708 	}
709 }
710 
711 int
712 ssh_session(void)
713 {
714 	int type;
715 	int i;
716 	int plen;
717 	int interactive = 0;
718 	int have_tty = 0;
719 	struct winsize ws;
720 	int authfd;
721 	char *cp;
722 
723 	/* Enable compression if requested. */
724 	if (options.compression) {
725 		debug("Requesting compression at level %d.", options.compression_level);
726 
727 		if (options.compression_level < 1 || options.compression_level > 9)
728 			fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
729 
730 		/* Send the request. */
731 		packet_start(SSH_CMSG_REQUEST_COMPRESSION);
732 		packet_put_int(options.compression_level);
733 		packet_send();
734 		packet_write_wait();
735 		type = packet_read(&plen);
736 		if (type == SSH_SMSG_SUCCESS)
737 			packet_start_compression(options.compression_level);
738 		else if (type == SSH_SMSG_FAILURE)
739 			log("Warning: Remote host refused compression.");
740 		else
741 			packet_disconnect("Protocol error waiting for compression response.");
742 	}
743 	/* Allocate a pseudo tty if appropriate. */
744 	if (tty_flag) {
745 		debug("Requesting pty.");
746 
747 		/* Start the packet. */
748 		packet_start(SSH_CMSG_REQUEST_PTY);
749 
750 		/* Store TERM in the packet.  There is no limit on the
751 		   length of the string. */
752 		cp = getenv("TERM");
753 		if (!cp)
754 			cp = "";
755 		packet_put_string(cp, strlen(cp));
756 
757 		/* Store window size in the packet. */
758 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
759 			memset(&ws, 0, sizeof(ws));
760 		packet_put_int(ws.ws_row);
761 		packet_put_int(ws.ws_col);
762 		packet_put_int(ws.ws_xpixel);
763 		packet_put_int(ws.ws_ypixel);
764 
765 		/* Store tty modes in the packet. */
766 		tty_make_modes(fileno(stdin));
767 
768 		/* Send the packet, and wait for it to leave. */
769 		packet_send();
770 		packet_write_wait();
771 
772 		/* Read response from the server. */
773 		type = packet_read(&plen);
774 		if (type == SSH_SMSG_SUCCESS) {
775 			interactive = 1;
776 			have_tty = 1;
777 		} else if (type == SSH_SMSG_FAILURE)
778 			log("Warning: Remote host failed or refused to allocate a pseudo tty.");
779 		else
780 			packet_disconnect("Protocol error waiting for pty request response.");
781 	}
782 	/* Request X11 forwarding if enabled and DISPLAY is set. */
783 	if (options.forward_x11 && getenv("DISPLAY") != NULL) {
784 		char proto[512], data[512];
785 		/* Get reasonable local authentication information. */
786 		x11_get_proto(proto, sizeof proto, data, sizeof data);
787 		/* Request forwarding with authentication spoofing. */
788 		debug("Requesting X11 forwarding with authentication spoofing.");
789 		x11_request_forwarding_with_spoofing(0, proto, data);
790 
791 		/* Read response from the server. */
792 		type = packet_read(&plen);
793 		if (type == SSH_SMSG_SUCCESS) {
794 			interactive = 1;
795 		} else if (type == SSH_SMSG_FAILURE) {
796 			log("Warning: Remote host denied X11 forwarding.");
797 		} else {
798 			packet_disconnect("Protocol error waiting for X11 forwarding");
799 		}
800 	}
801 	/* Tell the packet module whether this is an interactive session. */
802 	packet_set_interactive(interactive, options.keepalives);
803 
804 	/* Clear agent forwarding if we don\'t have an agent. */
805 	authfd = ssh_get_authentication_socket();
806 	if (authfd < 0)
807 		options.forward_agent = 0;
808 	else
809 		ssh_close_authentication_socket(authfd);
810 
811 	/* Request authentication agent forwarding if appropriate. */
812 	if (options.forward_agent) {
813 		debug("Requesting authentication agent forwarding.");
814 		auth_request_forwarding();
815 
816 		/* Read response from the server. */
817 		type = packet_read(&plen);
818 		packet_integrity_check(plen, 0, type);
819 		if (type != SSH_SMSG_SUCCESS)
820 			log("Warning: Remote host denied authentication agent forwarding.");
821 	}
822 	/* Initiate local TCP/IP port forwardings. */
823 	for (i = 0; i < options.num_local_forwards; i++) {
824 		debug("Connections to local port %d forwarded to remote address %.200s:%d",
825 		      options.local_forwards[i].port,
826 		      options.local_forwards[i].host,
827 		      options.local_forwards[i].host_port);
828 		channel_request_local_forwarding(options.local_forwards[i].port,
829 						 options.local_forwards[i].host,
830 						 options.local_forwards[i].host_port,
831 						 options.gateway_ports);
832 	}
833 
834 	/* Initiate remote TCP/IP port forwardings. */
835 	for (i = 0; i < options.num_remote_forwards; i++) {
836 		debug("Connections to remote port %d forwarded to local address %.200s:%d",
837 		      options.remote_forwards[i].port,
838 		      options.remote_forwards[i].host,
839 		      options.remote_forwards[i].host_port);
840 		channel_request_remote_forwarding(options.remote_forwards[i].port,
841 						  options.remote_forwards[i].host,
842 						  options.remote_forwards[i].host_port);
843 	}
844 
845 	/* If requested, let ssh continue in the background. */
846 	if (fork_after_authentication_flag)
847 		if (daemon(1, 1) < 0)
848 			fatal("daemon() failed: %.200s", strerror(errno));
849 
850 	/*
851 	 * If a command was specified on the command line, execute the
852 	 * command now. Otherwise request the server to start a shell.
853 	 */
854 	if (buffer_len(&command) > 0) {
855 		int len = buffer_len(&command);
856 		if (len > 900)
857 			len = 900;
858 		debug("Sending command: %.*s", len, buffer_ptr(&command));
859 		packet_start(SSH_CMSG_EXEC_CMD);
860 		packet_put_string(buffer_ptr(&command), buffer_len(&command));
861 		packet_send();
862 		packet_write_wait();
863 	} else {
864 		debug("Requesting shell.");
865 		packet_start(SSH_CMSG_EXEC_SHELL);
866 		packet_send();
867 		packet_write_wait();
868 	}
869 
870 	/* Enter the interactive session. */
871 	return client_loop(have_tty, tty_flag ? options.escape_char : -1);
872 }
873 
874 void
875 init_local_fwd(void)
876 {
877 	int i;
878 	/* Initiate local TCP/IP port forwardings. */
879 	for (i = 0; i < options.num_local_forwards; i++) {
880 		debug("Connections to local port %d forwarded to remote address %.200s:%d",
881 		      options.local_forwards[i].port,
882 		      options.local_forwards[i].host,
883 		      options.local_forwards[i].host_port);
884 		channel_request_local_forwarding(options.local_forwards[i].port,
885 						 options.local_forwards[i].host,
886 						 options.local_forwards[i].host_port,
887 						 options.gateway_ports);
888 	}
889 }
890 
891 extern void client_set_session_ident(int id);
892 
893 void
894 client_init(int id, void *arg)
895 {
896 	int len;
897 	debug("client_init id %d arg %d", id, (int)arg);
898 
899 	if (no_shell_flag)
900 		goto done;
901 
902 	if (tty_flag) {
903 		struct winsize ws;
904 		char *cp;
905 		cp = getenv("TERM");
906 		if (!cp)
907 			cp = "";
908 		/* Store window size in the packet. */
909 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
910 			memset(&ws, 0, sizeof(ws));
911 
912 		channel_request_start(id, "pty-req", 0);
913 		packet_put_cstring(cp);
914 		packet_put_int(ws.ws_col);
915 		packet_put_int(ws.ws_row);
916 		packet_put_int(ws.ws_xpixel);
917 		packet_put_int(ws.ws_ypixel);
918 		packet_put_cstring("");		/* XXX: encode terminal modes */
919 		packet_send();
920 		/* XXX wait for reply */
921 	}
922 	if (options.forward_x11 &&
923 	    getenv("DISPLAY") != NULL) {
924 		char proto[512], data[512];
925 		/* Get reasonable local authentication information. */
926 		x11_get_proto(proto, sizeof proto, data, sizeof data);
927 		/* Request forwarding with authentication spoofing. */
928 		debug("Requesting X11 forwarding with authentication spoofing.");
929 		x11_request_forwarding_with_spoofing(id, proto, data);
930 		/* XXX wait for reply */
931 	}
932 
933 	len = buffer_len(&command);
934 	if (len > 0) {
935 		if (len > 900)
936 			len = 900;
937 		debug("Sending command: %.*s", len, buffer_ptr(&command));
938 		channel_request_start(id, "exec", 0);
939 		packet_put_string(buffer_ptr(&command), len);
940 		packet_send();
941 	} else {
942 		channel_request(id, "shell", 0);
943 	}
944 	/* channel_callback(id, SSH2_MSG_OPEN_CONFIGMATION, client_init, 0); */
945 done:
946 	/* register different callback, etc. XXX */
947 	client_set_session_ident(id);
948 }
949 
950 int
951 ssh_session2(void)
952 {
953 	int window, packetmax, id;
954 	int in  = dup(STDIN_FILENO);
955 	int out = dup(STDOUT_FILENO);
956 	int err = dup(STDERR_FILENO);
957 
958 	if (in < 0 || out < 0 || err < 0)
959 		fatal("dump in/out/err failed");
960 
961 	/* should be pre-session */
962 	init_local_fwd();
963 
964 	window = 32*1024;
965 	if (tty_flag) {
966 		packetmax = window/8;
967 	} else {
968 		window *= 2;
969 		packetmax = window/2;
970 	}
971 
972 	id = channel_new(
973 	    "session", SSH_CHANNEL_OPENING, in, out, err,
974 	    window, packetmax, CHAN_EXTENDED_WRITE, xstrdup("client-session"));
975 
976 
977 	channel_open(id);
978 	channel_register_callback(id, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, client_init, (void *)0);
979 
980 	return client_loop(tty_flag, tty_flag ? options.escape_char : -1);
981 }
982