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