summaryrefslogtreecommitdiff
path: root/daemon/gkr-daemon.c
blob: 3b2f7a2a0354a8be2b5beb2b9c9e73313a231f9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
/* gnome-keyring-daemon.c - main keyring daemon code.

   Copyright (C) 2003 Red Hat, Inc

   Gnome keyring is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.
  
   Gnome keyring is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.
  
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

   Author: Alexander Larsson <alexl@redhat.com>
*/

#include "config.h"

#include "gkr-daemon.h"

#include "common/gkr-async.h"
#include "common/gkr-cleanup.h"
#include "common/gkr-crypto.h"
#include "common/gkr-daemon-util.h"
#include "common/gkr-secure-memory.h"
#include "common/gkr-unix-credentials.h"
#include "common/gkr-unix-signal.h"

#include "keyrings/gkr-keyring-login.h"

#include "library/gnome-keyring.h"

#include "pkcs11/gkr-pkcs11-daemon.h"

#include "ui/gkr-ask-daemon.h"

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <locale.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/wait.h>

#include <glib.h>
#include <glib/gi18n.h>

#include <gconf/gconf.h>
#include <gconf/gconf-client.h>

#include <gcrypt.h>

/* preset file descriptors */
#define  STDIN   0
#define  STDOUT  1
#define  STDERR  2

static GMainLoop *loop = NULL;

#ifndef HAVE_SOCKLEN_T
#define socklen_t int
#endif

/* -----------------------------------------------------------------------------
 * COMMAND LINE
 */

/* All the components to run on startup if not set in gconf */
#ifdef WITH_SSH
#define DEFAULT_COMPONENTS  "ssh,pkcs11"
#else
#define DEFAULT_COMPONENTS  "pkcs11"
#endif

static gboolean run_foreground = FALSE;
static gboolean run_daemonized = FALSE;
static gboolean run_for_login = FALSE;
static gboolean run_for_start = FALSE;
static gchar* run_components = NULL;
static gchar* login_password = NULL;
static gboolean initialization_completed = FALSE;

static GOptionEntry option_entries[] = {
	{ "foreground", 'f', 0, G_OPTION_ARG_NONE, &run_foreground, 
	  "Run in the foreground", NULL }, 
	{ "daemonize", 'd', 0, G_OPTION_ARG_NONE, &run_daemonized, 
	  "Run as a daemon", NULL }, 
	{ "login", 'l', 0, G_OPTION_ARG_NONE, &run_for_login, 
	  "Run for a user login. Read login password from stdin", NULL },
	{ "start", 's', 0, G_OPTION_ARG_NONE, &run_for_start,
	  "Start a dameon or initialize an already running daemon." },
	{ "components", 'c', 0, G_OPTION_ARG_STRING, &run_components,
	  "The optional components to run", DEFAULT_COMPONENTS },
	{ NULL }
};

static void
parse_arguments (int *argc, char** argv[])
{
	GError *err = NULL;
	GOptionContext *context;
	
	context = g_option_context_new ("- The Gnome Keyring Daemon");
	g_option_context_add_main_entries (context, option_entries, GETTEXT_PACKAGE);
	
	if (!g_option_context_parse (context, argc, argv, &err)) {
		g_printerr ("gnome-keyring-daemon: %s", err && err->message ? err->message : "");
		g_clear_error (&err);
	}
	
	/* Take ownership of the string */
	if (run_components) {
		run_components = g_strdup (run_components);
		gkr_cleanup_register (g_free, run_components);
	}
	
	/* Check the arguments */
	if (run_for_login && run_for_start) {
		g_printerr ("gnome-keyring-daemon: The --start option is incompatible with --login");
		run_for_login = FALSE;
	}
		
	
	g_option_context_free (context);
}

