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