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