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