static gboolean
check_conf_component (const gchar* component, gboolean *enabled)
{
	GConfClient *client;
	GConfValue *value;
	GError *err = NULL;
	gchar *key; 

	*enabled = FALSE;

	client = gconf_client_get_default ();
	g_return_val_if_fail (client, FALSE);
	
	key = g_strdup_printf ("/apps/gnome-keyring/daemon-components/%s", component);
	value = gconf_client_get (client, key, &err);
	g_free (key);
	g_object_unref (client);
	
	if (err) {
		g_printerr ("gnome-keyring-daemon: couldn't lookup %s component setting: %s", 
		            component, err->message ? err->message : "");
		g_clear_error (&err);
		return FALSE;
	}
	
	/* Value is unset */
	if (!value)
		return FALSE;		
	
	/* Should be a list of type string */
	if (value->type != GCONF_VALUE_BOOL) {
	    	g_printerr ("gnome-keyring-daemon: bad gconf value type for daemon-components");
	    	g_clear_error (&err);
	    	gconf_value_free (value);
	    	return FALSE;
	}
	
	*enabled = gconf_value_get_bool (value);
	gconf_value_free (value);
	return TRUE;
}

static gboolean
check_run_component (const char* component)
{
	const gchar *run = run_components;
	gboolean enabled;

	if (run == NULL) {

		/* Use gconf to determine whether the component should be enabled */	
		if (check_conf_component (component, &enabled))
			return enabled;
			
		/* No gconf, error or unset, use built in defaults */
		run = DEFAULT_COMPONENTS;
	}
	
	/* 
	 * Note that this assumes that no components are substrings of 
	 * one another. Which makes things quick, and simple.
	 */
	return strstr (run, component) ? TRUE : FALSE;
}

/* -----------------------------------------------------------------------------
 * MEMORY
 */

static gboolean do_warning = TRUE;
#define WARNING  "couldn't allocate secure memory to keep passwords " \
		 "and or keys from being written to the disk"
		 
#define ABORTMSG "The GNOME_KEYRING_PARANOID environment variable was set. " \
                 "Exiting..."


/* 
 * These are called from gkr-secure-memory.c to provide appropriate
 * locking for memory between threads
 */ 

void
gkr_memory_lock (void)
{
	/* The daemon uses cooperative threading, and doesn't need locking */
}

void 
gkr_memory_unlock (void)
{
	/* The daemon uses cooperative threading, and doesn't need locking */
}

void*
gkr_memory_fallback (void *p, unsigned long sz)
{
	const gchar *env;
	
	/* We were asked to free memory */
	if (!sz) {
		g_free (p);
		return NULL;
	}
	
	/* We were asked to allocate */
	if (!p) {
		if (do_warning) {
			g_message (WARNING);
			do_warning = FALSE;
		}
		
		env = g_getenv ("GNOME_KEYRING_PARANOID");
		if (env && *env) 
			g_error (ABORTMSG);
			
		return g_malloc0 (sz);
	}
	
	/* 
	 * Reallocation is a bit of a gray area, as we can be asked 
	 * by external libraries (like libgcrypt) to reallocate a 
	 * non-secure block into secure memory. We cannot satisfy 
	 * this request (as we don't know the size of the original 
	 * block) so we just try our best here.
	 */
			 
	return g_realloc (p, sz);
}

/* -----------------------------------------------------------------------------
 * LOGS
 */

static void
log_handler (const gchar *log_domain, GLogLevelFlags log_level, 
             const gchar *message, gpointer user_data)
{
    int level;

    /* Note that crit and err are the other way around in syslog */
        
    switch (G_LOG_LEVEL_MASK & log_level) {
    case G_LOG_LEVEL_ERROR:
        level = LOG_CRIT;
        break;
    case G_LOG_LEVEL_CRITICAL:
        level = LOG_ERR;
        break;
    case G_LOG_LEVEL_WARNING:
        level = LOG_WARNING;
        break;
    case G_LOG_LEVEL_MESSAGE:
        level = LOG_NOTICE;
        break;
    case G_LOG_LEVEL_INFO:
        level = LOG_INFO;
        break;
    case G_LOG_LEVEL_DEBUG:
        level = LOG_DEBUG;
        break;
    default:
        level = LOG_ERR;
        break;
    }
    
    /* Log to syslog first */
    if (log_domain)
        syslog (level, "%s: %s", log_domain, message);
    else
        syslog (level, "%s", message);
 
    /* And then to default handler for aborting and stuff like that */
    g_log_default_handler (log_domain, log_level, message, user_data); 
}

