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