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