ssh.c revision 149753
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, 2003 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.249 2005/07/30 01:26:16 djm Exp $");
44RCSID("$FreeBSD: head/crypto/openssh/ssh.c 149753 2005-09-03 07:04:25Z 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 "bufaux.h"
58#include "channels.h"
59#include "key.h"
60#include "authfd.h"
61#include "authfile.h"
62#include "pathnames.h"
63#include "dispatch.h"
64#include "clientloop.h"
65#include "log.h"
66#include "readconf.h"
67#include "sshconnect.h"
68#include "misc.h"
69#include "kex.h"
70#include "mac.h"
71#include "sshpty.h"
72#include "match.h"
73#include "msg.h"
74#include "monitor_fdpass.h"
75#include "uidswap.h"
76
77#ifdef SMARTCARD
78#include "scard.h"
79#endif
80
81extern char *__progname;
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/* pid of proxycommand child process */
143pid_t proxy_command_pid = 0;
144
145/* fd to control socket */
146int control_fd = -1;
147
148/* Multiplexing control command */
149static u_int mux_command = 0;
150
151/* Only used in control client mode */
152volatile sig_atomic_t control_client_terminate = 0;
153u_int control_server_pid = 0;
154
155/* Prints a help message to the user.  This function never returns. */
156
157static void
158usage(void)
159{
160	fprintf(stderr,
161"usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
162"           [-D port] [-e escape_char] [-F configfile]\n"
163"           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
164"           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
165"           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
166"           [user@]hostname [command]\n"
167	);
168	exit(1);
169}
170
171static int ssh_session(void);
172static int ssh_session2(void);
173static void load_public_identity_files(void);
174static void control_client(const char *path);
175
176/*
177 * Main program for the ssh client.
178 */
179int
180main(int ac, char **av)
181{
182	int i, opt, exit_status;
183	char *p, *cp, *line, buf[256];
184	struct stat st;
185	struct passwd *pw;
186	int dummy;
187	extern int optind, optreset;
188	extern char *optarg;
189	struct servent *sp;
190	Forward fwd;
191
192	__progname = ssh_get_progname(av[0]);
193	init_rng();
194
195	/*
196	 * Save the original real uid.  It will be needed later (uid-swapping
197	 * may clobber the real uid).
198	 */
199	original_real_uid = getuid();
200	original_effective_uid = geteuid();
201
202	/*
203	 * Use uid-swapping to give up root privileges for the duration of
204	 * option processing.  We will re-instantiate the rights when we are
205	 * ready to create the privileged port, and will permanently drop
206	 * them when the port has been created (actually, when the connection
207	 * has been made, as we may need to create the port several times).
208	 */
209	PRIV_END;
210
211#ifdef HAVE_SETRLIMIT
212	/* If we are installed setuid root be careful to not drop core. */
213	if (original_real_uid != original_effective_uid) {
214		struct rlimit rlim;
215		rlim.rlim_cur = rlim.rlim_max = 0;
216		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
217			fatal("setrlimit failed: %.100s", strerror(errno));
218	}
219#endif
220	/* Get user data. */
221	pw = getpwuid(original_real_uid);
222	if (!pw) {
223		logit("You don't exist, go away!");
224		exit(1);
225	}
226	/* Take a copy of the returned structure. */
227	pw = pwcopy(pw);
228
229	/*
230	 * Set our umask to something reasonable, as some files are created
231	 * with the default umask.  This will make them world-readable but
232	 * writable only by the owner, which is ok for all files for which we
233	 * don't set the modes explicitly.
234	 */
235	umask(022);
236
237	/* Initialize option structure to indicate that no values have been set. */
238	initialize_options(&options);
239
240	/* Parse command-line arguments. */
241	host = NULL;
242
243again:
244	while ((opt = getopt(ac, av,
245	    "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVXY")) != -1) {
246		switch (opt) {
247		case '1':
248			options.protocol = SSH_PROTO_1;
249			break;
250		case '2':
251			options.protocol = SSH_PROTO_2;
252			break;
253		case '4':
254			options.address_family = AF_INET;
255			break;
256		case '6':
257			options.address_family = AF_INET6;
258			break;
259		case 'n':
260			stdin_null_flag = 1;
261			break;
262		case 'f':
263			fork_after_authentication_flag = 1;
264			stdin_null_flag = 1;
265			break;
266		case 'x':
267			options.forward_x11 = 0;
268			break;
269		case 'X':
270			options.forward_x11 = 1;
271			break;
272		case 'Y':
273			options.forward_x11 = 1;
274			options.forward_x11_trusted = 1;
275			break;
276		case 'g':
277			options.gateway_ports = 1;
278			break;
279		case 'O':
280			if (strcmp(optarg, "check") == 0)
281				mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
282			else if (strcmp(optarg, "exit") == 0)
283				mux_command = SSHMUX_COMMAND_TERMINATE;
284			else
285				fatal("Invalid multiplex command.");
286			break;
287		case 'P':	/* deprecated */
288			options.use_privileged_port = 0;
289			break;
290		case 'a':
291			options.forward_agent = 0;
292			break;
293		case 'A':
294			options.forward_agent = 1;
295			break;
296		case 'k':
297			options.gss_deleg_creds = 0;
298			break;
299		case 'i':
300			if (stat(optarg, &st) < 0) {
301				fprintf(stderr, "Warning: Identity file %s "
302				    "not accessible: %s.\n", optarg,
303				    strerror(errno));
304				break;
305			}
306			if (options.num_identity_files >=
307			    SSH_MAX_IDENTITY_FILES)
308				fatal("Too many identity files specified "
309				    "(max %d)", SSH_MAX_IDENTITY_FILES);
310			options.identity_files[options.num_identity_files++] =
311			    xstrdup(optarg);
312			break;
313		case 'I':
314#ifdef SMARTCARD
315			options.smartcard_device = xstrdup(optarg);
316#else
317			fprintf(stderr, "no support for smartcards.\n");
318#endif
319			break;
320		case 't':
321			if (tty_flag)
322				force_tty_flag = 1;
323			tty_flag = 1;
324			break;
325		case 'v':
326			if (debug_flag == 0) {
327				debug_flag = 1;
328				options.log_level = SYSLOG_LEVEL_DEBUG1;
329			} else {
330				if (options.log_level < SYSLOG_LEVEL_DEBUG3)
331					options.log_level++;
332				break;
333			}
334			/* FALLTHROUGH */
335		case 'V':
336			fprintf(stderr, "%s, %s\n",
337			    SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
338			if (opt == 'V')
339				exit(0);
340			break;
341		case 'q':
342			options.log_level = SYSLOG_LEVEL_QUIET;
343			break;
344		case 'e':
345			if (optarg[0] == '^' && optarg[2] == 0 &&
346			    (u_char) optarg[1] >= 64 &&
347			    (u_char) optarg[1] < 128)
348				options.escape_char = (u_char) optarg[1] & 31;
349			else if (strlen(optarg) == 1)
350				options.escape_char = (u_char) optarg[0];
351			else if (strcmp(optarg, "none") == 0)
352				options.escape_char = SSH_ESCAPECHAR_NONE;
353			else {
354				fprintf(stderr, "Bad escape character '%s'.\n",
355				    optarg);
356				exit(1);
357			}
358			break;
359		case 'c':
360			if (ciphers_valid(optarg)) {
361				/* SSH2 only */
362				options.ciphers = xstrdup(optarg);
363				options.cipher = SSH_CIPHER_INVALID;
364			} else {
365				/* SSH1 only */
366				options.cipher = cipher_number(optarg);
367				if (options.cipher == -1) {
368					fprintf(stderr,
369					    "Unknown cipher type '%s'\n",
370					    optarg);
371					exit(1);
372				}
373				if (options.cipher == SSH_CIPHER_3DES)
374					options.ciphers = "3des-cbc";
375				else if (options.cipher == SSH_CIPHER_BLOWFISH)
376					options.ciphers = "blowfish-cbc";
377				else
378					options.ciphers = (char *)-1;
379			}
380			break;
381		case 'm':
382			if (mac_valid(optarg))
383				options.macs = xstrdup(optarg);
384			else {
385				fprintf(stderr, "Unknown mac type '%s'\n",
386				    optarg);
387				exit(1);
388			}
389			break;
390		case 'M':
391			if (options.control_master == SSHCTL_MASTER_YES)
392				options.control_master = SSHCTL_MASTER_ASK;
393			else
394				options.control_master = SSHCTL_MASTER_YES;
395			break;
396		case 'p':
397			options.port = a2port(optarg);
398			if (options.port == 0) {
399				fprintf(stderr, "Bad port '%s'\n", optarg);
400				exit(1);
401			}
402			break;
403		case 'l':
404			options.user = optarg;
405			break;
406
407		case 'L':
408			if (parse_forward(&fwd, optarg))
409				add_local_forward(&options, &fwd);
410			else {
411				fprintf(stderr,
412				    "Bad local forwarding specification '%s'\n",
413				    optarg);
414				exit(1);
415			}
416			break;
417
418		case 'R':
419			if (parse_forward(&fwd, optarg)) {
420				add_remote_forward(&options, &fwd);
421			} else {
422				fprintf(stderr,
423				    "Bad remote forwarding specification "
424				    "'%s'\n", optarg);
425				exit(1);
426			}
427			break;
428
429		case 'D':
430			cp = p = xstrdup(optarg);
431			memset(&fwd, '\0', sizeof(fwd));
432			fwd.connect_host = "socks";
433			if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
434				fprintf(stderr, "Bad dynamic forwarding "
435				    "specification '%.100s'\n", optarg);
436				exit(1);
437			}
438			if (cp != NULL) {
439				fwd.listen_port = a2port(cp);
440				fwd.listen_host = cleanhostname(fwd.listen_host);
441			} else {
442				fwd.listen_port = a2port(fwd.listen_host);
443				fwd.listen_host = NULL;
444			}
445
446			if (fwd.listen_port == 0) {
447				fprintf(stderr, "Bad dynamic port '%s'\n",
448				    optarg);
449				exit(1);
450			}
451			add_local_forward(&options, &fwd);
452			xfree(p);
453			break;
454
455		case 'C':
456			options.compression = 1;
457			break;
458		case 'N':
459			no_shell_flag = 1;
460			no_tty_flag = 1;
461			break;
462		case 'T':
463			no_tty_flag = 1;
464			break;
465		case 'o':
466			dummy = 1;
467			line = xstrdup(optarg);
468			if (process_config_line(&options, host ? host : "",
469			    line, "command-line", 0, &dummy) != 0)
470				exit(1);
471			xfree(line);
472			break;
473		case 's':
474			subsystem_flag = 1;
475			break;
476		case 'S':
477			if (options.control_path != NULL)
478				free(options.control_path);
479			options.control_path = xstrdup(optarg);
480			break;
481		case 'b':
482			options.bind_address = optarg;
483			break;
484		case 'F':
485			config = optarg;
486			break;
487		default:
488			usage();
489		}
490	}
491
492	ac -= optind;
493	av += optind;
494
495	if (ac > 0 && !host && **av != '-') {
496		if (strrchr(*av, '@')) {
497			p = xstrdup(*av);
498			cp = strrchr(p, '@');
499			if (cp == NULL || cp == p)
500				usage();
501			options.user = p;
502			*cp = '\0';
503			host = ++cp;
504		} else
505			host = *av;
506		if (ac > 1) {
507			optind = optreset = 1;
508			goto again;
509		}
510		ac--, av++;
511	}
512
513	/* Check that we got a host name. */
514	if (!host)
515		usage();
516
517	SSLeay_add_all_algorithms();
518	ERR_load_crypto_strings();
519
520	/* Initialize the command to execute on remote host. */
521	buffer_init(&command);
522
523	/*
524	 * Save the command to execute on the remote host in a buffer. There
525	 * is no limit on the length of the command, except by the maximum
526	 * packet size.  Also sets the tty flag if there is no command.
527	 */
528	if (!ac) {
529		/* No command specified - execute shell on a tty. */
530		tty_flag = 1;
531		if (subsystem_flag) {
532			fprintf(stderr,
533			    "You must specify a subsystem to invoke.\n");
534			usage();
535		}
536	} else {
537		/* A command has been specified.  Store it into the buffer. */
538		for (i = 0; i < ac; i++) {
539			if (i)
540				buffer_append(&command, " ", 1);
541			buffer_append(&command, av[i], strlen(av[i]));
542		}
543	}
544
545	/* Cannot fork to background if no command. */
546	if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
547		fatal("Cannot fork into background without a command to execute.");
548
549	/* Allocate a tty by default if no command specified. */
550	if (buffer_len(&command) == 0)
551		tty_flag = 1;
552
553	/* Force no tty */
554	if (no_tty_flag)
555		tty_flag = 0;
556	/* Do not allocate a tty if stdin is not a tty. */
557	if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
558		if (tty_flag)
559			logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
560		tty_flag = 0;
561	}
562
563	/*
564	 * Initialize "log" output.  Since we are the client all output
565	 * actually goes to stderr.
566	 */
567	log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
568	    SYSLOG_FACILITY_USER, 1);
569
570	/*
571	 * Read per-user configuration file.  Ignore the system wide config
572	 * file if the user specifies a config file on the command line.
573	 */
574	if (config != NULL) {
575		if (!read_config_file(config, host, &options, 0))
576			fatal("Can't open user config file %.100s: "
577			    "%.100s", config, strerror(errno));
578	} else  {
579		snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
580		    _PATH_SSH_USER_CONFFILE);
581		(void)read_config_file(buf, host, &options, 1);
582
583		/* Read systemwide configuration file after use config. */
584		(void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
585		    &options, 0);
586	}
587
588	/* Fill configuration defaults. */
589	fill_default_options(&options);
590
591	channel_set_af(options.address_family);
592
593	/* reinit */
594	log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
595
596	seed_rng();
597
598	if (options.user == NULL)
599		options.user = xstrdup(pw->pw_name);
600
601	if (options.hostname != NULL)
602		host = options.hostname;
603
604	/* Find canonic host name. */
605	if (strchr(host, '.') == 0) {
606		struct addrinfo hints;
607		struct addrinfo *ai = NULL;
608		int errgai;
609		memset(&hints, 0, sizeof(hints));
610		hints.ai_family = options.address_family;
611		hints.ai_flags = AI_CANONNAME;
612		hints.ai_socktype = SOCK_STREAM;
613		errgai = getaddrinfo(host, NULL, &hints, &ai);
614		if (errgai == 0) {
615			if (ai->ai_canonname != NULL)
616				host = xstrdup(ai->ai_canonname);
617			freeaddrinfo(ai);
618		}
619	}
620
621	/* force lowercase for hostkey matching */
622	if (options.host_key_alias != NULL) {
623		for (p = options.host_key_alias; *p; p++)
624			if (isupper(*p))
625				*p = tolower(*p);
626	}
627
628	/* Get default port if port has not been set. */
629	if (options.port == 0) {
630		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
631		options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
632	}
633
634	if (options.proxy_command != NULL &&
635	    strcmp(options.proxy_command, "none") == 0)
636		options.proxy_command = NULL;
637	if (options.control_path != NULL &&
638	    strcmp(options.control_path, "none") == 0)
639		options.control_path = NULL;
640
641	if (options.control_path != NULL) {
642		snprintf(buf, sizeof(buf), "%d", options.port);
643		cp = tilde_expand_filename(options.control_path,
644		    original_real_uid);
645		options.control_path = percent_expand(cp, "p", buf, "h", host,
646		    "r", options.user, (char *)NULL);
647		xfree(cp);
648	}
649	if (mux_command != 0 && options.control_path == NULL)
650		fatal("No ControlPath specified for \"-O\" command");
651	if (options.control_path != NULL)
652		control_client(options.control_path);
653
654	/* Open a connection to the remote host. */
655	if (ssh_connect(host, &hostaddr, options.port,
656	    options.address_family, options.connection_attempts,
657#ifdef HAVE_CYGWIN
658	    options.use_privileged_port,
659#else
660	    original_effective_uid == 0 && options.use_privileged_port,
661#endif
662	    options.proxy_command) != 0)
663		exit(1);
664
665	/*
666	 * If we successfully made the connection, load the host private key
667	 * in case we will need it later for combined rsa-rhosts
668	 * authentication. This must be done before releasing extra
669	 * privileges, because the file is only readable by root.
670	 * If we cannot access the private keys, load the public keys
671	 * instead and try to execute the ssh-keysign helper instead.
672	 */
673	sensitive_data.nkeys = 0;
674	sensitive_data.keys = NULL;
675	sensitive_data.external_keysign = 0;
676	if (options.rhosts_rsa_authentication ||
677	    options.hostbased_authentication) {
678		sensitive_data.nkeys = 3;
679		sensitive_data.keys = xmalloc(sensitive_data.nkeys *
680		    sizeof(Key));
681
682		PRIV_START;
683		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
684		    _PATH_HOST_KEY_FILE, "", NULL);
685		sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
686		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
687		sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
688		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
689		PRIV_END;
690
691		if (options.hostbased_authentication == 1 &&
692		    sensitive_data.keys[0] == NULL &&
693		    sensitive_data.keys[1] == NULL &&
694		    sensitive_data.keys[2] == NULL) {
695			sensitive_data.keys[1] = key_load_public(
696			    _PATH_HOST_DSA_KEY_FILE, NULL);
697			sensitive_data.keys[2] = key_load_public(
698			    _PATH_HOST_RSA_KEY_FILE, NULL);
699			sensitive_data.external_keysign = 1;
700		}
701	}
702	/*
703	 * Get rid of any extra privileges that we may have.  We will no
704	 * longer need them.  Also, extra privileges could make it very hard
705	 * to read identity files and other non-world-readable files from the
706	 * user's home directory if it happens to be on a NFS volume where
707	 * root is mapped to nobody.
708	 */
709	if (original_effective_uid == 0) {
710		PRIV_START;
711		permanently_set_uid(pw);
712	}
713
714	/*
715	 * Now that we are back to our own permissions, create ~/.ssh
716	 * directory if it doesn\'t already exist.
717	 */
718	snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
719	if (stat(buf, &st) < 0)
720		if (mkdir(buf, 0700) < 0)
721			error("Could not create directory '%.200s'.", buf);
722
723	/* load options.identity_files */
724	load_public_identity_files();
725
726	/* Expand ~ in known host file names. */
727	/* XXX mem-leaks: */
728	options.system_hostfile =
729	    tilde_expand_filename(options.system_hostfile, original_real_uid);
730	options.user_hostfile =
731	    tilde_expand_filename(options.user_hostfile, original_real_uid);
732	options.system_hostfile2 =
733	    tilde_expand_filename(options.system_hostfile2, original_real_uid);
734	options.user_hostfile2 =
735	    tilde_expand_filename(options.user_hostfile2, original_real_uid);
736
737	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
738
739	/* Log into the remote system.  This never returns if the login fails. */
740	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
741
742	/* We no longer need the private host keys.  Clear them now. */
743	if (sensitive_data.nkeys != 0) {
744		for (i = 0; i < sensitive_data.nkeys; i++) {
745			if (sensitive_data.keys[i] != NULL) {
746				/* Destroys contents safely */
747				debug3("clear hostkey %d", i);
748				key_free(sensitive_data.keys[i]);
749				sensitive_data.keys[i] = NULL;
750			}
751		}
752		xfree(sensitive_data.keys);
753	}
754	for (i = 0; i < options.num_identity_files; i++) {
755		if (options.identity_files[i]) {
756			xfree(options.identity_files[i]);
757			options.identity_files[i] = NULL;
758		}
759		if (options.identity_keys[i]) {
760			key_free(options.identity_keys[i]);
761			options.identity_keys[i] = NULL;
762		}
763	}
764
765	exit_status = compat20 ? ssh_session2() : ssh_session();
766	packet_close();
767
768	if (options.control_path != NULL && control_fd != -1)
769		unlink(options.control_path);
770
771	/*
772	 * Send SIGHUP to proxy command if used. We don't wait() in
773	 * case it hangs and instead rely on init to reap the child
774	 */
775	if (proxy_command_pid > 1)
776		kill(proxy_command_pid, SIGHUP);
777
778	return exit_status;
779}
780
781static void
782ssh_init_forwarding(void)
783{
784	int success = 0;
785	int i;
786
787	/* Initiate local TCP/IP port forwardings. */
788	for (i = 0; i < options.num_local_forwards; i++) {
789		debug("Local connections to %.200s:%d forwarded to remote "
790		    "address %.200s:%d",
791		    (options.local_forwards[i].listen_host == NULL) ?
792		    (options.gateway_ports ? "*" : "LOCALHOST") :
793		    options.local_forwards[i].listen_host,
794		    options.local_forwards[i].listen_port,
795		    options.local_forwards[i].connect_host,
796		    options.local_forwards[i].connect_port);
797		success += channel_setup_local_fwd_listener(
798		    options.local_forwards[i].listen_host,
799		    options.local_forwards[i].listen_port,
800		    options.local_forwards[i].connect_host,
801		    options.local_forwards[i].connect_port,
802		    options.gateway_ports);
803	}
804	if (i > 0 && success == 0)
805		error("Could not request local forwarding.");
806
807	/* Initiate remote TCP/IP port forwardings. */
808	for (i = 0; i < options.num_remote_forwards; i++) {
809		debug("Remote connections from %.200s:%d forwarded to "
810		    "local address %.200s:%d",
811		    (options.remote_forwards[i].listen_host == NULL) ?
812		    (options.gateway_ports ? "*" : "LOCALHOST") :
813		    options.remote_forwards[i].listen_host,
814		    options.remote_forwards[i].listen_port,
815		    options.remote_forwards[i].connect_host,
816		    options.remote_forwards[i].connect_port);
817		channel_request_remote_forwarding(
818		    options.remote_forwards[i].listen_host,
819		    options.remote_forwards[i].listen_port,
820		    options.remote_forwards[i].connect_host,
821		    options.remote_forwards[i].connect_port);
822	}
823}
824
825static void
826check_agent_present(void)
827{
828	if (options.forward_agent) {
829		/* Clear agent forwarding if we don\'t have an agent. */
830		if (!ssh_agent_present())
831			options.forward_agent = 0;
832	}
833}
834
835static int
836ssh_session(void)
837{
838	int type;
839	int interactive = 0;
840	int have_tty = 0;
841	struct winsize ws;
842	char *cp;
843	const char *display;
844
845	/* Enable compression if requested. */
846	if (options.compression) {
847		debug("Requesting compression at level %d.", options.compression_level);
848
849		if (options.compression_level < 1 || options.compression_level > 9)
850			fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
851
852		/* Send the request. */
853		packet_start(SSH_CMSG_REQUEST_COMPRESSION);
854		packet_put_int(options.compression_level);
855		packet_send();
856		packet_write_wait();
857		type = packet_read();
858		if (type == SSH_SMSG_SUCCESS)
859			packet_start_compression(options.compression_level);
860		else if (type == SSH_SMSG_FAILURE)
861			logit("Warning: Remote host refused compression.");
862		else
863			packet_disconnect("Protocol error waiting for compression response.");
864	}
865	/* Allocate a pseudo tty if appropriate. */
866	if (tty_flag) {
867		debug("Requesting pty.");
868
869		/* Start the packet. */
870		packet_start(SSH_CMSG_REQUEST_PTY);
871
872		/* Store TERM in the packet.  There is no limit on the
873		   length of the string. */
874		cp = getenv("TERM");
875		if (!cp)
876			cp = "";
877		packet_put_cstring(cp);
878
879		/* Store window size in the packet. */
880		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
881			memset(&ws, 0, sizeof(ws));
882		packet_put_int(ws.ws_row);
883		packet_put_int(ws.ws_col);
884		packet_put_int(ws.ws_xpixel);
885		packet_put_int(ws.ws_ypixel);
886
887		/* Store tty modes in the packet. */
888		tty_make_modes(fileno(stdin), NULL);
889
890		/* Send the packet, and wait for it to leave. */
891		packet_send();
892		packet_write_wait();
893
894		/* Read response from the server. */
895		type = packet_read();
896		if (type == SSH_SMSG_SUCCESS) {
897			interactive = 1;
898			have_tty = 1;
899		} else if (type == SSH_SMSG_FAILURE)
900			logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
901		else
902			packet_disconnect("Protocol error waiting for pty request response.");
903	}
904	/* Request X11 forwarding if enabled and DISPLAY is set. */
905	display = getenv("DISPLAY");
906	if (options.forward_x11 && display != NULL) {
907		char *proto, *data;
908		/* Get reasonable local authentication information. */
909		client_x11_get_proto(display, options.xauth_location,
910		    options.forward_x11_trusted, &proto, &data);
911		/* Request forwarding with authentication spoofing. */
912		debug("Requesting X11 forwarding with authentication spoofing.");
913		x11_request_forwarding_with_spoofing(0, display, proto, data);
914
915		/* Read response from the server. */
916		type = packet_read();
917		if (type == SSH_SMSG_SUCCESS) {
918			interactive = 1;
919		} else if (type == SSH_SMSG_FAILURE) {
920			logit("Warning: Remote host denied X11 forwarding.");
921		} else {
922			packet_disconnect("Protocol error waiting for X11 forwarding");
923		}
924	}
925	/* Tell the packet module whether this is an interactive session. */
926	packet_set_interactive(interactive);
927
928	/* Request authentication agent forwarding if appropriate. */
929	check_agent_present();
930
931	if (options.forward_agent) {
932		debug("Requesting authentication agent forwarding.");
933		auth_request_forwarding();
934
935		/* Read response from the server. */
936		type = packet_read();
937		packet_check_eom();
938		if (type != SSH_SMSG_SUCCESS)
939			logit("Warning: Remote host denied authentication agent forwarding.");
940	}
941
942	/* Initiate port forwardings. */
943	ssh_init_forwarding();
944
945	/* If requested, let ssh continue in the background. */
946	if (fork_after_authentication_flag)
947		if (daemon(1, 1) < 0)
948			fatal("daemon() failed: %.200s", strerror(errno));
949
950	/*
951	 * If a command was specified on the command line, execute the
952	 * command now. Otherwise request the server to start a shell.
953	 */
954	if (buffer_len(&command) > 0) {
955		int len = buffer_len(&command);
956		if (len > 900)
957			len = 900;
958		debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
959		packet_start(SSH_CMSG_EXEC_CMD);
960		packet_put_string(buffer_ptr(&command), buffer_len(&command));
961		packet_send();
962		packet_write_wait();
963	} else {
964		debug("Requesting shell.");
965		packet_start(SSH_CMSG_EXEC_SHELL);
966		packet_send();
967		packet_write_wait();
968	}
969
970	/* Enter the interactive session. */
971	return client_loop(have_tty, tty_flag ?
972	    options.escape_char : SSH_ESCAPECHAR_NONE, 0);
973}
974
975static void
976ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
977{
978	int id, len;
979
980	id = packet_get_int();
981	len = buffer_len(&command);
982	if (len > 900)
983		len = 900;
984	packet_check_eom();
985	if (type == SSH2_MSG_CHANNEL_FAILURE)
986		fatal("Request for subsystem '%.*s' failed on channel %d",
987		    len, (u_char *)buffer_ptr(&command), id);
988}
989
990void
991client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
992{
993	int i;
994
995	i = client_global_request_id++;
996	if (i >= options.num_remote_forwards)
997		return;
998	debug("remote forward %s for: listen %d, connect %s:%d",
999	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1000	    options.remote_forwards[i].listen_port,
1001	    options.remote_forwards[i].connect_host,
1002	    options.remote_forwards[i].connect_port);
1003	if (type == SSH2_MSG_REQUEST_FAILURE)
1004		logit("Warning: remote port forwarding failed for listen "
1005		    "port %d", options.remote_forwards[i].listen_port);
1006}
1007
1008static void
1009ssh_control_listener(void)
1010{
1011	struct sockaddr_un addr;
1012	mode_t old_umask;
1013	int addr_len;
1014
1015	if (options.control_path == NULL ||
1016	    options.control_master == SSHCTL_MASTER_NO)
1017		return;
1018
1019	debug("setting up multiplex master socket");
1020
1021	memset(&addr, '\0', sizeof(addr));
1022	addr.sun_family = AF_UNIX;
1023	addr_len = offsetof(struct sockaddr_un, sun_path) +
1024	    strlen(options.control_path) + 1;
1025
1026	if (strlcpy(addr.sun_path, options.control_path,
1027	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1028		fatal("ControlPath too long");
1029
1030	if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1031		fatal("%s socket(): %s\n", __func__, strerror(errno));
1032
1033	old_umask = umask(0177);
1034	if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1035		control_fd = -1;
1036		if (errno == EINVAL || errno == EADDRINUSE)
1037			fatal("ControlSocket %s already exists",
1038			    options.control_path);
1039		else
1040			fatal("%s bind(): %s\n", __func__, strerror(errno));
1041	}
1042	umask(old_umask);
1043
1044	if (listen(control_fd, 64) == -1)
1045		fatal("%s listen(): %s\n", __func__, strerror(errno));
1046
1047	set_nonblock(control_fd);
1048}
1049
1050/* request pty/x11/agent/tcpfwd/shell for channel */
1051static void
1052ssh_session2_setup(int id, void *arg)
1053{
1054	extern char **environ;
1055	const char *display;
1056	int interactive = tty_flag;
1057
1058	display = getenv("DISPLAY");
1059	if (options.forward_x11 && display != NULL) {
1060		char *proto, *data;
1061		/* Get reasonable local authentication information. */
1062		client_x11_get_proto(display, options.xauth_location,
1063		    options.forward_x11_trusted, &proto, &data);
1064		/* Request forwarding with authentication spoofing. */
1065		debug("Requesting X11 forwarding with authentication spoofing.");
1066		x11_request_forwarding_with_spoofing(id, display, proto, data);
1067		interactive = 1;
1068		/* XXX wait for reply */
1069	}
1070
1071	check_agent_present();
1072	if (options.forward_agent) {
1073		debug("Requesting authentication agent forwarding.");
1074		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1075		packet_send();
1076	}
1077
1078	client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1079	    NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1080
1081	packet_set_interactive(interactive);
1082}
1083
1084/* open new channel for a session */
1085static int
1086ssh_session2_open(void)
1087{
1088	Channel *c;
1089	int window, packetmax, in, out, err;
1090
1091	if (stdin_null_flag) {
1092		in = open(_PATH_DEVNULL, O_RDONLY);
1093	} else {
1094		in = dup(STDIN_FILENO);
1095	}
1096	out = dup(STDOUT_FILENO);
1097	err = dup(STDERR_FILENO);
1098
1099	if (in < 0 || out < 0 || err < 0)
1100		fatal("dup() in/out/err failed");
1101
1102	/* enable nonblocking unless tty */
1103	if (!isatty(in))
1104		set_nonblock(in);
1105	if (!isatty(out))
1106		set_nonblock(out);
1107	if (!isatty(err))
1108		set_nonblock(err);
1109
1110	window = CHAN_SES_WINDOW_DEFAULT;
1111	packetmax = CHAN_SES_PACKET_DEFAULT;
1112	if (tty_flag) {
1113		window >>= 1;
1114		packetmax >>= 1;
1115	}
1116	c = channel_new(
1117	    "session", SSH_CHANNEL_OPENING, in, out, err,
1118	    window, packetmax, CHAN_EXTENDED_WRITE,
1119	    "client-session", /*nonblock*/0);
1120
1121	debug3("ssh_session2_open: channel_new: %d", c->self);
1122
1123	channel_send_open(c->self);
1124	if (!no_shell_flag)
1125		channel_register_confirm(c->self, ssh_session2_setup, NULL);
1126
1127	return c->self;
1128}
1129
1130static int
1131ssh_session2(void)
1132{
1133	int id = -1;
1134
1135	/* XXX should be pre-session */
1136	ssh_init_forwarding();
1137	ssh_control_listener();
1138
1139	if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1140		id = ssh_session2_open();
1141
1142	/* If requested, let ssh continue in the background. */
1143	if (fork_after_authentication_flag)
1144		if (daemon(1, 1) < 0)
1145			fatal("daemon() failed: %.200s", strerror(errno));
1146
1147	return client_loop(tty_flag, tty_flag ?
1148	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1149}
1150
1151static void
1152load_public_identity_files(void)
1153{
1154	char *filename;
1155	int i = 0;
1156	Key *public;
1157#ifdef SMARTCARD
1158	Key **keys;
1159
1160	if (options.smartcard_device != NULL &&
1161	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1162	    (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1163		int count = 0;
1164		for (i = 0; keys[i] != NULL; i++) {
1165			count++;
1166			memmove(&options.identity_files[1], &options.identity_files[0],
1167			    sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1168			memmove(&options.identity_keys[1], &options.identity_keys[0],
1169			    sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1170			options.num_identity_files++;
1171			options.identity_keys[0] = keys[i];
1172			options.identity_files[0] = sc_get_key_label(keys[i]);
1173		}
1174		if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1175			options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1176		i = count;
1177		xfree(keys);
1178	}
1179#endif /* SMARTCARD */
1180	for (; i < options.num_identity_files; i++) {
1181		filename = tilde_expand_filename(options.identity_files[i],
1182		    original_real_uid);
1183		public = key_load_public(filename, NULL);
1184		debug("identity file %s type %d", filename,
1185		    public ? public->type : -1);
1186		xfree(options.identity_files[i]);
1187		options.identity_files[i] = filename;
1188		options.identity_keys[i] = public;
1189	}
1190}
1191
1192static void
1193control_client_sighandler(int signo)
1194{
1195	control_client_terminate = signo;
1196}
1197
1198static void
1199control_client_sigrelay(int signo)
1200{
1201	if (control_server_pid > 1)
1202		kill(control_server_pid, signo);
1203}
1204
1205static int
1206env_permitted(char *env)
1207{
1208	int i;
1209	char name[1024], *cp;
1210
1211	strlcpy(name, env, sizeof(name));
1212	if ((cp = strchr(name, '=')) == NULL)
1213		return (0);
1214
1215	*cp = '\0';
1216
1217	for (i = 0; i < options.num_send_env; i++)
1218		if (match_pattern(name, options.send_env[i]))
1219			return (1);
1220
1221	return (0);
1222}
1223
1224static void
1225control_client(const char *path)
1226{
1227	struct sockaddr_un addr;
1228	int i, r, fd, sock, exitval, num_env, addr_len;
1229	Buffer m;
1230	char *term;
1231	extern char **environ;
1232	u_int  flags;
1233
1234	if (mux_command == 0)
1235		mux_command = SSHMUX_COMMAND_OPEN;
1236
1237	switch (options.control_master) {
1238	case SSHCTL_MASTER_AUTO:
1239	case SSHCTL_MASTER_AUTO_ASK:
1240		debug("auto-mux: Trying existing master");
1241		/* FALLTHROUGH */
1242	case SSHCTL_MASTER_NO:
1243		break;
1244	default:
1245		return;
1246	}
1247
1248	memset(&addr, '\0', sizeof(addr));
1249	addr.sun_family = AF_UNIX;
1250	addr_len = offsetof(struct sockaddr_un, sun_path) +
1251	    strlen(path) + 1;
1252
1253	if (strlcpy(addr.sun_path, path,
1254	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1255		fatal("ControlPath too long");
1256
1257	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1258		fatal("%s socket(): %s", __func__, strerror(errno));
1259
1260	if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1261		if (mux_command != SSHMUX_COMMAND_OPEN) {
1262			fatal("Control socket connect(%.100s): %s", path,
1263			    strerror(errno));
1264		}
1265		if (errno == ENOENT)
1266	 		debug("Control socket \"%.100s\" does not exist", path);
1267		else {
1268	 		error("Control socket connect(%.100s): %s", path,
1269			    strerror(errno));
1270		}
1271 		close(sock);
1272 		return;
1273 	}
1274
1275 	if (stdin_null_flag) {
1276 		if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1277 			fatal("open(/dev/null): %s", strerror(errno));
1278 		if (dup2(fd, STDIN_FILENO) == -1)
1279 			fatal("dup2: %s", strerror(errno));
1280 		if (fd > STDERR_FILENO)
1281 			close(fd);
1282 	}
1283
1284	term = getenv("TERM");
1285
1286	flags = 0;
1287	if (tty_flag)
1288		flags |= SSHMUX_FLAG_TTY;
1289	if (subsystem_flag)
1290		flags |= SSHMUX_FLAG_SUBSYS;
1291	if (options.forward_x11)
1292		flags |= SSHMUX_FLAG_X11_FWD;
1293	if (options.forward_agent)
1294		flags |= SSHMUX_FLAG_AGENT_FWD;
1295
1296	buffer_init(&m);
1297
1298	/* Send our command to server */
1299	buffer_put_int(&m, mux_command);
1300	buffer_put_int(&m, flags);
1301	if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1302		fatal("%s: msg_send", __func__);
1303	buffer_clear(&m);
1304
1305	/* Get authorisation status and PID of controlee */
1306	if (ssh_msg_recv(sock, &m) == -1)
1307		fatal("%s: msg_recv", __func__);
1308	if (buffer_get_char(&m) != SSHMUX_VER)
1309		fatal("%s: wrong version", __func__);
1310	if (buffer_get_int(&m) != 1)
1311		fatal("Connection to master denied");
1312	control_server_pid = buffer_get_int(&m);
1313
1314	buffer_clear(&m);
1315
1316	switch (mux_command) {
1317	case SSHMUX_COMMAND_ALIVE_CHECK:
1318		fprintf(stderr, "Master running (pid=%d)\r\n",
1319		    control_server_pid);
1320		exit(0);
1321	case SSHMUX_COMMAND_TERMINATE:
1322		fprintf(stderr, "Exit request sent.\r\n");
1323		exit(0);
1324	case SSHMUX_COMMAND_OPEN:
1325		/* continue below */
1326		break;
1327	default:
1328		fatal("silly mux_command %d", mux_command);
1329	}
1330
1331	/* SSHMUX_COMMAND_OPEN */
1332	buffer_put_cstring(&m, term ? term : "");
1333	buffer_append(&command, "\0", 1);
1334	buffer_put_cstring(&m, buffer_ptr(&command));
1335
1336	if (options.num_send_env == 0 || environ == NULL) {
1337		buffer_put_int(&m, 0);
1338	} else {
1339		/* Pass environment */
1340		num_env = 0;
1341		for (i = 0; environ[i] != NULL; i++)
1342			if (env_permitted(environ[i]))
1343				num_env++; /* Count */
1344
1345		buffer_put_int(&m, num_env);
1346
1347		for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1348			if (env_permitted(environ[i])) {
1349				num_env--;
1350				buffer_put_cstring(&m, environ[i]);
1351			}
1352	}
1353
1354	if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1355		fatal("%s: msg_send", __func__);
1356
1357	mm_send_fd(sock, STDIN_FILENO);
1358	mm_send_fd(sock, STDOUT_FILENO);
1359	mm_send_fd(sock, STDERR_FILENO);
1360
1361	/* Wait for reply, so master has a chance to gather ttymodes */
1362	buffer_clear(&m);
1363	if (ssh_msg_recv(sock, &m) == -1)
1364		fatal("%s: msg_recv", __func__);
1365	if (buffer_get_char(&m) != SSHMUX_VER)
1366		fatal("%s: wrong version", __func__);
1367	buffer_free(&m);
1368
1369	signal(SIGHUP, control_client_sighandler);
1370	signal(SIGINT, control_client_sighandler);
1371	signal(SIGTERM, control_client_sighandler);
1372	signal(SIGWINCH, control_client_sigrelay);
1373
1374	if (tty_flag)
1375		enter_raw_mode();
1376
1377	/* Stick around until the controlee closes the client_fd */
1378	exitval = 0;
1379	for (;!control_client_terminate;) {
1380		r = read(sock, &exitval, sizeof(exitval));
1381		if (r == 0) {
1382			debug2("Received EOF from master");
1383			break;
1384		}
1385		if (r > 0)
1386			debug2("Received exit status from master %d", exitval);
1387		if (r == -1 && errno != EINTR)
1388			fatal("%s: read %s", __func__, strerror(errno));
1389	}
1390
1391	if (control_client_terminate)
1392		debug2("Exiting on signal %d", control_client_terminate);
1393
1394	close(sock);
1395
1396	leave_raw_mode();
1397
1398	if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1399		fprintf(stderr, "Connection to master closed.\r\n");
1400
1401	exit(exitval);
1402}
1403