- (dtucker) [openbsd-compat/port-linux.c] Bug #1851: fix syntax error in
[openssh-git.git] / ssh.c
blobd32ef78b0d150d09ca558e9ab606f0ea5939a75b
1 /* $OpenBSD: ssh.c,v 1.356 2011/01/06 22:23:53 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.
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".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
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.
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.
43 #include "includes.h"
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/param.h>
52 #include <sys/socket.h>
53 #include <sys/wait.h>
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>
71 #include <netinet/in.h>
72 #include <arpa/inet.h>
74 #include <openssl/evp.h>
75 #include <openssl/err.h>
76 #include "openbsd-compat/openssl-compat.h"
77 #include "openbsd-compat/sys-queue.h"
79 #include "xmalloc.h"
80 #include "ssh.h"
81 #include "ssh1.h"
82 #include "ssh2.h"
83 #include "canohost.h"
84 #include "compat.h"
85 #include "cipher.h"
86 #include "packet.h"
87 #include "buffer.h"
88 #include "channels.h"
89 #include "key.h"
90 #include "authfd.h"
91 #include "authfile.h"
92 #include "pathnames.h"
93 #include "dispatch.h"
94 #include "clientloop.h"
95 #include "log.h"
96 #include "readconf.h"
97 #include "sshconnect.h"
98 #include "misc.h"
99 #include "kex.h"
100 #include "mac.h"
101 #include "sshpty.h"
102 #include "match.h"
103 #include "msg.h"
104 #include "uidswap.h"
105 #include "roaming.h"
106 #include "version.h"
108 #ifdef ENABLE_PKCS11
109 #include "ssh-pkcs11.h"
110 #endif
112 extern char *__progname;
114 /* Flag indicating whether debug mode is on. May be set on the command line. */
115 int debug_flag = 0;
117 /* Flag indicating whether a tty should be allocated */
118 int tty_flag = 0;
119 int no_tty_flag = 0;
120 int force_tty_flag = 0;
122 /* don't exec a shell */
123 int no_shell_flag = 0;
126 * Flag indicating that nothing should be read from stdin. This can be set
127 * on the command line.
129 int stdin_null_flag = 0;
132 * Flag indicating that the current process should be backgrounded and
133 * a new slave launched in the foreground for ControlPersist.
135 int need_controlpersist_detach = 0;
137 /* Copies of flags for ControlPersist foreground slave */
138 int ostdin_null_flag, ono_shell_flag, ono_tty_flag, otty_flag;
141 * Flag indicating that ssh should fork after authentication. This is useful
142 * so that the passphrase can be entered manually, and then ssh goes to the
143 * background.
145 int fork_after_authentication_flag = 0;
147 /* forward stdio to remote host and port */
148 char *stdio_forward_host = NULL;
149 int stdio_forward_port = 0;
152 * General data structure for command line options and options configurable
153 * in configuration files. See readconf.h.
155 Options options;
157 /* optional user configfile */
158 char *config = NULL;
161 * Name of the host we are connecting to. This is the name given on the
162 * command line, or the HostName specified for the user-supplied name in a
163 * configuration file.
165 char *host;
167 /* socket address the host resolves to */
168 struct sockaddr_storage hostaddr;
170 /* Private host keys. */
171 Sensitive sensitive_data;
173 /* Original real UID. */
174 uid_t original_real_uid;
175 uid_t original_effective_uid;
177 /* command to be executed */
178 Buffer command;
180 /* Should we execute a command or invoke a subsystem? */
181 int subsystem_flag = 0;
183 /* # of replies received for global requests */
184 static int remote_forward_confirms_received = 0;
186 /* mux.c */
187 extern int muxserver_sock;
188 extern u_int muxclient_command;
190 /* Prints a help message to the user. This function never returns. */
192 static void
193 usage(void)
195 fprintf(stderr,
196 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
197 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
198 " [-I pkcs11] [-i identity_file]\n"
199 " [-L [bind_address:]port:host:hostport]\n"
200 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
201 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
202 " [-W host:port] [-w local_tun[:remote_tun]]\n"
203 " [user@]hostname [command]\n"
205 exit(255);
208 static int ssh_session(void);
209 static int ssh_session2(void);
210 static void load_public_identity_files(void);
211 static void main_sigchld_handler(int);
213 /* from muxclient.c */
214 void muxclient(const char *);
215 void muxserver_listen(void);
218 * Main program for the ssh client.
221 main(int ac, char **av)
223 int i, r, opt, exit_status, use_syslog;
224 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg;
225 struct stat st;
226 struct passwd *pw;
227 int dummy, timeout_ms;
228 extern int optind, optreset;
229 extern char *optarg;
230 struct servent *sp;
231 Forward fwd;
233 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
234 sanitise_stdfd();
236 __progname = ssh_get_progname(av[0]);
237 init_rng();
240 * Discard other fds that are hanging around. These can cause problem
241 * with backgrounded ssh processes started by ControlPersist.
243 closefrom(STDERR_FILENO + 1);
246 * Save the original real uid. It will be needed later (uid-swapping
247 * may clobber the real uid).
249 original_real_uid = getuid();
250 original_effective_uid = geteuid();
253 * Use uid-swapping to give up root privileges for the duration of
254 * option processing. We will re-instantiate the rights when we are
255 * ready to create the privileged port, and will permanently drop
256 * them when the port has been created (actually, when the connection
257 * has been made, as we may need to create the port several times).
259 PRIV_END;
261 #ifdef HAVE_SETRLIMIT
262 /* If we are installed setuid root be careful to not drop core. */
263 if (original_real_uid != original_effective_uid) {
264 struct rlimit rlim;
265 rlim.rlim_cur = rlim.rlim_max = 0;
266 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
267 fatal("setrlimit failed: %.100s", strerror(errno));
269 #endif
270 /* Get user data. */
271 pw = getpwuid(original_real_uid);
272 if (!pw) {
273 logit("You don't exist, go away!");
274 exit(255);
276 /* Take a copy of the returned structure. */
277 pw = pwcopy(pw);
280 * Set our umask to something reasonable, as some files are created
281 * with the default umask. This will make them world-readable but
282 * writable only by the owner, which is ok for all files for which we
283 * don't set the modes explicitly.
285 umask(022);
288 * Initialize option structure to indicate that no values have been
289 * set.
291 initialize_options(&options);
293 /* Parse command-line arguments. */
294 host = NULL;
295 use_syslog = 0;
296 argv0 = av[0];
298 again:
299 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
300 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
301 switch (opt) {
302 case '1':
303 options.protocol = SSH_PROTO_1;
304 break;
305 case '2':
306 options.protocol = SSH_PROTO_2;
307 break;
308 case '4':
309 options.address_family = AF_INET;
310 break;
311 case '6':
312 options.address_family = AF_INET6;
313 break;
314 case 'n':
315 stdin_null_flag = 1;
316 break;
317 case 'f':
318 fork_after_authentication_flag = 1;
319 stdin_null_flag = 1;
320 break;
321 case 'x':
322 options.forward_x11 = 0;
323 break;
324 case 'X':
325 options.forward_x11 = 1;
326 break;
327 case 'y':
328 use_syslog = 1;
329 break;
330 case 'Y':
331 options.forward_x11 = 1;
332 options.forward_x11_trusted = 1;
333 break;
334 case 'g':
335 options.gateway_ports = 1;
336 break;
337 case 'O':
338 if (stdio_forward_host != NULL)
339 fatal("Cannot specify multiplexing "
340 "command with -W");
341 else if (muxclient_command != 0)
342 fatal("Multiplexing command already specified");
343 if (strcmp(optarg, "check") == 0)
344 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
345 else if (strcmp(optarg, "forward") == 0)
346 muxclient_command = SSHMUX_COMMAND_FORWARD;
347 else if (strcmp(optarg, "exit") == 0)
348 muxclient_command = SSHMUX_COMMAND_TERMINATE;
349 else
350 fatal("Invalid multiplex command.");
351 break;
352 case 'P': /* deprecated */
353 options.use_privileged_port = 0;
354 break;
355 case 'a':
356 options.forward_agent = 0;
357 break;
358 case 'A':
359 options.forward_agent = 1;
360 break;
361 case 'k':
362 options.gss_deleg_creds = 0;
363 break;
364 case 'K':
365 options.gss_authentication = 1;
366 options.gss_deleg_creds = 1;
367 break;
368 case 'i':
369 if (stat(optarg, &st) < 0) {
370 fprintf(stderr, "Warning: Identity file %s "
371 "not accessible: %s.\n", optarg,
372 strerror(errno));
373 break;
375 if (options.num_identity_files >=
376 SSH_MAX_IDENTITY_FILES)
377 fatal("Too many identity files specified "
378 "(max %d)", SSH_MAX_IDENTITY_FILES);
379 options.identity_files[options.num_identity_files++] =
380 xstrdup(optarg);
381 break;
382 case 'I':
383 #ifdef ENABLE_PKCS11
384 options.pkcs11_provider = xstrdup(optarg);
385 #else
386 fprintf(stderr, "no support for PKCS#11.\n");
387 #endif
388 break;
389 case 't':
390 if (tty_flag)
391 force_tty_flag = 1;
392 tty_flag = 1;
393 break;
394 case 'v':
395 if (debug_flag == 0) {
396 debug_flag = 1;
397 options.log_level = SYSLOG_LEVEL_DEBUG1;
398 } else {
399 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
400 options.log_level++;
401 break;
403 /* FALLTHROUGH */
404 case 'V':
405 fprintf(stderr, "%s, %s\n",
406 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
407 if (opt == 'V')
408 exit(0);
409 break;
410 case 'w':
411 if (options.tun_open == -1)
412 options.tun_open = SSH_TUNMODE_DEFAULT;
413 options.tun_local = a2tun(optarg, &options.tun_remote);
414 if (options.tun_local == SSH_TUNID_ERR) {
415 fprintf(stderr,
416 "Bad tun device '%s'\n", optarg);
417 exit(255);
419 break;
420 case 'W':
421 if (stdio_forward_host != NULL)
422 fatal("stdio forward already specified");
423 if (muxclient_command != 0)
424 fatal("Cannot specify stdio forward with -O");
425 if (parse_forward(&fwd, optarg, 1, 0)) {
426 stdio_forward_host = fwd.listen_host;
427 stdio_forward_port = fwd.listen_port;
428 xfree(fwd.connect_host);
429 } else {
430 fprintf(stderr,
431 "Bad stdio forwarding specification '%s'\n",
432 optarg);
433 exit(255);
435 no_tty_flag = 1;
436 no_shell_flag = 1;
437 options.clear_forwardings = 1;
438 options.exit_on_forward_failure = 1;
439 break;
440 case 'q':
441 options.log_level = SYSLOG_LEVEL_QUIET;
442 break;
443 case 'e':
444 if (optarg[0] == '^' && optarg[2] == 0 &&
445 (u_char) optarg[1] >= 64 &&
446 (u_char) optarg[1] < 128)
447 options.escape_char = (u_char) optarg[1] & 31;
448 else if (strlen(optarg) == 1)
449 options.escape_char = (u_char) optarg[0];
450 else if (strcmp(optarg, "none") == 0)
451 options.escape_char = SSH_ESCAPECHAR_NONE;
452 else {
453 fprintf(stderr, "Bad escape character '%s'.\n",
454 optarg);
455 exit(255);
457 break;
458 case 'c':
459 if (ciphers_valid(optarg)) {
460 /* SSH2 only */
461 options.ciphers = xstrdup(optarg);
462 options.cipher = SSH_CIPHER_INVALID;
463 } else {
464 /* SSH1 only */
465 options.cipher = cipher_number(optarg);
466 if (options.cipher == -1) {
467 fprintf(stderr,
468 "Unknown cipher type '%s'\n",
469 optarg);
470 exit(255);
472 if (options.cipher == SSH_CIPHER_3DES)
473 options.ciphers = "3des-cbc";
474 else if (options.cipher == SSH_CIPHER_BLOWFISH)
475 options.ciphers = "blowfish-cbc";
476 else
477 options.ciphers = (char *)-1;
479 break;
480 case 'm':
481 if (mac_valid(optarg))
482 options.macs = xstrdup(optarg);
483 else {
484 fprintf(stderr, "Unknown mac type '%s'\n",
485 optarg);
486 exit(255);
488 break;
489 case 'M':
490 if (options.control_master == SSHCTL_MASTER_YES)
491 options.control_master = SSHCTL_MASTER_ASK;
492 else
493 options.control_master = SSHCTL_MASTER_YES;
494 break;
495 case 'p':
496 options.port = a2port(optarg);
497 if (options.port <= 0) {
498 fprintf(stderr, "Bad port '%s'\n", optarg);
499 exit(255);
501 break;
502 case 'l':
503 options.user = optarg;
504 break;
506 case 'L':
507 if (parse_forward(&fwd, optarg, 0, 0))
508 add_local_forward(&options, &fwd);
509 else {
510 fprintf(stderr,
511 "Bad local forwarding specification '%s'\n",
512 optarg);
513 exit(255);
515 break;
517 case 'R':
518 if (parse_forward(&fwd, optarg, 0, 1)) {
519 add_remote_forward(&options, &fwd);
520 } else {
521 fprintf(stderr,
522 "Bad remote forwarding specification "
523 "'%s'\n", optarg);
524 exit(255);
526 break;
528 case 'D':
529 if (parse_forward(&fwd, optarg, 1, 0)) {
530 add_local_forward(&options, &fwd);
531 } else {
532 fprintf(stderr,
533 "Bad dynamic forwarding specification "
534 "'%s'\n", optarg);
535 exit(255);
537 break;
539 case 'C':
540 options.compression = 1;
541 break;
542 case 'N':
543 no_shell_flag = 1;
544 no_tty_flag = 1;
545 break;
546 case 'T':
547 no_tty_flag = 1;
548 break;
549 case 'o':
550 dummy = 1;
551 line = xstrdup(optarg);
552 if (process_config_line(&options, host ? host : "",
553 line, "command-line", 0, &dummy) != 0)
554 exit(255);
555 xfree(line);
556 break;
557 case 's':
558 subsystem_flag = 1;
559 break;
560 case 'S':
561 if (options.control_path != NULL)
562 free(options.control_path);
563 options.control_path = xstrdup(optarg);
564 break;
565 case 'b':
566 options.bind_address = optarg;
567 break;
568 case 'F':
569 config = optarg;
570 break;
571 default:
572 usage();
576 ac -= optind;
577 av += optind;
579 if (ac > 0 && !host) {
580 if (strrchr(*av, '@')) {
581 p = xstrdup(*av);
582 cp = strrchr(p, '@');
583 if (cp == NULL || cp == p)
584 usage();
585 options.user = p;
586 *cp = '\0';
587 host = ++cp;
588 } else
589 host = *av;
590 if (ac > 1) {
591 optind = optreset = 1;
592 goto again;
594 ac--, av++;
597 /* Check that we got a host name. */
598 if (!host)
599 usage();
601 OpenSSL_add_all_algorithms();
602 ERR_load_crypto_strings();
604 /* Initialize the command to execute on remote host. */
605 buffer_init(&command);
608 * Save the command to execute on the remote host in a buffer. There
609 * is no limit on the length of the command, except by the maximum
610 * packet size. Also sets the tty flag if there is no command.
612 if (!ac) {
613 /* No command specified - execute shell on a tty. */
614 tty_flag = 1;
615 if (subsystem_flag) {
616 fprintf(stderr,
617 "You must specify a subsystem to invoke.\n");
618 usage();
620 } else {
621 /* A command has been specified. Store it into the buffer. */
622 for (i = 0; i < ac; i++) {
623 if (i)
624 buffer_append(&command, " ", 1);
625 buffer_append(&command, av[i], strlen(av[i]));
629 /* Cannot fork to background if no command. */
630 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
631 !no_shell_flag)
632 fatal("Cannot fork into background without a command "
633 "to execute.");
635 /* Allocate a tty by default if no command specified. */
636 if (buffer_len(&command) == 0)
637 tty_flag = 1;
639 /* Force no tty */
640 if (no_tty_flag || muxclient_command != 0)
641 tty_flag = 0;
642 /* Do not allocate a tty if stdin is not a tty. */
643 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
644 if (tty_flag)
645 logit("Pseudo-terminal will not be allocated because "
646 "stdin is not a terminal.");
647 tty_flag = 0;
651 * Initialize "log" output. Since we are the client all output
652 * actually goes to stderr.
654 log_init(argv0,
655 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
656 SYSLOG_FACILITY_USER, !use_syslog);
659 * Read per-user configuration file. Ignore the system wide config
660 * file if the user specifies a config file on the command line.
662 if (config != NULL) {
663 if (!read_config_file(config, host, &options, 0))
664 fatal("Can't open user config file %.100s: "
665 "%.100s", config, strerror(errno));
666 } else {
667 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
668 _PATH_SSH_USER_CONFFILE);
669 if (r > 0 && (size_t)r < sizeof(buf))
670 (void)read_config_file(buf, host, &options, 1);
672 /* Read systemwide configuration file after use config. */
673 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
674 &options, 0);
677 /* Fill configuration defaults. */
678 fill_default_options(&options);
680 channel_set_af(options.address_family);
682 /* reinit */
683 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
685 seed_rng();
687 if (options.user == NULL)
688 options.user = xstrdup(pw->pw_name);
690 /* Get default port if port has not been set. */
691 if (options.port == 0) {
692 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
693 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
696 /* preserve host name given on command line for %n expansion */
697 host_arg = host;
698 if (options.hostname != NULL) {
699 host = percent_expand(options.hostname,
700 "h", host, (char *)NULL);
703 if (options.local_command != NULL) {
704 char thishost[NI_MAXHOST];
706 if (gethostname(thishost, sizeof(thishost)) == -1)
707 fatal("gethostname: %s", strerror(errno));
708 snprintf(buf, sizeof(buf), "%d", options.port);
709 debug3("expanding LocalCommand: %s", options.local_command);
710 cp = options.local_command;
711 options.local_command = percent_expand(cp, "d", pw->pw_dir,
712 "h", host, "l", thishost, "n", host_arg, "r", options.user,
713 "p", buf, "u", pw->pw_name, (char *)NULL);
714 debug3("expanded LocalCommand: %s", options.local_command);
715 xfree(cp);
718 /* force lowercase for hostkey matching */
719 if (options.host_key_alias != NULL) {
720 for (p = options.host_key_alias; *p; p++)
721 if (isupper(*p))
722 *p = (char)tolower(*p);
725 if (options.proxy_command != NULL &&
726 strcmp(options.proxy_command, "none") == 0) {
727 xfree(options.proxy_command);
728 options.proxy_command = NULL;
730 if (options.control_path != NULL &&
731 strcmp(options.control_path, "none") == 0) {
732 xfree(options.control_path);
733 options.control_path = NULL;
736 if (options.control_path != NULL) {
737 char thishost[NI_MAXHOST];
739 if (gethostname(thishost, sizeof(thishost)) == -1)
740 fatal("gethostname: %s", strerror(errno));
741 snprintf(buf, sizeof(buf), "%d", options.port);
742 cp = tilde_expand_filename(options.control_path,
743 original_real_uid);
744 xfree(options.control_path);
745 options.control_path = percent_expand(cp, "p", buf, "h", host,
746 "r", options.user, "l", thishost, (char *)NULL);
747 xfree(cp);
749 if (muxclient_command != 0 && options.control_path == NULL)
750 fatal("No ControlPath specified for \"-O\" command");
751 if (options.control_path != NULL)
752 muxclient(options.control_path);
754 timeout_ms = options.connection_timeout * 1000;
756 /* Open a connection to the remote host. */
757 if (ssh_connect(host, &hostaddr, options.port,
758 options.address_family, options.connection_attempts, &timeout_ms,
759 options.tcp_keep_alive,
760 #ifdef HAVE_CYGWIN
761 options.use_privileged_port,
762 #else
763 original_effective_uid == 0 && options.use_privileged_port,
764 #endif
765 options.proxy_command) != 0)
766 exit(255);
768 if (timeout_ms > 0)
769 debug3("timeout: %d ms remain after connect", timeout_ms);
772 * If we successfully made the connection, load the host private key
773 * in case we will need it later for combined rsa-rhosts
774 * authentication. This must be done before releasing extra
775 * privileges, because the file is only readable by root.
776 * If we cannot access the private keys, load the public keys
777 * instead and try to execute the ssh-keysign helper instead.
779 sensitive_data.nkeys = 0;
780 sensitive_data.keys = NULL;
781 sensitive_data.external_keysign = 0;
782 if (options.rhosts_rsa_authentication ||
783 options.hostbased_authentication) {
784 sensitive_data.nkeys = 7;
785 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
786 sizeof(Key));
787 for (i = 0; i < sensitive_data.nkeys; i++)
788 sensitive_data.keys[i] = NULL;
790 PRIV_START;
791 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
792 _PATH_HOST_KEY_FILE, "", NULL, NULL);
793 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
794 _PATH_HOST_DSA_KEY_FILE, "", NULL);
795 #ifdef OPENSSL_HAS_ECC
796 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
797 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
798 #endif
799 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
800 _PATH_HOST_RSA_KEY_FILE, "", NULL);
801 sensitive_data.keys[4] = key_load_private_type(KEY_DSA,
802 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
803 #ifdef OPENSSL_HAS_ECC
804 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
805 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
806 #endif
807 sensitive_data.keys[6] = key_load_private_type(KEY_RSA,
808 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
809 PRIV_END;
811 if (options.hostbased_authentication == 1 &&
812 sensitive_data.keys[0] == NULL &&
813 sensitive_data.keys[4] == NULL &&
814 sensitive_data.keys[5] == NULL &&
815 sensitive_data.keys[6] == NULL) {
816 sensitive_data.keys[1] = key_load_cert(
817 _PATH_HOST_DSA_KEY_FILE);
818 #ifdef OPENSSL_HAS_ECC
819 sensitive_data.keys[2] = key_load_cert(
820 _PATH_HOST_ECDSA_KEY_FILE);
821 #endif
822 sensitive_data.keys[3] = key_load_cert(
823 _PATH_HOST_RSA_KEY_FILE);
824 sensitive_data.keys[4] = key_load_public(
825 _PATH_HOST_DSA_KEY_FILE, NULL);
826 #ifdef OPENSSL_HAS_ECC
827 sensitive_data.keys[5] = key_load_public(
828 _PATH_HOST_ECDSA_KEY_FILE, NULL);
829 #endif
830 sensitive_data.keys[6] = key_load_public(
831 _PATH_HOST_RSA_KEY_FILE, NULL);
832 sensitive_data.external_keysign = 1;
836 * Get rid of any extra privileges that we may have. We will no
837 * longer need them. Also, extra privileges could make it very hard
838 * to read identity files and other non-world-readable files from the
839 * user's home directory if it happens to be on a NFS volume where
840 * root is mapped to nobody.
842 if (original_effective_uid == 0) {
843 PRIV_START;
844 permanently_set_uid(pw);
848 * Now that we are back to our own permissions, create ~/.ssh
849 * directory if it doesn't already exist.
851 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
852 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
853 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
854 #ifdef WITH_SELINUX
855 ssh_selinux_setfscreatecon(buf);
856 #endif
857 if (mkdir(buf, 0700) < 0)
858 error("Could not create directory '%.200s'.", buf);
859 #ifdef WITH_SELINUX
860 ssh_selinux_setfscreatecon(NULL);
861 #endif
863 /* load options.identity_files */
864 load_public_identity_files();
866 /* Expand ~ in known host file names. */
867 /* XXX mem-leaks: */
868 options.system_hostfile =
869 tilde_expand_filename(options.system_hostfile, original_real_uid);
870 options.user_hostfile =
871 tilde_expand_filename(options.user_hostfile, original_real_uid);
872 options.system_hostfile2 =
873 tilde_expand_filename(options.system_hostfile2, original_real_uid);
874 options.user_hostfile2 =
875 tilde_expand_filename(options.user_hostfile2, original_real_uid);
877 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
878 signal(SIGCHLD, main_sigchld_handler);
880 /* Log into the remote system. Never returns if the login fails. */
881 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
882 options.port, pw, timeout_ms);
884 if (packet_connection_is_on_socket()) {
885 verbose("Authenticated to %s ([%s]:%d).", host,
886 get_remote_ipaddr(), get_remote_port());
887 } else {
888 verbose("Authenticated to %s (via proxy).", host);
891 /* We no longer need the private host keys. Clear them now. */
892 if (sensitive_data.nkeys != 0) {
893 for (i = 0; i < sensitive_data.nkeys; i++) {
894 if (sensitive_data.keys[i] != NULL) {
895 /* Destroys contents safely */
896 debug3("clear hostkey %d", i);
897 key_free(sensitive_data.keys[i]);
898 sensitive_data.keys[i] = NULL;
901 xfree(sensitive_data.keys);
903 for (i = 0; i < options.num_identity_files; i++) {
904 if (options.identity_files[i]) {
905 xfree(options.identity_files[i]);
906 options.identity_files[i] = NULL;
908 if (options.identity_keys[i]) {
909 key_free(options.identity_keys[i]);
910 options.identity_keys[i] = NULL;
914 exit_status = compat20 ? ssh_session2() : ssh_session();
915 packet_close();
917 if (options.control_path != NULL && muxserver_sock != -1)
918 unlink(options.control_path);
920 /* Kill ProxyCommand if it is running. */
921 ssh_kill_proxy_command();
923 return exit_status;
926 static void
927 control_persist_detach(void)
929 pid_t pid;
930 int devnull;
932 debug("%s: backgrounding master process", __func__);
935 * master (current process) into the background, and make the
936 * foreground process a client of the backgrounded master.
938 switch ((pid = fork())) {
939 case -1:
940 fatal("%s: fork: %s", __func__, strerror(errno));
941 case 0:
942 /* Child: master process continues mainloop */
943 break;
944 default:
945 /* Parent: set up mux slave to connect to backgrounded master */
946 debug2("%s: background process is %ld", __func__, (long)pid);
947 stdin_null_flag = ostdin_null_flag;
948 no_shell_flag = ono_shell_flag;
949 no_tty_flag = ono_tty_flag;
950 tty_flag = otty_flag;
951 close(muxserver_sock);
952 muxserver_sock = -1;
953 options.control_master = SSHCTL_MASTER_NO;
954 muxclient(options.control_path);
955 /* muxclient() doesn't return on success. */
956 fatal("Failed to connect to new control master");
958 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
959 error("%s: open(\"/dev/null\"): %s", __func__,
960 strerror(errno));
961 } else {
962 if (dup2(devnull, STDIN_FILENO) == -1 ||
963 dup2(devnull, STDOUT_FILENO) == -1)
964 error("%s: dup2: %s", __func__, strerror(errno));
965 if (devnull > STDERR_FILENO)
966 close(devnull);
970 /* Do fork() after authentication. Used by "ssh -f" */
971 static void
972 fork_postauth(void)
974 if (need_controlpersist_detach)
975 control_persist_detach();
976 debug("forking to background");
977 fork_after_authentication_flag = 0;
978 if (daemon(1, 1) < 0)
979 fatal("daemon() failed: %.200s", strerror(errno));
982 /* Callback for remote forward global requests */
983 static void
984 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
986 Forward *rfwd = (Forward *)ctxt;
988 /* XXX verbose() on failure? */
989 debug("remote forward %s for: listen %d, connect %s:%d",
990 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
991 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
992 if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
993 rfwd->allocated_port = packet_get_int();
994 logit("Allocated port %u for remote forward to %s:%d",
995 rfwd->allocated_port,
996 rfwd->connect_host, rfwd->connect_port);
999 if (type == SSH2_MSG_REQUEST_FAILURE) {
1000 if (options.exit_on_forward_failure)
1001 fatal("Error: remote port forwarding failed for "
1002 "listen port %d", rfwd->listen_port);
1003 else
1004 logit("Warning: remote port forwarding failed for "
1005 "listen port %d", rfwd->listen_port);
1007 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1008 debug("All remote forwarding requests processed");
1009 if (fork_after_authentication_flag)
1010 fork_postauth();
1014 static void
1015 client_cleanup_stdio_fwd(int id, void *arg)
1017 debug("stdio forwarding: done");
1018 cleanup_exit(0);
1021 static int
1022 client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
1024 Channel *c;
1025 int in, out;
1027 debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
1028 port_to_connect);
1030 in = dup(STDIN_FILENO);
1031 out = dup(STDOUT_FILENO);
1032 if (in < 0 || out < 0)
1033 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1035 if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
1036 in, out)) == NULL)
1037 return 0;
1038 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1039 return 1;
1042 static void
1043 ssh_init_forwarding(void)
1045 int success = 0;
1046 int i;
1048 if (stdio_forward_host != NULL) {
1049 if (!compat20) {
1050 fatal("stdio forwarding require Protocol 2");
1052 if (!client_setup_stdio_fwd(stdio_forward_host,
1053 stdio_forward_port))
1054 fatal("Failed to connect in stdio forward mode.");
1057 /* Initiate local TCP/IP port forwardings. */
1058 for (i = 0; i < options.num_local_forwards; i++) {
1059 debug("Local connections to %.200s:%d forwarded to remote "
1060 "address %.200s:%d",
1061 (options.local_forwards[i].listen_host == NULL) ?
1062 (options.gateway_ports ? "*" : "LOCALHOST") :
1063 options.local_forwards[i].listen_host,
1064 options.local_forwards[i].listen_port,
1065 options.local_forwards[i].connect_host,
1066 options.local_forwards[i].connect_port);
1067 success += channel_setup_local_fwd_listener(
1068 options.local_forwards[i].listen_host,
1069 options.local_forwards[i].listen_port,
1070 options.local_forwards[i].connect_host,
1071 options.local_forwards[i].connect_port,
1072 options.gateway_ports);
1074 if (i > 0 && success != i && options.exit_on_forward_failure)
1075 fatal("Could not request local forwarding.");
1076 if (i > 0 && success == 0)
1077 error("Could not request local forwarding.");
1079 /* Initiate remote TCP/IP port forwardings. */
1080 for (i = 0; i < options.num_remote_forwards; i++) {
1081 debug("Remote connections from %.200s:%d forwarded to "
1082 "local address %.200s:%d",
1083 (options.remote_forwards[i].listen_host == NULL) ?
1084 "LOCALHOST" : options.remote_forwards[i].listen_host,
1085 options.remote_forwards[i].listen_port,
1086 options.remote_forwards[i].connect_host,
1087 options.remote_forwards[i].connect_port);
1088 if (channel_request_remote_forwarding(
1089 options.remote_forwards[i].listen_host,
1090 options.remote_forwards[i].listen_port,
1091 options.remote_forwards[i].connect_host,
1092 options.remote_forwards[i].connect_port) < 0) {
1093 if (options.exit_on_forward_failure)
1094 fatal("Could not request remote forwarding.");
1095 else
1096 logit("Warning: Could not request remote "
1097 "forwarding.");
1099 client_register_global_confirm(ssh_confirm_remote_forward,
1100 &options.remote_forwards[i]);
1103 /* Initiate tunnel forwarding. */
1104 if (options.tun_open != SSH_TUNMODE_NO) {
1105 if (client_request_tun_fwd(options.tun_open,
1106 options.tun_local, options.tun_remote) == -1) {
1107 if (options.exit_on_forward_failure)
1108 fatal("Could not request tunnel forwarding.");
1109 else
1110 error("Could not request tunnel forwarding.");
1115 static void
1116 check_agent_present(void)
1118 if (options.forward_agent) {
1119 /* Clear agent forwarding if we don't have an agent. */
1120 if (!ssh_agent_present())
1121 options.forward_agent = 0;
1125 static int
1126 ssh_session(void)
1128 int type;
1129 int interactive = 0;
1130 int have_tty = 0;
1131 struct winsize ws;
1132 char *cp;
1133 const char *display;
1135 /* Enable compression if requested. */
1136 if (options.compression) {
1137 debug("Requesting compression at level %d.",
1138 options.compression_level);
1140 if (options.compression_level < 1 ||
1141 options.compression_level > 9)
1142 fatal("Compression level must be from 1 (fast) to "
1143 "9 (slow, best).");
1145 /* Send the request. */
1146 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1147 packet_put_int(options.compression_level);
1148 packet_send();
1149 packet_write_wait();
1150 type = packet_read();
1151 if (type == SSH_SMSG_SUCCESS)
1152 packet_start_compression(options.compression_level);
1153 else if (type == SSH_SMSG_FAILURE)
1154 logit("Warning: Remote host refused compression.");
1155 else
1156 packet_disconnect("Protocol error waiting for "
1157 "compression response.");
1159 /* Allocate a pseudo tty if appropriate. */
1160 if (tty_flag) {
1161 debug("Requesting pty.");
1163 /* Start the packet. */
1164 packet_start(SSH_CMSG_REQUEST_PTY);
1166 /* Store TERM in the packet. There is no limit on the
1167 length of the string. */
1168 cp = getenv("TERM");
1169 if (!cp)
1170 cp = "";
1171 packet_put_cstring(cp);
1173 /* Store window size in the packet. */
1174 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1175 memset(&ws, 0, sizeof(ws));
1176 packet_put_int((u_int)ws.ws_row);
1177 packet_put_int((u_int)ws.ws_col);
1178 packet_put_int((u_int)ws.ws_xpixel);
1179 packet_put_int((u_int)ws.ws_ypixel);
1181 /* Store tty modes in the packet. */
1182 tty_make_modes(fileno(stdin), NULL);
1184 /* Send the packet, and wait for it to leave. */
1185 packet_send();
1186 packet_write_wait();
1188 /* Read response from the server. */
1189 type = packet_read();
1190 if (type == SSH_SMSG_SUCCESS) {
1191 interactive = 1;
1192 have_tty = 1;
1193 } else if (type == SSH_SMSG_FAILURE)
1194 logit("Warning: Remote host failed or refused to "
1195 "allocate a pseudo tty.");
1196 else
1197 packet_disconnect("Protocol error waiting for pty "
1198 "request response.");
1200 /* Request X11 forwarding if enabled and DISPLAY is set. */
1201 display = getenv("DISPLAY");
1202 if (options.forward_x11 && display != NULL) {
1203 char *proto, *data;
1204 /* Get reasonable local authentication information. */
1205 client_x11_get_proto(display, options.xauth_location,
1206 options.forward_x11_trusted,
1207 options.forward_x11_timeout,
1208 &proto, &data);
1209 /* Request forwarding with authentication spoofing. */
1210 debug("Requesting X11 forwarding with authentication "
1211 "spoofing.");
1212 x11_request_forwarding_with_spoofing(0, display, proto, data);
1214 /* Read response from the server. */
1215 type = packet_read();
1216 if (type == SSH_SMSG_SUCCESS) {
1217 interactive = 1;
1218 } else if (type == SSH_SMSG_FAILURE) {
1219 logit("Warning: Remote host denied X11 forwarding.");
1220 } else {
1221 packet_disconnect("Protocol error waiting for X11 "
1222 "forwarding");
1225 /* Tell the packet module whether this is an interactive session. */
1226 packet_set_interactive(interactive,
1227 options.ip_qos_interactive, options.ip_qos_bulk);
1229 /* Request authentication agent forwarding if appropriate. */
1230 check_agent_present();
1232 if (options.forward_agent) {
1233 debug("Requesting authentication agent forwarding.");
1234 auth_request_forwarding();
1236 /* Read response from the server. */
1237 type = packet_read();
1238 packet_check_eom();
1239 if (type != SSH_SMSG_SUCCESS)
1240 logit("Warning: Remote host denied authentication agent forwarding.");
1243 /* Initiate port forwardings. */
1244 ssh_init_forwarding();
1246 /* Execute a local command */
1247 if (options.local_command != NULL &&
1248 options.permit_local_command)
1249 ssh_local_cmd(options.local_command);
1252 * If requested and we are not interested in replies to remote
1253 * forwarding requests, then let ssh continue in the background.
1255 if (fork_after_authentication_flag) {
1256 if (options.exit_on_forward_failure &&
1257 options.num_remote_forwards > 0) {
1258 debug("deferring postauth fork until remote forward "
1259 "confirmation received");
1260 } else
1261 fork_postauth();
1265 * If a command was specified on the command line, execute the
1266 * command now. Otherwise request the server to start a shell.
1268 if (buffer_len(&command) > 0) {
1269 int len = buffer_len(&command);
1270 if (len > 900)
1271 len = 900;
1272 debug("Sending command: %.*s", len,
1273 (u_char *)buffer_ptr(&command));
1274 packet_start(SSH_CMSG_EXEC_CMD);
1275 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1276 packet_send();
1277 packet_write_wait();
1278 } else {
1279 debug("Requesting shell.");
1280 packet_start(SSH_CMSG_EXEC_SHELL);
1281 packet_send();
1282 packet_write_wait();
1285 /* Enter the interactive session. */
1286 return client_loop(have_tty, tty_flag ?
1287 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1290 /* request pty/x11/agent/tcpfwd/shell for channel */
1291 static void
1292 ssh_session2_setup(int id, int success, void *arg)
1294 extern char **environ;
1295 const char *display;
1296 int interactive = tty_flag;
1298 if (!success)
1299 return; /* No need for error message, channels code sens one */
1301 display = getenv("DISPLAY");
1302 if (options.forward_x11 && display != NULL) {
1303 char *proto, *data;
1304 /* Get reasonable local authentication information. */
1305 client_x11_get_proto(display, options.xauth_location,
1306 options.forward_x11_trusted,
1307 options.forward_x11_timeout, &proto, &data);
1308 /* Request forwarding with authentication spoofing. */
1309 debug("Requesting X11 forwarding with authentication "
1310 "spoofing.");
1311 x11_request_forwarding_with_spoofing(id, display, proto, data);
1312 interactive = 1;
1313 /* XXX wait for reply */
1316 check_agent_present();
1317 if (options.forward_agent) {
1318 debug("Requesting authentication agent forwarding.");
1319 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1320 packet_send();
1323 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1324 NULL, fileno(stdin), &command, environ);
1327 /* open new channel for a session */
1328 static int
1329 ssh_session2_open(void)
1331 Channel *c;
1332 int window, packetmax, in, out, err;
1334 if (stdin_null_flag) {
1335 in = open(_PATH_DEVNULL, O_RDONLY);
1336 } else {
1337 in = dup(STDIN_FILENO);
1339 out = dup(STDOUT_FILENO);
1340 err = dup(STDERR_FILENO);
1342 if (in < 0 || out < 0 || err < 0)
1343 fatal("dup() in/out/err failed");
1345 /* enable nonblocking unless tty */
1346 if (!isatty(in))
1347 set_nonblock(in);
1348 if (!isatty(out))
1349 set_nonblock(out);
1350 if (!isatty(err))
1351 set_nonblock(err);
1353 window = CHAN_SES_WINDOW_DEFAULT;
1354 packetmax = CHAN_SES_PACKET_DEFAULT;
1355 if (tty_flag) {
1356 window >>= 1;
1357 packetmax >>= 1;
1359 c = channel_new(
1360 "session", SSH_CHANNEL_OPENING, in, out, err,
1361 window, packetmax, CHAN_EXTENDED_WRITE,
1362 "client-session", /*nonblock*/0);
1364 debug3("ssh_session2_open: channel_new: %d", c->self);
1366 channel_send_open(c->self);
1367 if (!no_shell_flag)
1368 channel_register_open_confirm(c->self,
1369 ssh_session2_setup, NULL);
1371 return c->self;
1374 static int
1375 ssh_session2(void)
1377 int id = -1;
1379 /* XXX should be pre-session */
1380 ssh_init_forwarding();
1382 /* Start listening for multiplex clients */
1383 muxserver_listen();
1386 * If we are in control persist mode, then prepare to background
1387 * ourselves and have a foreground client attach as a control
1388 * slave. NB. we must save copies of the flags that we override for
1389 * the backgrounding, since we defer attachment of the slave until
1390 * after the connection is fully established (in particular,
1391 * async rfwd replies have been received for ExitOnForwardFailure).
1393 if (options.control_persist && muxserver_sock != -1) {
1394 ostdin_null_flag = stdin_null_flag;
1395 ono_shell_flag = no_shell_flag;
1396 ono_tty_flag = no_tty_flag;
1397 otty_flag = tty_flag;
1398 stdin_null_flag = 1;
1399 no_shell_flag = 1;
1400 no_tty_flag = 1;
1401 tty_flag = 0;
1402 if (!fork_after_authentication_flag)
1403 need_controlpersist_detach = 1;
1404 fork_after_authentication_flag = 1;
1407 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1408 id = ssh_session2_open();
1410 /* If we don't expect to open a new session, then disallow it */
1411 if (options.control_master == SSHCTL_MASTER_NO &&
1412 (datafellows & SSH_NEW_OPENSSH)) {
1413 debug("Requesting no-more-sessions@openssh.com");
1414 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1415 packet_put_cstring("no-more-sessions@openssh.com");
1416 packet_put_char(0);
1417 packet_send();
1420 /* Execute a local command */
1421 if (options.local_command != NULL &&
1422 options.permit_local_command)
1423 ssh_local_cmd(options.local_command);
1426 * If requested and we are not interested in replies to remote
1427 * forwarding requests, then let ssh continue in the background.
1429 if (fork_after_authentication_flag) {
1430 if (options.exit_on_forward_failure &&
1431 options.num_remote_forwards > 0) {
1432 debug("deferring postauth fork until remote forward "
1433 "confirmation received");
1434 } else
1435 fork_postauth();
1438 if (options.use_roaming)
1439 request_roaming();
1441 return client_loop(tty_flag, tty_flag ?
1442 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1445 static void
1446 load_public_identity_files(void)
1448 char *filename, *cp, thishost[NI_MAXHOST];
1449 char *pwdir = NULL, *pwname = NULL;
1450 int i = 0;
1451 Key *public;
1452 struct passwd *pw;
1453 u_int n_ids;
1454 char *identity_files[SSH_MAX_IDENTITY_FILES];
1455 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1456 #ifdef ENABLE_PKCS11
1457 Key **keys;
1458 int nkeys;
1459 #endif /* PKCS11 */
1461 n_ids = 0;
1462 bzero(identity_files, sizeof(identity_files));
1463 bzero(identity_keys, sizeof(identity_keys));
1465 #ifdef ENABLE_PKCS11
1466 if (options.pkcs11_provider != NULL &&
1467 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1468 (pkcs11_init(!options.batch_mode) == 0) &&
1469 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1470 &keys)) > 0) {
1471 for (i = 0; i < nkeys; i++) {
1472 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1473 key_free(keys[i]);
1474 continue;
1476 identity_keys[n_ids] = keys[i];
1477 identity_files[n_ids] =
1478 xstrdup(options.pkcs11_provider); /* XXX */
1479 n_ids++;
1481 xfree(keys);
1483 #endif /* ENABLE_PKCS11 */
1484 if ((pw = getpwuid(original_real_uid)) == NULL)
1485 fatal("load_public_identity_files: getpwuid failed");
1486 pwname = xstrdup(pw->pw_name);
1487 pwdir = xstrdup(pw->pw_dir);
1488 if (gethostname(thishost, sizeof(thishost)) == -1)
1489 fatal("load_public_identity_files: gethostname: %s",
1490 strerror(errno));
1491 for (i = 0; i < options.num_identity_files; i++) {
1492 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1493 xfree(options.identity_files[i]);
1494 continue;
1496 cp = tilde_expand_filename(options.identity_files[i],
1497 original_real_uid);
1498 filename = percent_expand(cp, "d", pwdir,
1499 "u", pwname, "l", thishost, "h", host,
1500 "r", options.user, (char *)NULL);
1501 xfree(cp);
1502 public = key_load_public(filename, NULL);
1503 debug("identity file %s type %d", filename,
1504 public ? public->type : -1);
1505 xfree(options.identity_files[i]);
1506 identity_files[n_ids] = filename;
1507 identity_keys[n_ids] = public;
1509 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1510 continue;
1512 /* Try to add the certificate variant too */
1513 xasprintf(&cp, "%s-cert", filename);
1514 public = key_load_public(cp, NULL);
1515 debug("identity file %s type %d", cp,
1516 public ? public->type : -1);
1517 if (public == NULL) {
1518 xfree(cp);
1519 continue;
1521 if (!key_is_cert(public)) {
1522 debug("%s: key %s type %s is not a certificate",
1523 __func__, cp, key_type(public));
1524 key_free(public);
1525 xfree(cp);
1526 continue;
1528 identity_keys[n_ids] = public;
1529 /* point to the original path, most likely the private key */
1530 identity_files[n_ids] = xstrdup(filename);
1531 n_ids++;
1533 options.num_identity_files = n_ids;
1534 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1535 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1537 bzero(pwname, strlen(pwname));
1538 xfree(pwname);
1539 bzero(pwdir, strlen(pwdir));
1540 xfree(pwdir);
1543 static void
1544 main_sigchld_handler(int sig)
1546 int save_errno = errno;
1547 pid_t pid;
1548 int status;
1550 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1551 (pid < 0 && errno == EINTR))
1554 signal(sig, main_sigchld_handler);
1555 errno = save_errno;