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