static void
prepare_logging ()
{
    GLogLevelFlags flags = G_LOG_FLAG_FATAL | G_LOG_LEVEL_ERROR | 
                G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | 
                G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO;
                
    openlog ("gnome-keyring-daemon", LOG_PID, LOG_AUTH);
    
    g_log_set_handler (NULL, flags, log_handler, NULL);
    g_log_set_handler ("Glib", flags, log_handler, NULL);
    g_log_set_handler ("Gtk", flags, log_handler, NULL);
    g_log_set_handler ("Gnome", flags, log_handler, NULL);
    g_log_set_default_handler (log_handler, NULL);
}

void
gkr_daemon_quit (void)
{
	g_main_loop_quit (loop);
}

static gboolean
signal_handler (guint sig, gpointer unused)
{
	gkr_daemon_quit ();
	return TRUE;
}

static int
sane_dup2 (int fd1, int fd2)
{
	int ret;

 retry:
	ret = dup2 (fd1, fd2);
	if (ret < 0 && errno == EINTR)
		goto retry;
	
	return ret;
}

static gchar*
read_login_password (int fd)
{
	/* We only accept a max of 8K as the login password */
	#define MAX_LENGTH 8192
	#define MAX_BLOCK 256

	/* 
	 * When --login is specified then the login password is passed 
	 * in on stdin. All data (including newlines) are part of the 
	 * password.
	 */
	
	gchar *buf = gkr_secure_alloc (MAX_BLOCK);
	gchar *ret = NULL;
	int r, len = 0;
	
	for (;;) {
		r = read (fd, buf, sizeof (buf));
		if (r < 0) {
			if (errno == EAGAIN)
				continue;
			gkr_secure_free (ret);
			gkr_secure_free (buf);
			return NULL;
			
		} else  { 
			char *n = gkr_secure_realloc (ret, len + r + 1);
			memset(n + len, 0, r + 1); 
			ret = n;
			len = len + r;
			
			strncat (ret, buf, r);
		}
		
		if (r == 0 || len > MAX_LENGTH)
			break;
	}
	
	gkr_secure_free (buf);
	return ret;
}

static void
cleanup_and_exit (int code)
{
	gkr_cleanup_perform ();
	exit (code);
}

static void
clear_login_password (void)
{
	if(login_password)
		gkr_secure_strfree (login_password);
	login_password = NULL;
}

static gboolean
lifetime_slave_pipe_io (GIOChannel  *channel,
			GIOCondition cond,
			gpointer     callback_data)
{
	gkr_cleanup_perform ();
	_exit (2);
	return FALSE;
}

static void
slave_lifetime_to_fd (void)
{
	const char *env;
	GIOChannel *channel;
	int fd;
	
	env = getenv ("GNOME_KEYRING_LIFETIME_FD");
	if (env && env[0]) {
		fd = atoi (env);
		if (fd != 0) {
			channel = g_io_channel_unix_new (fd);
			g_io_add_watch (channel,
					G_IO_IN | G_IO_HUP,
					lifetime_slave_pipe_io, NULL);
			g_io_channel_unref (channel);
		}
	}
}

static void
print_environment (pid_t pid)
{
	const gchar **env;
	for (env = gkr_daemon_util_get_environment (); *env; ++env)
		printf ("%s\n", *env);
	if (pid)
		printf ("GNOME_KEYRING_PID=%d\n", (gint)pid);
}

