1
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
2
/* gnome-keyring-daemon.c - main keyring daemon code.
4
Copyright (C) 2003 Red Hat, Inc
6
Gnome keyring is free software; you can redistribute it and/or
7
modify it under the terms of the GNU General Public License as
8
published by the Free Software Foundation; either version 2 of the
9
License, or (at your option) any later version.
11
Gnome keyring is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
General Public License for more details.
16
You should have received a copy of the GNU General Public License
17
along with this program; if not, write to the Free Software
18
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
Author: Alexander Larsson <alexl@redhat.com>
25
#include "gkr-daemon.h"
27
#include "egg/egg-cleanup.h"
28
#include "egg/egg-libgcrypt.h"
29
#include "egg/egg-secure-memory.h"
30
#include "egg/egg-unix-credentials.h"
32
#include "keyrings/gkr-keyring-login.h"
34
#include "library/gnome-keyring.h"
36
#include "pkcs11/gkr-pkcs11-daemon.h"
38
#include "ui/gkr-ask-daemon.h"
40
#include "util/gkr-daemon-async.h"
41
#include "util/gkr-daemon-util.h"
53
#include <sys/types.h>
54
#include <sys/socket.h>
60
#include <glib/gi18n.h>
62
#include <gconf/gconf.h>
63
#include <gconf/gconf-client.h>
67
/* preset file descriptors */
72
#ifndef HAVE_SOCKLEN_T
76
/* -----------------------------------------------------------------------------
80
/* All the components to run on startup if not set in gconf */
82
#define DEFAULT_COMPONENTS "ssh,pkcs11"
84
#define DEFAULT_COMPONENTS "pkcs11"
87
static gboolean run_foreground = FALSE;
88
static gboolean run_daemonized = FALSE;
89
static gboolean run_for_login = FALSE;
90
static gboolean run_for_start = FALSE;
91
static gchar* run_components = NULL;
92
static gchar* login_password = NULL;
93
static gboolean initialization_completed = FALSE;
94
static gboolean sig_thread_valid = FALSE;
95
static pthread_t sig_thread;
97
static GOptionEntry option_entries[] = {
98
{ "foreground", 'f', 0, G_OPTION_ARG_NONE, &run_foreground,
99
"Run in the foreground", NULL },
100
{ "daemonize", 'd', 0, G_OPTION_ARG_NONE, &run_daemonized,
101
"Run as a daemon", NULL },
102
{ "login", 'l', 0, G_OPTION_ARG_NONE, &run_for_login,
103
"Run for a user login. Read login password from stdin", NULL },
104
{ "start", 's', 0, G_OPTION_ARG_NONE, &run_for_start,
105
"Start a dameon or initialize an already running daemon." },
106
{ "components", 'c', 0, G_OPTION_ARG_STRING, &run_components,
107
"The optional components to run", DEFAULT_COMPONENTS },
112
parse_arguments (int *argc, char** argv[])
115
GOptionContext *context;
117
context = g_option_context_new ("- The Gnome Keyring Daemon");
118
g_option_context_add_main_entries (context, option_entries, GETTEXT_PACKAGE);
120
if (!g_option_context_parse (context, argc, argv, &err)) {
121
g_printerr ("gnome-keyring-daemon: %s", err && err->message ? err->message : "");
122
g_clear_error (&err);
125
/* Take ownership of the string */
126
if (run_components) {
127
run_components = g_strdup (run_components);
128
egg_cleanup_register (g_free, run_components);
131
/* Check the arguments */
132
if (run_for_login && run_for_start) {
133
g_printerr ("gnome-keyring-daemon: The --start option is incompatible with --login");
134
run_for_login = FALSE;
138
g_option_context_free (context);
142
check_conf_component (const gchar* component, gboolean *enabled)
151
client = gconf_client_get_default ();
152
g_return_val_if_fail (client, FALSE);
154
key = g_strdup_printf ("/apps/gnome-keyring/daemon-components/%s", component);
155
value = gconf_client_get (client, key, &err);
157
g_object_unref (client);
160
g_printerr ("gnome-keyring-daemon: couldn't lookup %s component setting: %s",
161
component, err->message ? err->message : "");
162
g_clear_error (&err);
170
/* Should be a list of type string */
171
if (value->type != GCONF_VALUE_BOOL) {
172
g_printerr ("gnome-keyring-daemon: bad gconf value type for daemon-components");
173
g_clear_error (&err);
174
gconf_value_free (value);
178
*enabled = gconf_value_get_bool (value);
179
gconf_value_free (value);
184
check_run_component (const char* component)
186
const gchar *run = run_components;
191
/* Use gconf to determine whether the component should be enabled */
192
if (check_conf_component (component, &enabled))
195
/* No gconf, error or unset, use built in defaults */
196
run = DEFAULT_COMPONENTS;
200
* Note that this assumes that no components are substrings of
201
* one another. Which makes things quick, and simple.
203
return strstr (run, component) ? TRUE : FALSE;
206
/* -----------------------------------------------------------------------------
210
static gboolean do_warning = TRUE;
211
#define WARNING "couldn't allocate secure memory to keep passwords " \
212
"and or keys from being written to the disk"
214
#define ABORTMSG "The GNOME_KEYRING_PARANOID environment variable was set. " \
219
* These are called from gkr-secure-memory.c to provide appropriate
220
* locking for memory between threads
224
egg_memory_lock (void)
226
/* The daemon uses cooperative threading, and doesn't need locking */
230
egg_memory_unlock (void)
232
/* The daemon uses cooperative threading, and doesn't need locking */
236
egg_memory_fallback (void *p, size_t sz)
240
/* We were asked to free memory */
246
/* We were asked to allocate */
253
env = g_getenv ("GNOME_KEYRING_PARANOID");
257
return g_malloc0 (sz);
261
* Reallocation is a bit of a gray area, as we can be asked
262
* by external libraries (like libgcrypt) to reallocate a
263
* non-secure block into secure memory. We cannot satisfy
264
* this request (as we don't know the size of the original
265
* block) so we just try our best here.
268
return g_realloc (p, sz);
271
/* -----------------------------------------------------------------------------
276
log_handler (const gchar *log_domain, GLogLevelFlags log_level,
277
const gchar *message, gpointer user_data)
281
/* Note that crit and err are the other way around in syslog */
283
switch (G_LOG_LEVEL_MASK & log_level) {
284
case G_LOG_LEVEL_ERROR:
287
case G_LOG_LEVEL_CRITICAL:
290
case G_LOG_LEVEL_WARNING:
293
case G_LOG_LEVEL_MESSAGE:
296
case G_LOG_LEVEL_INFO:
299
case G_LOG_LEVEL_DEBUG:
307
/* Log to syslog first */
309
syslog (level, "%s: %s", log_domain, message);
311
syslog (level, "%s", message);
313
/* And then to default handler for aborting and stuff like that */
314
g_log_default_handler (log_domain, log_level, message, user_data);
318
printerr_handler (const gchar *string)
320
/* Print to syslog and stderr */
321
syslog (LOG_WARNING, "%s", string);
322
fprintf (stderr, "%s", string);
328
GLogLevelFlags flags = G_LOG_FLAG_FATAL | G_LOG_LEVEL_ERROR |
329
G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING |
330
G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO;
332
openlog ("gnome-keyring-daemon", LOG_PID, LOG_AUTH);
334
g_log_set_handler (NULL, flags, log_handler, NULL);
335
g_log_set_handler ("Glib", flags, log_handler, NULL);
336
g_log_set_handler ("Gtk", flags, log_handler, NULL);
337
g_log_set_handler ("Gnome", flags, log_handler, NULL);
338
g_log_set_default_handler (log_handler, NULL);
339
g_set_printerr_handler (printerr_handler);
342
/* -----------------------------------------------------------------------------
346
static sigset_t signal_set;
347
static gint signal_quitting = 0;
350
signal_thread (gpointer user_data)
352
GMainLoop *loop = user_data;
356
err = sigwait (&signal_set, &sig);
357
if (err != EINTR && err != 0) {
358
g_warning ("couldn't wait for signals: %s", g_strerror (err));
369
g_atomic_int_set (&signal_quitting, 1);
370
g_main_loop_quit (loop);
373
g_warning ("received unexpected signal when waiting for signals: %d", sig);
378
g_assert_not_reached ();
383
setup_signal_handling (GMainLoop *loop)
388
* Block these signals for this thread, and any threads
389
* started up after this point (so essentially all threads).
391
* We also start a signal handling thread which uses signal_set
392
* to catch the various signals we're interested in.
395
sigemptyset (&signal_set);
396
sigaddset (&signal_set, SIGPIPE);
397
sigaddset (&signal_set, SIGINT);
398
sigaddset (&signal_set, SIGHUP);
399
sigaddset (&signal_set, SIGTERM);
400
pthread_sigmask (SIG_BLOCK, &signal_set, NULL);
402
res = pthread_create (&sig_thread, NULL, signal_thread, loop);
404
sig_thread_valid = TRUE;
406
g_warning ("couldn't startup thread for signal handling: %s",
412
gkr_daemon_quit (void)
415
* Send a signal to terminate our signal thread,
416
* which in turn runs stops the main loop and that
417
* starts the shutdown process.
420
if (sig_thread_valid)
421
pthread_kill (sig_thread, SIGTERM);
427
cleanup_signal_handling (void)
429
/* The thread is not joinable, so cleans itself up */
430
if (!g_atomic_int_get (&signal_quitting))
431
g_warning ("gkr_daemon_quit() was not used to shutdown the daemon");
434
/* -----------------------------------------------------------------------------
439
sane_dup2 (int fd1, int fd2)
444
ret = dup2 (fd1, fd2);
445
if (ret < 0 && errno == EINTR)
452
read_login_password (int fd)
454
/* We only accept a max of 8K as the login password */
455
#define MAX_LENGTH 8192
456
#define MAX_BLOCK 256
459
* When --login is specified then the login password is passed
460
* in on stdin. All data (including newlines) are part of the
464
gchar *buf = egg_secure_alloc (MAX_BLOCK);
469
r = read (fd, buf, sizeof (buf));
473
egg_secure_free (ret);
474
egg_secure_free (buf);
478
char *n = egg_secure_realloc (ret, len + r + 1);
479
memset(n + len, 0, r + 1);
483
strncat (ret, buf, r);
486
if (r == 0 || len > MAX_LENGTH)
490
egg_secure_free (buf);
495
cleanup_and_exit (int code)
497
egg_cleanup_perform ();
502
clear_login_password (void)
505
egg_secure_strfree (login_password);
506
login_password = NULL;
510
lifetime_slave_pipe_io (GIOChannel *channel,
512
gpointer callback_data)
514
egg_cleanup_perform ();
520
slave_lifetime_to_fd (void)
526
env = getenv ("GNOME_KEYRING_LIFETIME_FD");
530
channel = g_io_channel_unix_new (fd);
531
g_io_add_watch (channel,
533
lifetime_slave_pipe_io, NULL);
534
g_io_channel_unref (channel);
540
print_environment (pid_t pid)
543
for (env = gkr_daemon_util_get_environment (); *env; ++env)
544
printf ("%s\n", *env);
546
printf ("GNOME_KEYRING_PID=%d\n", (gint)pid);
550
initialize_other_running_daemon (int sock)
552
GnomeKeyringResult res;
557
if (egg_unix_credentials_write (sock) < 0)
560
egg_buffer_init_full (&buf, 128, g_realloc);
562
envp = gnome_keyring_build_environment (GNOME_KEYRING_IN_ENVIRONMENT);
563
ret = gkr_proto_encode_prepare_environment (&buf, (const gchar**)envp);
567
egg_buffer_uninit (&buf);
568
g_return_val_if_reached (FALSE);
573
ret = gnome_keyring_socket_write_buffer (sock, &buf) &&
574
gnome_keyring_socket_read_buffer (sock, &buf) &&
575
gkr_proto_decode_prepare_environment_reply (&buf, &res, &envp);
578
egg_buffer_uninit (&buf);
581
g_warning ("couldn't initialize running daemon");
585
if (res == GNOME_KEYRING_RESULT_OK) {
586
g_return_val_if_fail (envp, FALSE);
587
for (e = envp; *e; ++e)
588
gkr_daemon_util_push_environment_full (*e);
591
g_warning ("couldn't initialize running daemon: %s", gnome_keyring_result_to_message (res));
601
start_or_initialize_daemon (void)
607
* Is a daemon already running? If not we need to run
608
* a daemon process, just return and let things go
611
sock = gnome_keyring_socket_connect_daemon (FALSE, TRUE);
615
ret = initialize_other_running_daemon (sock);
618
/* Initialization failed, start this process up as a daemon */
623
* Now we've initialized the daemon, we need to print out
624
* the daemon's environment for any callers, and possibly
625
* block if we've been asked to remain in the foreground.
627
print_environment (0);
629
/* TODO: Better way to sleep forever? */
630
if (run_foreground) {
631
while (sleep(0x08000000) == 0);
638
fork_and_print_environment (void)
644
if (run_foreground) {
645
print_environment (getpid ());
653
/* Here we are in the initial process */
655
if (run_daemonized) {
657
/* Initial process, waits for intermediate child */
661
waitpid (pid, &status, 0);
662
if (WEXITSTATUS (status) != 0)
663
exit (WEXITSTATUS (status));
666
/* Not double forking, we know the PID */
667
print_environment (pid);
670
/* The initial process exits successfully */
674
if (run_daemonized) {
676
/* Double fork if need to daemonize properly */
681
/* Here we are in the intermediate child process */
684
* This process exits, so that the final child will inherit
685
* init as parent to avoid zombies
690
/* We've done two forks. Now we know the PID */
691
print_environment (pid);
693
/* The intermediate child exits */
699
/* Here we are in the resulting daemon or background process. */
701
for (i = 0; i < 3; ++i) {
702
fd = open ("/dev/null", O_RDONLY);
709
gkr_daemon_startup_steps (void)
711
/* Startup the appropriate components, creates sockets etc.. */
713
if (check_run_component ("ssh")) {
714
if (!gkr_pkcs11_daemon_startup_ssh ())
719
if (check_run_component ("pkcs11")) {
720
if (!gkr_pkcs11_daemon_startup_pkcs11 ())
728
gkr_daemon_initialize_steps (void)
730
/* Initialize new style PKCS#11 components */
731
if (!gkr_pkcs11_daemon_initialize ())
734
gkr_daemon_dbus_initialize ();
739
gkr_daemon_complete_initialization (void)
742
* Sometimes we don't initialize the full daemon right on
743
* startup. When run with --login is one such case.
746
if (initialization_completed) {
747
g_message ("The daemon was already initialized.");
751
/* Set this early so that two initializations don't overlap */
752
initialization_completed = TRUE;
753
gkr_daemon_startup_steps ();
754
gkr_daemon_initialize_steps ();
758
main (int argc, char *argv[])
764
* The gnome-keyring startup is not as simple as I wish it could be.
766
* It's often started in the primidoral stages of a session, where
767
* there's no DBus, no GConf, and no proper X display. This is the
768
* strange world of PAM.
770
* When started with the --login option, we do as little initialization
771
* as possible. We expect a login password on the stdin, and unlock
772
* or create the login keyring.
774
* Then later we expect gnome-keyring-dameon to be run again with the
775
* --start option. This second gnome-keyring-daemon will hook the
776
* original daemon up with environment variables necessary to initialize
777
* itself and bring it into the session. This second daemon usually exits.
779
* Without either of these options, we follow a more boring and
780
* predictable startup.
784
g_thread_init (NULL);
787
/* internationalisation */
788
setlocale (LC_ALL, "");
792
bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
793
textdomain (GETTEXT_PACKAGE);
794
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
797
egg_libgcrypt_initialize ();
799
/* Send all warning or error messages to syslog */
802
parse_arguments (&argc, &argv);
804
/* The --start option */
806
if (start_or_initialize_daemon ())
807
cleanup_and_exit (0);
810
/* Initialize our daemon main loop and threading */
811
loop = g_main_loop_new (NULL, FALSE);
812
ctx = g_main_loop_get_context (loop);
813
gkr_daemon_async_workers_init (loop);
816
* Always initialize the keyring subsystem. This is a necessary
817
* component that everything else depends on in one way or
820
if (!gkr_daemon_io_create_master_socket ())
821
cleanup_and_exit (1);
823
/* The --login option. Delayed initialization */
825
login_password = read_login_password (STDIN);
826
atexit (clear_login_password);
828
/* Not a login daemon. Startup stuff now.*/
830
/* These are things that can run before forking */
831
if (!gkr_daemon_startup_steps ())
832
cleanup_and_exit (1);
835
/* The whole forking and daemonizing dance starts here. */
836
fork_and_print_environment();
838
setup_signal_handling (loop);
840
/* Prepare logging a second time, since we may be in a different process */
843
/* Remainder initialization after forking, if initialization not delayed */
844
if (!run_for_login) {
845
initialization_completed = TRUE;
846
gkr_daemon_initialize_steps ();
849
/* TODO: Do we still need this? XFCE still seems to use it. */
850
slave_lifetime_to_fd ();
853
* Unlock the login keyring if we were given a password on STDIN.
854
* If it does not exist. We create it.
856
if (login_password) {
857
if (!gkr_keyring_login_unlock (login_password))
858
g_message ("Failed to unlock login on startup");
859
egg_secure_strclear (login_password);
862
g_main_loop_run (loop);
864
/* Make sure no other threads are running */
865
gkr_daemon_async_workers_stop_all ();
867
/* This wraps everything up in order */
868
egg_cleanup_perform ();
870
/* Final shutdown of anything workers running about */
871
gkr_daemon_async_workers_uninit ();
873
/* Wrap up signal handling here */
874
cleanup_signal_handling ();