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