static gboolean
initialize_other_running_daemon (int sock)
{
	GnomeKeyringResult res;
	gchar **envp, **e;
	GkrBuffer buf;
	gboolean ret;
	
	if (gkr_unix_credentials_write (sock) < 0)
		return FALSE;

	gkr_buffer_init_full (&buf, 128, (GkrBufferAllocator)g_realloc);
	
	envp = gnome_keyring_build_environment (GNOME_KEYRING_IN_ENVIRONMENT);
	ret = gkr_proto_encode_prepare_environment (&buf, (const gchar**)envp);
	g_strfreev (envp);
	
	if (!ret) {
		gkr_buffer_uninit (&buf);
		g_return_val_if_reached (FALSE);
	}

	envp = NULL;

	ret = gnome_keyring_socket_write_buffer (sock, &buf) && 
	      gnome_keyring_socket_read_buffer (sock, &buf) && 
	      gkr_proto_decode_prepare_environment_reply (&buf, &res, &envp);
	
	
	gkr_buffer_uninit (&buf);
	
	if(!ret) {
		g_warning ("couldn't initialize running daemon");
		return FALSE;
	}

	if (res == GNOME_KEYRING_RESULT_OK) {
		g_return_val_if_fail (envp, FALSE);
		for (e = envp; *e; ++e)
			gkr_daemon_util_push_environment_full (*e);
		ret = TRUE;
	} else {
		g_warning ("couldn't initialize running daemon: %s", gnome_keyring_result_to_message (res));
		ret = FALSE;
	}
	
	g_strfreev (envp);

	return ret;
}

static gboolean
start_or_initialize_daemon (void)
{
	gboolean ret;
	int sock;
	
	/* 
	 * Is a daemon already running? If not we need to run
	 * a daemon process, just return and let things go 
	 * their normal way. 
	 */
	sock = gnome_keyring_socket_connect_daemon (FALSE, TRUE);
	if (sock == -1)
		return FALSE;
	
	ret = initialize_other_running_daemon (sock);
	close (sock);
	
	/* Initialization failed, start this process up as a daemon */
	if (!ret)
		return FALSE;
	
	/* 
	 * Now we've initialized the daemon, we need to print out 
	 * the daemon's environment for any callers, and possibly
	 * block if we've been asked to remain in the foreground.
	 */
	print_environment (0);
	
	/* TODO: Better way to sleep forever? */
	if (run_foreground) {
		while (sleep(0x08000000) == 0);
	}
	
	return TRUE;
}

static void
fork_and_print_environment (void)
{
	int status;
	pid_t pid;
	int fd, i;

	if (run_foreground) {
		print_environment (getpid ());
		return;
	}
	
	pid = fork ();
		
	if (pid != 0) {

		/* Here we are in the initial process */

		if (run_daemonized) {
			
			/* Initial process, waits for intermediate child */
			if (pid == -1)
				exit (1);

			waitpid (pid, &status, 0);
			if (WEXITSTATUS (status) != 0)
				exit (WEXITSTATUS (status));
			
		} else {
			/* Not double forking, we know the PID */
			print_environment (pid);
		}

		/* The initial process exits successfully */
		exit (0);
	}
	
	if (!run_daemonized) 
		return;
	
	/* Double fork if need to daemonize properly */
	pid = fork ();
	
	if (pid != 0) {

		/* Here we are in the intermediate child process */
			
		/* 
		 * This process exits, so that the final child will inherit 
		 * init as parent to avoid zombies
		 */
		if (pid == -1)
			exit (1);

		/* We've done two forks. Now we know the PID */
		print_environment (pid);
			
		/* The intermediate child exits */
		exit (0);
	}

	/* Here we are in the resulting daemon process. */

	for (i = 0; i < 3; ++i) {
		fd = open ("/dev/null", O_RDONLY);
		sane_dup2 (fd, i);
		close (fd);
	}
}

