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