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