gboolean
gkr_daemon_complete_initialization(void)
{
	/*
	 * Sometimes we don't initialize the full daemon right on 
	 * startup. When run with --login is one such case.
	 */
	
	if (initialization_completed) {
		g_message ("The daemon was already initialized.");
		return TRUE;
	}
	
	/* Initialize new style PKCS#11 components */
	if (!gkr_pkcs11_daemon_initialize ())
		return FALSE;
	
	/* Initialize the appropriate components */
	
#ifdef WITH_SSH	
	if (check_run_component ("ssh")) {
		if (!gkr_pkcs11_daemon_setup_ssh ())
			return FALSE;
	}
#endif
	
	if (check_run_component ("pkcs11")) {
		if (!gkr_pkcs11_daemon_setup_pkcs11 ())
			return FALSE;
	}
	
	gkr_daemon_dbus_setup ();
	
	initialization_completed = TRUE;
	return TRUE;
}

int
main (int argc, char *argv[])
{
	GMainContext *ctx;
	
	/* 
	 * The gnome-keyring startup is not as simple as I wish it could be. 
	 * 
	 * It's often started in the primidoral stages of a session, where 
	 * there's no DBus, no GConf, and no proper X display. This is the 
	 * strange world of PAM.
	 * 
	 * When started with the --login option, we do as little initialization
	 * as possible. We expect a login password on the stdin, and unlock
	 * or create the login keyring.
	 * 
	 * Then later we expect gnome-keyring-dameon to be run again with the 
	 * --start option. This second gnome-keyring-daemon will hook the
	 * original daemon up with environment variables necessary to initialize
	 * itself and bring it into the session. This second daemon usually exits.
	 * 
	 * Without either of these options, we follow a more boring and 
	 * predictable startup.  
	 */
	
	g_type_init ();
	g_thread_init (NULL);
	
#ifdef HAVE_LOCALE_H
	/* internationalisation */
	setlocale (LC_ALL, "");
#endif

#ifdef HAVE_GETTEXT
	bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
	textdomain (GETTEXT_PACKAGE);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif

	gkr_crypto_setup ();

	/* Send all warning or error messages to syslog */
	prepare_logging ();
	
	parse_arguments (&argc, &argv);
	
	/* The --start option */
	if (run_for_start) {
		if (start_or_initialize_daemon ())
			cleanup_and_exit (0);
	} 

	/* Initialize our daemon main loop and threading */
	loop = g_main_loop_new (NULL, FALSE);
	ctx = g_main_loop_get_context (loop);
	gkr_async_workers_init (loop);
	
	/* 
	 * Always initialize the keyring subsystem. This is a necessary
	 * component that everything else depends on in one way or 
	 * another. 
	 */
	if (!gkr_daemon_io_create_master_socket ())
		cleanup_and_exit (1);

	/* The --login option. Delayed initialization */
	if (run_for_login) {
		login_password = read_login_password (STDIN);
		atexit (clear_login_password);
	
	/* Not a login daemon. Initialize now. */
	} else {
		if (!gkr_daemon_complete_initialization ())
			cleanup_and_exit (1);
	}
	 
	/* The whole forking and daemonizing dance starts here. */
	fork_and_print_environment();

	/* Prepare logging a second time, since we may be in a different process */
	prepare_logging();

	signal (SIGPIPE, SIG_IGN);
	gkr_unix_signal_connect (ctx, SIGINT, signal_handler, NULL);
	gkr_unix_signal_connect (ctx, SIGHUP, signal_handler, NULL);
	gkr_unix_signal_connect (ctx, SIGTERM, signal_handler, NULL);
             
	/* TODO: Do we still need this? XFCE still seems to use it. */
	slave_lifetime_to_fd ();

	/*
	 * Unlock the login keyring if we were given a password on STDIN.
	 * If it does not exist. We create it. 
	 */
	if (login_password) {
		if (!gkr_keyring_login_unlock (login_password))
			g_warning ("Failed to unlock login on startup");
		gkr_secure_strclear (login_password);
	}
	
	g_main_loop_run (loop);

	/* Make sure no other threads are running */
	gkr_async_workers_stop_all ();
	
	/* This wraps everything up in order */
	gkr_cleanup_perform ();
	
	/* Final shutdown of anything workers running about */
	gkr_async_workers_uninit ();

	return 0;
}