xref: /dragonfly/crypto/openssh/ssh.c (revision 984263bc)
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"
43 RCSID("$OpenBSD: ssh.c,v 1.186 2002/09/19 01:58:18 djm Exp $");
44 RCSID("$FreeBSD: src/crypto/openssh/ssh.c,v 1.4.2.7 2003/02/03 17:31:07 des Exp $");
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
78 extern char *__progname;
79 #else
80 char *__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
86 int IPv4or6 = AF_INET;
87 #else
88 int IPv4or6 = AF_UNSPEC;
89 #endif
90 
91 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
92 int debug_flag = 0;
93 
94 /* Flag indicating whether a tty should be allocated */
95 int tty_flag = 0;
96 int no_tty_flag = 0;
97 int force_tty_flag = 0;
98 
99 /* don't exec a shell */
100 int 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  */
106 int 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  */
113 int 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  */
119 Options options;
120 
121 /* optional user configfile */
122 char *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  */
129 char *host;
130 
131 /* socket address the host resolves to */
132 struct sockaddr_storage hostaddr;
133 
134 /* Private host keys. */
135 Sensitive sensitive_data;
136 
137 /* Original real UID. */
138 uid_t original_real_uid;
139 uid_t original_effective_uid;
140 
141 /* command to be executed */
142 Buffer command;
143 
144 /* Should we execute a command or invoke a subsystem? */
145 int subsystem_flag = 0;
146 
147 /* # of replies received for global requests */
148 static int client_global_request_id = 0;
149 
150 /* pid of proxycommand child process */
151 pid_t proxy_command_pid = 0;
152 
153 /* Prints a help message to the user.  This function never returns. */
154 
155 static void
156 usage(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 
206 static int ssh_session(void);
207 static int ssh_session2(void);
208 static void load_public_identity_files(void);
209 
210 /*
211  * Main program for the ssh client.
212  */
213 int
214 main(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 
277 again:
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 (strchr(*av, '@')) {
500 			p = xstrdup(*av);
501 			cp = strchr(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 		ac--, av++;
510 		if (ac > 0) {
511 			optind = 0;
512 			optreset = 1;
513 			goto again;
514 		}
515 	}
516 
517 	/* Check that we got a host name. */
518 	if (!host)
519 		usage();
520 
521 	SSLeay_add_all_algorithms();
522 	ERR_load_crypto_strings();
523 	channel_set_af(IPv4or6);
524 
525 	/* Initialize the command to execute on remote host. */
526 	buffer_init(&command);
527 
528 	/*
529 	 * Save the command to execute on the remote host in a buffer. There
530 	 * is no limit on the length of the command, except by the maximum
531 	 * packet size.  Also sets the tty flag if there is no command.
532 	 */
533 	if (!ac) {
534 		/* No command specified - execute shell on a tty. */
535 		tty_flag = 1;
536 		if (subsystem_flag) {
537 			fprintf(stderr,
538 			    "You must specify a subsystem to invoke.\n");
539 			usage();
540 		}
541 	} else {
542 		/* A command has been specified.  Store it into the buffer. */
543 		for (i = 0; i < ac; i++) {
544 			if (i)
545 				buffer_append(&command, " ", 1);
546 			buffer_append(&command, av[i], strlen(av[i]));
547 		}
548 	}
549 
550 	/* Cannot fork to background if no command. */
551 	if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
552 		fatal("Cannot fork into background without a command to execute.");
553 
554 	/* Allocate a tty by default if no command specified. */
555 	if (buffer_len(&command) == 0)
556 		tty_flag = 1;
557 
558 	/* Force no tty */
559 	if (no_tty_flag)
560 		tty_flag = 0;
561 	/* Do not allocate a tty if stdin is not a tty. */
562 	if (!isatty(fileno(stdin)) && !force_tty_flag) {
563 		if (tty_flag)
564 			log("Pseudo-terminal will not be allocated because stdin is not a terminal.");
565 		tty_flag = 0;
566 	}
567 
568 	/*
569 	 * Initialize "log" output.  Since we are the client all output
570 	 * actually goes to stderr.
571 	 */
572 	log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
573 	    SYSLOG_FACILITY_USER, 1);
574 
575 	/*
576 	 * Read per-user configuration file.  Ignore the system wide config
577 	 * file if the user specifies a config file on the command line.
578 	 */
579 	if (config != NULL) {
580 		if (!read_config_file(config, host, &options))
581 			fatal("Can't open user config file %.100s: "
582 			    "%.100s", config, strerror(errno));
583 	} else  {
584 		snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
585 		    _PATH_SSH_USER_CONFFILE);
586 		(void)read_config_file(buf, host, &options);
587 
588 		/* Read systemwide configuration file after use config. */
589 		(void)read_config_file(_PATH_HOST_CONFIG_FILE, host, &options);
590 	}
591 
592 	/* Fill configuration defaults. */
593 	fill_default_options(&options);
594 
595 	/* reinit */
596 	log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
597 
598 	seed_rng();
599 
600 	if (options.user == NULL)
601 		options.user = xstrdup(pw->pw_name);
602 
603 	if (options.hostname != NULL)
604 		host = options.hostname;
605 
606 	/* Find canonic host name. */
607 	if (strchr(host, '.') == 0) {
608 		struct addrinfo hints;
609 		struct addrinfo *ai = NULL;
610 		int errgai;
611 		memset(&hints, 0, sizeof(hints));
612 		hints.ai_family = IPv4or6;
613 		hints.ai_flags = AI_CANONNAME;
614 		hints.ai_socktype = SOCK_STREAM;
615 		errgai = getaddrinfo(host, NULL, &hints, &ai);
616 		if (errgai == 0) {
617 			if (ai->ai_canonname != NULL)
618 				host = xstrdup(ai->ai_canonname);
619 			freeaddrinfo(ai);
620 		}
621 	}
622 
623 	/* Disable rhosts authentication if not running as root. */
624 #ifdef HAVE_CYGWIN
625 	/* Ignore uid if running under Windows */
626 	if (!options.use_privileged_port) {
627 #else
628 	if (original_effective_uid != 0 || !options.use_privileged_port) {
629 #endif
630 		debug("Rhosts Authentication disabled, "
631 		    "originating port will not be trusted.");
632 		options.rhosts_authentication = 0;
633 	}
634 	/* Open a connection to the remote host. */
635 
636 	if (ssh_connect(host, &hostaddr, options.port, IPv4or6,
637 	    options.connection_attempts,
638 #ifdef HAVE_CYGWIN
639 	    options.use_privileged_port,
640 #else
641 	    original_effective_uid == 0 && options.use_privileged_port,
642 #endif
643 	    options.proxy_command) != 0)
644 		exit(1);
645 
646 	/*
647 	 * If we successfully made the connection, load the host private key
648 	 * in case we will need it later for combined rsa-rhosts
649 	 * authentication. This must be done before releasing extra
650 	 * privileges, because the file is only readable by root.
651 	 * If we cannot access the private keys, load the public keys
652 	 * instead and try to execute the ssh-keysign helper instead.
653 	 */
654 	sensitive_data.nkeys = 0;
655 	sensitive_data.keys = NULL;
656 	sensitive_data.external_keysign = 0;
657 	if (options.rhosts_rsa_authentication ||
658 	    options.hostbased_authentication) {
659 		sensitive_data.nkeys = 3;
660 		sensitive_data.keys = xmalloc(sensitive_data.nkeys *
661 		    sizeof(Key));
662 
663 		PRIV_START;
664 		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
665 		    _PATH_HOST_KEY_FILE, "", NULL);
666 		sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
667 		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
668 		sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
669 		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
670 		PRIV_END;
671 
672 		if (options.hostbased_authentication == 1 &&
673 		    sensitive_data.keys[0] == NULL &&
674 		    sensitive_data.keys[1] == NULL &&
675 		    sensitive_data.keys[2] == NULL) {
676 			sensitive_data.keys[1] = key_load_public(
677 			    _PATH_HOST_DSA_KEY_FILE, NULL);
678 			sensitive_data.keys[2] = key_load_public(
679 			    _PATH_HOST_RSA_KEY_FILE, NULL);
680 			sensitive_data.external_keysign = 1;
681 		}
682 	}
683 	/*
684 	 * Get rid of any extra privileges that we may have.  We will no
685 	 * longer need them.  Also, extra privileges could make it very hard
686 	 * to read identity files and other non-world-readable files from the
687 	 * user's home directory if it happens to be on a NFS volume where
688 	 * root is mapped to nobody.
689 	 */
690 	seteuid(original_real_uid);
691 	setuid(original_real_uid);
692 
693 	/*
694 	 * Now that we are back to our own permissions, create ~/.ssh
695 	 * directory if it doesn\'t already exist.
696 	 */
697 	snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
698 	if (stat(buf, &st) < 0)
699 		if (mkdir(buf, 0700) < 0)
700 			error("Could not create directory '%.200s'.", buf);
701 
702 	/* load options.identity_files */
703 	load_public_identity_files();
704 
705 	/* Expand ~ in known host file names. */
706 	/* XXX mem-leaks: */
707 	options.system_hostfile =
708 	    tilde_expand_filename(options.system_hostfile, original_real_uid);
709 	options.user_hostfile =
710 	    tilde_expand_filename(options.user_hostfile, original_real_uid);
711 	options.system_hostfile2 =
712 	    tilde_expand_filename(options.system_hostfile2, original_real_uid);
713 	options.user_hostfile2 =
714 	    tilde_expand_filename(options.user_hostfile2, original_real_uid);
715 
716 	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
717 
718 	/* Log into the remote system.  This never returns if the login fails. */
719 	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
720 
721 	/* We no longer need the private host keys.  Clear them now. */
722 	if (sensitive_data.nkeys != 0) {
723 		for (i = 0; i < sensitive_data.nkeys; i++) {
724 			if (sensitive_data.keys[i] != NULL) {
725 				/* Destroys contents safely */
726 				debug3("clear hostkey %d", i);
727 				key_free(sensitive_data.keys[i]);
728 				sensitive_data.keys[i] = NULL;
729 			}
730 		}
731 		xfree(sensitive_data.keys);
732 	}
733 	for (i = 0; i < options.num_identity_files; i++) {
734 		if (options.identity_files[i]) {
735 			xfree(options.identity_files[i]);
736 			options.identity_files[i] = NULL;
737 		}
738 		if (options.identity_keys[i]) {
739 			key_free(options.identity_keys[i]);
740 			options.identity_keys[i] = NULL;
741 		}
742 	}
743 
744 	exit_status = compat20 ? ssh_session2() : ssh_session();
745 	packet_close();
746 
747 	/*
748 	 * Send SIGHUP to proxy command if used. We don't wait() in
749 	 * case it hangs and instead rely on init to reap the child
750 	 */
751 	if (proxy_command_pid > 1)
752 		kill(proxy_command_pid, SIGHUP);
753 
754 	return exit_status;
755 }
756 
757 static void
758 x11_get_proto(char **_proto, char **_data)
759 {
760 	char line[512];
761 	static char proto[512], data[512];
762 	FILE *f;
763 	int got_data = 0, i;
764 	char *display;
765 	struct stat st;
766 
767 	*_proto = proto;
768 	*_data = data;
769 	proto[0] = data[0] = '\0';
770 	if (!options.xauth_location ||
771 	    (stat(options.xauth_location, &st) == -1)) {
772 		debug("No xauth program.");
773 	} else {
774 		if ((display = getenv("DISPLAY")) == NULL) {
775 			debug("x11_get_proto: DISPLAY not set");
776 			return;
777 		}
778 		/* Try to get Xauthority information for the display. */
779 		if (strncmp(display, "localhost:", 10) == 0)
780 			/*
781 			 * Handle FamilyLocal case where $DISPLAY does
782 			 * not match an authorization entry.  For this we
783 			 * just try "xauth list unix:displaynum.screennum".
784 			 * XXX: "localhost" match to determine FamilyLocal
785 			 *      is not perfect.
786 			 */
787 			snprintf(line, sizeof line, "%s list unix:%s 2>"
788 			    _PATH_DEVNULL, options.xauth_location, display+10);
789 		else
790 			snprintf(line, sizeof line, "%s list %.200s 2>"
791 			    _PATH_DEVNULL, options.xauth_location, display);
792 		debug2("x11_get_proto: %s", line);
793 		f = popen(line, "r");
794 		if (f && fgets(line, sizeof(line), f) &&
795 		    sscanf(line, "%*s %511s %511s", proto, data) == 2)
796 			got_data = 1;
797 		if (f)
798 			pclose(f);
799 	}
800 	/*
801 	 * If we didn't get authentication data, just make up some
802 	 * data.  The forwarding code will check the validity of the
803 	 * response anyway, and substitute this data.  The X11
804 	 * server, however, will ignore this fake data and use
805 	 * whatever authentication mechanisms it was using otherwise
806 	 * for the local connection.
807 	 */
808 	if (!got_data) {
809 		u_int32_t rand = 0;
810 
811 		log("Warning: No xauth data; using fake authentication data for X11 forwarding.");
812 		strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
813 		for (i = 0; i < 16; i++) {
814 			if (i % 4 == 0)
815 				rand = arc4random();
816 			snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
817 			rand >>= 8;
818 		}
819 	}
820 }
821 
822 static void
823 ssh_init_forwarding(void)
824 {
825 	int success = 0;
826 	int i;
827 
828 	/* Initiate local TCP/IP port forwardings. */
829 	for (i = 0; i < options.num_local_forwards; i++) {
830 		debug("Connections to local port %d forwarded to remote address %.200s:%d",
831 		    options.local_forwards[i].port,
832 		    options.local_forwards[i].host,
833 		    options.local_forwards[i].host_port);
834 		success += channel_setup_local_fwd_listener(
835 		    options.local_forwards[i].port,
836 		    options.local_forwards[i].host,
837 		    options.local_forwards[i].host_port,
838 		    options.gateway_ports);
839 	}
840 	if (i > 0 && success == 0)
841 		error("Could not request local forwarding.");
842 
843 	/* Initiate remote TCP/IP port forwardings. */
844 	for (i = 0; i < options.num_remote_forwards; i++) {
845 		debug("Connections to remote port %d forwarded to local address %.200s:%d",
846 		    options.remote_forwards[i].port,
847 		    options.remote_forwards[i].host,
848 		    options.remote_forwards[i].host_port);
849 		channel_request_remote_forwarding(
850 		    options.remote_forwards[i].port,
851 		    options.remote_forwards[i].host,
852 		    options.remote_forwards[i].host_port);
853 	}
854 }
855 
856 static void
857 check_agent_present(void)
858 {
859 	if (options.forward_agent) {
860 		/* Clear agent forwarding if we don\'t have an agent. */
861 		if (!ssh_agent_present())
862 			options.forward_agent = 0;
863 	}
864 }
865 
866 static int
867 ssh_session(void)
868 {
869 	int type;
870 	int interactive = 0;
871 	int have_tty = 0;
872 	struct winsize ws;
873 	char *cp;
874 
875 	/* Enable compression if requested. */
876 	if (options.compression) {
877 		debug("Requesting compression at level %d.", options.compression_level);
878 
879 		if (options.compression_level < 1 || options.compression_level > 9)
880 			fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
881 
882 		/* Send the request. */
883 		packet_start(SSH_CMSG_REQUEST_COMPRESSION);
884 		packet_put_int(options.compression_level);
885 		packet_send();
886 		packet_write_wait();
887 		type = packet_read();
888 		if (type == SSH_SMSG_SUCCESS)
889 			packet_start_compression(options.compression_level);
890 		else if (type == SSH_SMSG_FAILURE)
891 			log("Warning: Remote host refused compression.");
892 		else
893 			packet_disconnect("Protocol error waiting for compression response.");
894 	}
895 	/* Allocate a pseudo tty if appropriate. */
896 	if (tty_flag) {
897 		debug("Requesting pty.");
898 
899 		/* Start the packet. */
900 		packet_start(SSH_CMSG_REQUEST_PTY);
901 
902 		/* Store TERM in the packet.  There is no limit on the
903 		   length of the string. */
904 		cp = getenv("TERM");
905 		if (!cp)
906 			cp = "";
907 		packet_put_cstring(cp);
908 
909 		/* Store window size in the packet. */
910 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
911 			memset(&ws, 0, sizeof(ws));
912 		packet_put_int(ws.ws_row);
913 		packet_put_int(ws.ws_col);
914 		packet_put_int(ws.ws_xpixel);
915 		packet_put_int(ws.ws_ypixel);
916 
917 		/* Store tty modes in the packet. */
918 		tty_make_modes(fileno(stdin), NULL);
919 
920 		/* Send the packet, and wait for it to leave. */
921 		packet_send();
922 		packet_write_wait();
923 
924 		/* Read response from the server. */
925 		type = packet_read();
926 		if (type == SSH_SMSG_SUCCESS) {
927 			interactive = 1;
928 			have_tty = 1;
929 		} else if (type == SSH_SMSG_FAILURE)
930 			log("Warning: Remote host failed or refused to allocate a pseudo tty.");
931 		else
932 			packet_disconnect("Protocol error waiting for pty request response.");
933 	}
934 	/* Request X11 forwarding if enabled and DISPLAY is set. */
935 	if (options.forward_x11 && getenv("DISPLAY") != NULL) {
936 		char *proto, *data;
937 		/* Get reasonable local authentication information. */
938 		x11_get_proto(&proto, &data);
939 		/* Request forwarding with authentication spoofing. */
940 		debug("Requesting X11 forwarding with authentication spoofing.");
941 		x11_request_forwarding_with_spoofing(0, proto, data);
942 
943 		/* Read response from the server. */
944 		type = packet_read();
945 		if (type == SSH_SMSG_SUCCESS) {
946 			interactive = 1;
947 		} else if (type == SSH_SMSG_FAILURE) {
948 			log("Warning: Remote host denied X11 forwarding.");
949 		} else {
950 			packet_disconnect("Protocol error waiting for X11 forwarding");
951 		}
952 	}
953 	/* Tell the packet module whether this is an interactive session. */
954 	packet_set_interactive(interactive);
955 
956 	/* Request authentication agent forwarding if appropriate. */
957 	check_agent_present();
958 
959 	if (options.forward_agent) {
960 		debug("Requesting authentication agent forwarding.");
961 		auth_request_forwarding();
962 
963 		/* Read response from the server. */
964 		type = packet_read();
965 		packet_check_eom();
966 		if (type != SSH_SMSG_SUCCESS)
967 			log("Warning: Remote host denied authentication agent forwarding.");
968 	}
969 
970 	/* Initiate port forwardings. */
971 	ssh_init_forwarding();
972 
973 	/* If requested, let ssh continue in the background. */
974 	if (fork_after_authentication_flag)
975 		if (daemon(1, 1) < 0)
976 			fatal("daemon() failed: %.200s", strerror(errno));
977 
978 	/*
979 	 * If a command was specified on the command line, execute the
980 	 * command now. Otherwise request the server to start a shell.
981 	 */
982 	if (buffer_len(&command) > 0) {
983 		int len = buffer_len(&command);
984 		if (len > 900)
985 			len = 900;
986 		debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
987 		packet_start(SSH_CMSG_EXEC_CMD);
988 		packet_put_string(buffer_ptr(&command), buffer_len(&command));
989 		packet_send();
990 		packet_write_wait();
991 	} else {
992 		debug("Requesting shell.");
993 		packet_start(SSH_CMSG_EXEC_SHELL);
994 		packet_send();
995 		packet_write_wait();
996 	}
997 
998 	/* Enter the interactive session. */
999 	return client_loop(have_tty, tty_flag ?
1000 	    options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1001 }
1002 
1003 static void
1004 client_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1005 {
1006 	int id, len;
1007 
1008 	id = packet_get_int();
1009 	len = buffer_len(&command);
1010 	if (len > 900)
1011 		len = 900;
1012 	packet_check_eom();
1013 	if (type == SSH2_MSG_CHANNEL_FAILURE)
1014 		fatal("Request for subsystem '%.*s' failed on channel %d",
1015 		    len, (u_char *)buffer_ptr(&command), id);
1016 }
1017 
1018 void
1019 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
1020 {
1021 	int i;
1022 
1023 	i = client_global_request_id++;
1024 	if (i >= options.num_remote_forwards) {
1025 		debug("client_global_request_reply: too many replies %d > %d",
1026 		    i, options.num_remote_forwards);
1027 		return;
1028 	}
1029 	debug("remote forward %s for: listen %d, connect %s:%d",
1030 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1031 	    options.remote_forwards[i].port,
1032 	    options.remote_forwards[i].host,
1033 	    options.remote_forwards[i].host_port);
1034 	if (type == SSH2_MSG_REQUEST_FAILURE)
1035 		log("Warning: remote port forwarding failed for listen port %d",
1036 		    options.remote_forwards[i].port);
1037 }
1038 
1039 /* request pty/x11/agent/tcpfwd/shell for channel */
1040 static void
1041 ssh_session2_setup(int id, void *arg)
1042 {
1043 	int len;
1044 	int interactive = 0;
1045 	struct termios tio;
1046 
1047 	debug("ssh_session2_setup: id %d", id);
1048 
1049 	if (tty_flag) {
1050 		struct winsize ws;
1051 		char *cp;
1052 		cp = getenv("TERM");
1053 		if (!cp)
1054 			cp = "";
1055 		/* Store window size in the packet. */
1056 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1057 			memset(&ws, 0, sizeof(ws));
1058 
1059 		channel_request_start(id, "pty-req", 0);
1060 		packet_put_cstring(cp);
1061 		packet_put_int(ws.ws_col);
1062 		packet_put_int(ws.ws_row);
1063 		packet_put_int(ws.ws_xpixel);
1064 		packet_put_int(ws.ws_ypixel);
1065 		tio = get_saved_tio();
1066 		tty_make_modes(/*ignored*/ 0, &tio);
1067 		packet_send();
1068 		interactive = 1;
1069 		/* XXX wait for reply */
1070 	}
1071 	if (options.forward_x11 &&
1072 	    getenv("DISPLAY") != NULL) {
1073 		char *proto, *data;
1074 		/* Get reasonable local authentication information. */
1075 		x11_get_proto(&proto, &data);
1076 		/* Request forwarding with authentication spoofing. */
1077 		debug("Requesting X11 forwarding with authentication spoofing.");
1078 		x11_request_forwarding_with_spoofing(id, proto, data);
1079 		interactive = 1;
1080 		/* XXX wait for reply */
1081 	}
1082 
1083 	check_agent_present();
1084 	if (options.forward_agent) {
1085 		debug("Requesting authentication agent forwarding.");
1086 		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1087 		packet_send();
1088 	}
1089 
1090 	len = buffer_len(&command);
1091 	if (len > 0) {
1092 		if (len > 900)
1093 			len = 900;
1094 		if (subsystem_flag) {
1095 			debug("Sending subsystem: %.*s", len, (u_char *)buffer_ptr(&command));
1096 			channel_request_start(id, "subsystem", /*want reply*/ 1);
1097 			/* register callback for reply */
1098 			/* XXX we assume that client_loop has already been called */
1099 			dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &client_subsystem_reply);
1100 			dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &client_subsystem_reply);
1101 		} else {
1102 			debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1103 			channel_request_start(id, "exec", 0);
1104 		}
1105 		packet_put_string(buffer_ptr(&command), buffer_len(&command));
1106 		packet_send();
1107 	} else {
1108 		channel_request_start(id, "shell", 0);
1109 		packet_send();
1110 	}
1111 
1112 	packet_set_interactive(interactive);
1113 }
1114 
1115 /* open new channel for a session */
1116 static int
1117 ssh_session2_open(void)
1118 {
1119 	Channel *c;
1120 	int window, packetmax, in, out, err;
1121 
1122 	if (stdin_null_flag) {
1123 		in = open(_PATH_DEVNULL, O_RDONLY);
1124 	} else {
1125 		in = dup(STDIN_FILENO);
1126 	}
1127 	out = dup(STDOUT_FILENO);
1128 	err = dup(STDERR_FILENO);
1129 
1130 	if (in < 0 || out < 0 || err < 0)
1131 		fatal("dup() in/out/err failed");
1132 
1133 	/* enable nonblocking unless tty */
1134 	if (!isatty(in))
1135 		set_nonblock(in);
1136 	if (!isatty(out))
1137 		set_nonblock(out);
1138 	if (!isatty(err))
1139 		set_nonblock(err);
1140 
1141 	window = CHAN_SES_WINDOW_DEFAULT;
1142 	packetmax = CHAN_SES_PACKET_DEFAULT;
1143 	if (tty_flag) {
1144 		window >>= 1;
1145 		packetmax >>= 1;
1146 	}
1147 	c = channel_new(
1148 	    "session", SSH_CHANNEL_OPENING, in, out, err,
1149 	    window, packetmax, CHAN_EXTENDED_WRITE,
1150 	    xstrdup("client-session"), /*nonblock*/0);
1151 
1152 	debug3("ssh_session2_open: channel_new: %d", c->self);
1153 
1154 	channel_send_open(c->self);
1155 	if (!no_shell_flag)
1156 		channel_register_confirm(c->self, ssh_session2_setup);
1157 
1158 	return c->self;
1159 }
1160 
1161 static int
1162 ssh_session2(void)
1163 {
1164 	int id = -1;
1165 
1166 	/* XXX should be pre-session */
1167 	ssh_init_forwarding();
1168 
1169 	if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1170 		id = ssh_session2_open();
1171 
1172 	/* If requested, let ssh continue in the background. */
1173 	if (fork_after_authentication_flag)
1174 		if (daemon(1, 1) < 0)
1175 			fatal("daemon() failed: %.200s", strerror(errno));
1176 
1177 	return client_loop(tty_flag, tty_flag ?
1178 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1179 }
1180 
1181 static void
1182 load_public_identity_files(void)
1183 {
1184 	char *filename;
1185 	int i = 0;
1186 	Key *public;
1187 #ifdef SMARTCARD
1188 	Key **keys;
1189 
1190 	if (options.smartcard_device != NULL &&
1191 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1192 	    (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1193 		int count = 0;
1194 		for (i = 0; keys[i] != NULL; i++) {
1195 			count++;
1196 			memmove(&options.identity_files[1], &options.identity_files[0],
1197 			    sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1198 			memmove(&options.identity_keys[1], &options.identity_keys[0],
1199 			    sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1200 			options.num_identity_files++;
1201 			options.identity_keys[0] = keys[i];
1202 			options.identity_files[0] = xstrdup("smartcard key");;
1203 		}
1204 		if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1205 			options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1206 		i = count;
1207 		xfree(keys);
1208 	}
1209 #endif /* SMARTCARD */
1210 	for (; i < options.num_identity_files; i++) {
1211 		filename = tilde_expand_filename(options.identity_files[i],
1212 		    original_real_uid);
1213 		public = key_load_public(filename, NULL);
1214 		debug("identity file %s type %d", filename,
1215 		    public ? public->type : -1);
1216 		xfree(options.identity_files[i]);
1217 		options.identity_files[i] = filename;
1218 		options.identity_keys[i] = public;
1219 	}
1220 }
1221