1
/* scdaemon.c - The GnuPG Smartcard Daemon
2
* Copyright (C) 2001, 2002, 2004 Free Software Foundation, Inc.
4
* This file is part of GnuPG.
6
* GnuPG is free software; you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation; either version 2 of the License, or
9
* (at your option) any later version.
11
* GnuPG 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
14
* GNU 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
32
#ifndef HAVE_W32_SYSTEM
33
#include <sys/socket.h>
35
#endif /*HAVE_W32_SYSTEM*/
42
#define JNLIB_NEED_LOG_LOGV
47
#include <assuan.h> /* malloc hooks */
51
#include "app-common.h"
52
#ifdef HAVE_W32_SYSTEM
53
#include "../jnlib/w32-afunix.h"
57
enum cmd_and_opt_values
94
static ARGPARSE_OPTS opts[] = {
96
{ aGPGConfList, "gpgconf-list", 256, "@" },
98
{ 301, NULL, 0, N_("@Options:\n ") },
100
{ oServer, "server", 0, N_("run in server mode (foreground)") },
101
{ oDaemon, "daemon", 0, N_("run in daemon mode (background)") },
102
{ oVerbose, "verbose", 0, N_("verbose") },
103
{ oQuiet, "quiet", 0, N_("be somewhat more quiet") },
104
{ oSh, "sh", 0, N_("sh-style command output") },
105
{ oCsh, "csh", 0, N_("csh-style command output") },
106
{ oOptions, "options" , 2, N_("read options from file")},
107
{ oDebug, "debug" ,4|16, "@"},
108
{ oDebugAll, "debug-all" ,0, "@"},
109
{ oDebugLevel, "debug-level" ,2, "@"},
110
{ oDebugWait,"debug-wait",1, "@"},
111
{ oDebugSC, "debug-sc", 1, N_("|N|set OpenSC debug level to N")},
112
{ oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
113
{ oLogFile, "log-file" ,2, N_("use a log file for the server")},
114
{ oReaderPort, "reader-port", 2, N_("|N|connect to reader at port N")},
115
{ octapiDriver, "ctapi-driver", 2, N_("|NAME|use NAME as ct-API driver")},
116
{ opcscDriver, "pcsc-driver", 2, N_("|NAME|use NAME as PC/SC driver")},
117
{ oDisableCCID, "disable-ccid", 0,
119
N_("do not use the internal CCID driver")
123
/* end --disable-ccid */},
124
{ oDisableOpenSC, "disable-opensc", 0,
126
N_("do not use the OpenSC layer")
130
/* end --disable-opensc */},
131
{ oAllowAdmin, "allow-admin", 0, N_("allow the use of admin card commands")},
132
{ oDenyAdmin, "deny-admin", 0, "@" },
133
{ oDisableApplication, "disable-application", 2, "@"},
139
/* The card dirver we use by default for PC/SC. */
140
#ifdef HAVE_W32_SYSTEM
141
#define DEFAULT_PCSC_DRIVER "winscard.dll"
143
#define DEFAULT_PCSC_DRIVER "libpcsclite.so"
147
static volatile int caught_fatal_sig = 0;
149
/* Flag to indicate that a shutdown was requested. */
150
static int shutdown_pending;
152
/* It is possible that we are currently running under setuid permissions */
153
static int maybe_setuid = 1;
155
/* Name of the communication socket */
156
static char socket_name[128];
161
/* Pth wrapper function definitions. */
162
GCRY_THREAD_OPTION_PTH_IMPL;
164
static void *ticker_thread (void *arg);
165
#endif /*USE_GNU_PTH*/
166
#endif /*!HAVE_OPENSC*/
169
my_strusage (int level)
174
case 11: p = "scdaemon (GnuPG)";
176
case 13: p = VERSION; break;
177
case 17: p = PRINTABLE_OS_NAME; break;
178
case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
181
case 40: p = _("Usage: scdaemon [options] (-h for help)");
183
case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
184
"Smartcard daemon for GnuPG\n");
197
#ifdef USE_SIMPLE_GETTEXT
198
set_gettext_file( PACKAGE_GT );
201
setlocale (LC_ALL, "");
202
bindtextdomain (PACKAGE_GT, LOCALEDIR);
203
textdomain (PACKAGE_GT);
210
/* Used by gcry for logging */
212
my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr)
214
/* translate the log levels */
217
case GCRY_LOG_CONT: level = JNLIB_LOG_CONT; break;
218
case GCRY_LOG_INFO: level = JNLIB_LOG_INFO; break;
219
case GCRY_LOG_WARN: level = JNLIB_LOG_WARN; break;
220
case GCRY_LOG_ERROR:level = JNLIB_LOG_ERROR; break;
221
case GCRY_LOG_FATAL:level = JNLIB_LOG_FATAL; break;
222
case GCRY_LOG_BUG: level = JNLIB_LOG_BUG; break;
223
case GCRY_LOG_DEBUG:level = JNLIB_LOG_DEBUG; break;
224
default: level = JNLIB_LOG_ERROR; break;
226
log_logv (level, fmt, arg_ptr);
230
/* Setup the debugging. With a LEVEL of NULL only the active debug
231
flags are propagated to the subsystems. With LEVEL set, a specific
232
set of debug flags is set; thus overriding all flags already
235
set_debug (const char *level)
239
else if (!strcmp (level, "none"))
241
else if (!strcmp (level, "basic"))
242
opt.debug = DBG_ASSUAN_VALUE;
243
else if (!strcmp (level, "advanced"))
244
opt.debug = DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE;
245
else if (!strcmp (level, "expert"))
246
opt.debug = (DBG_ASSUAN_VALUE|DBG_COMMAND_VALUE
247
|DBG_CACHE_VALUE|DBG_CARD_IO_VALUE);
248
else if (!strcmp (level, "guru"))
252
log_error (_("invalid debug-level `%s' given\n"), level);
257
if (opt.debug && !opt.verbose)
259
if (opt.debug && opt.quiet)
262
if (opt.debug & DBG_MPI_VALUE)
263
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
264
if (opt.debug & DBG_CRYPTO_VALUE )
265
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
266
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
278
remove (socket_name);
279
p = strrchr (socket_name, '/');
294
if (caught_fatal_sig)
296
caught_fatal_sig = 1;
298
/* gcry_control( GCRYCTL_TERM_SECMEM );*/
301
#ifndef HAVE_DOSISH_SYSTEM
302
{ /* reset action to default action and raise signal again */
303
struct sigaction nact;
304
nact.sa_handler = SIG_DFL;
305
sigemptyset( &nact.sa_mask );
307
sigaction( sig, &nact, NULL);
314
main (int argc, char **argv )
321
FILE *configfp = NULL;
322
char *configname = NULL;
324
unsigned configlineno;
326
const char *debug_level = NULL;
327
int default_config =1;
334
char *logfile = NULL;
336
int gpgconf_list = 0;
337
const char *config_filename = NULL;
339
set_strusage (my_strusage);
340
gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
341
/* Please note that we may running SUID(ROOT), so be very CAREFUL
342
when adding any stuff between here and the call to INIT_SECMEM()
343
somewhere after the option parsing */
344
log_set_prefix ("scdaemon", 1|4);
345
/* Try to auto set the character set. */
346
set_native_charset (NULL);
350
/* Libgcrypt requires us to register the threading model first.
351
Note that this will also do the pth_init. */
354
err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
357
log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
360
#endif /*USE_GNU_PTH*/
361
#endif /*!HAVE_OPENSC*/
363
/* Check that the libraries are suitable. Do it here because
364
the option parsing may need services of the library */
365
if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
367
log_fatal( _("libgcrypt is too old (need %s, have %s)\n"),
368
NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
371
ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
373
assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
374
assuan_set_assuan_log_stream (log_get_stream ());
375
assuan_set_assuan_log_prefix (log_get_prefix (NULL));
377
gcry_set_log_handler (my_gcry_logger, NULL);
378
gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
380
may_coredump = disable_core_dumps ();
382
/* Set default options. */
383
opt.pcsc_driver = DEFAULT_PCSC_DRIVER;
386
shell = getenv ("SHELL");
387
if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
390
opt.homedir = default_homedir ();
392
/* Check whether we have a config file on the commandline */
397
pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
398
while (arg_parse( &pargs, opts))
400
if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
402
else if (pargs.r_opt == oOptions)
403
{ /* yes there is one, so we do not try the default one, but
404
read the option file when it is encountered at the
408
else if (pargs.r_opt == oNoOptions)
409
default_config = 0; /* --no-options */
410
else if (pargs.r_opt == oHomedir)
411
opt.homedir = pargs.r.ret_str;
414
/* initialize the secure memory. */
415
gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
419
Now we are working under our real uid
424
configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
431
pargs.flags= 1; /* do not remove the args */
436
configfp = fopen (configname, "r");
442
log_info (_("NOTE: no default option file `%s'\n"),
447
log_error (_("option file `%s': %s\n"),
448
configname, strerror(errno) );
454
if (parse_debug && configname )
455
log_info (_("reading options from `%s'\n"), configname );
459
while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
463
case aGPGConfList: gpgconf_list = 1; break;
464
case oQuiet: opt.quiet = 1; break;
465
case oVerbose: opt.verbose++; break;
466
case oBatch: opt.batch=1; break;
468
case oDebug: opt.debug |= pargs.r.ret_ulong; break;
469
case oDebugAll: opt.debug = ~0; break;
470
case oDebugLevel: debug_level = pargs.r.ret_str; break;
471
case oDebugWait: debug_wait = pargs.r.ret_int; break;
472
case oDebugSC: opt.debug_sc = pargs.r.ret_int; break;
475
/* config files may not be nested (silently ignore them) */
479
configname = xstrdup(pargs.r.ret_str);
483
case oNoGreeting: nogreeting = 1; break;
484
case oNoVerbose: opt.verbose = 0; break;
485
case oNoOptions: break; /* no-options */
486
case oHomedir: opt.homedir = pargs.r.ret_str; break;
487
case oNoDetach: nodetach = 1; break;
488
case oLogFile: logfile = pargs.r.ret_str; break;
489
case oCsh: csh_style = 1; break;
490
case oSh: csh_style = 0; break;
491
case oServer: pipe_server = 1; break;
492
case oDaemon: is_daemon = 1; break;
494
case oReaderPort: opt.reader_port = pargs.r.ret_str; break;
495
case octapiDriver: opt.ctapi_driver = pargs.r.ret_str; break;
496
case opcscDriver: opt.pcsc_driver = pargs.r.ret_str; break;
497
case oDisableCCID: opt.disable_ccid = 1; break;
498
case oDisableOpenSC: opt.disable_opensc = 1; break;
500
case oAllowAdmin: opt.allow_admin = 1; break;
501
case oDenyAdmin: opt.allow_admin = 0; break;
503
case oDisableApplication:
504
add_to_strlist (&opt.disabled_applications, pargs.r.ret_str);
507
default : pargs.err = configfp? 1:2; break;
514
/* Keep a copy of the config name for use by --gpgconf-list. */
515
config_filename = configname;
521
if (log_get_errorcount(0))
528
fprintf (stderr, "%s %s; %s\n",
529
strusage(11), strusage(13), strusage(14) );
530
fprintf (stderr, "%s\n", strusage(15) );
532
#ifdef IS_DEVELOPMENT_VERSION
533
log_info ("NOTE: this is a development version!\n");
537
if (atexit (cleanup))
539
log_error ("atexit failed\n");
544
set_debug (debug_level);
546
if (debug_wait && pipe_server)
548
log_debug ("waiting for debugger - my pid is %u .....\n",
549
(unsigned int)getpid());
551
log_debug ("... okay\n");
556
/* List options and default values in the GPG Conf format. */
558
/* The following list is taken from gnupg/tools/gpgconf-comp.c. */
559
/* Option flags. YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING
560
FLAGS, AS THEY ARE PART OF THE EXTERNAL INTERFACE. */
561
#define GC_OPT_FLAG_NONE 0UL
562
/* The RUNTIME flag for an option indicates that the option can be
563
changed at runtime. */
564
#define GC_OPT_FLAG_RUNTIME (1UL << 3)
565
/* The DEFAULT flag for an option indicates that the option has a
567
#define GC_OPT_FLAG_DEFAULT (1UL << 4)
568
/* The DEF_DESC flag for an option indicates that the option has a
569
default, which is described by the value of the default field. */
570
#define GC_OPT_FLAG_DEF_DESC (1UL << 5)
571
/* The NO_ARG_DESC flag for an option indicates that the argument has
572
a default, which is described by the value of the ARGDEF field. */
573
#define GC_OPT_FLAG_NO_ARG_DESC (1UL << 6)
574
if (!config_filename)
575
config_filename = make_filename (opt.homedir, "scdaemon.conf", NULL );
577
printf ("gpgconf-scdaemon.conf:%lu:\"%s\n",
578
GC_OPT_FLAG_DEFAULT, config_filename);
580
printf ("verbose:%lu:\n"
582
"debug-level:%lu:\"none:\n"
589
printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE );
590
printf ("ctapi-driver:%lu:\n", GC_OPT_FLAG_NONE );
591
printf ("pcsc-driver:%lu:\"%s:\n",
592
GC_OPT_FLAG_DEFAULT, DEFAULT_PCSC_DRIVER );
594
printf ("disable-ccid:%lu:\n", GC_OPT_FLAG_NONE );
597
printf ("disable-opensc:%lu:\n", GC_OPT_FLAG_NONE );
599
printf ("allow-admin:%lu:\n", GC_OPT_FLAG_NONE );
605
/* now start with logging to a file if this is desired */
608
log_set_file (logfile);
609
log_set_prefix (NULL, 1|2|4);
614
{ /* This is the simple pipe based server */
619
tattr = pth_attr_new();
620
pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
621
pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 512*1024);
622
pth_attr_set (tattr, PTH_ATTR_NAME, "ticker");
624
if (!pth_spawn (tattr, ticker_thread, NULL))
626
log_error ("error spawning ticker thread: %s\n", strerror (errno));
629
#endif /*USE_GNU_PTH*/
630
#endif /*!HAVE_OPENSC*/
631
scd_command_handler (-1);
635
log_info (_("please use the option `--daemon'"
636
" to run the program in the background\n"));
639
{ /* regular server mode */
644
struct sockaddr_un serv_addr;
647
/* fixme: if there is already a running gpg-agent we should
648
share the same directory - and vice versa */
650
snprintf (socket_name, DIM(socket_name)-1,
651
"/tmp/gpg-XXXXXX/S.scdaemon");
652
socket_name[DIM(socket_name)-1] = 0;
653
p = strrchr (socket_name, '/');
658
#ifndef HAVE_W32_SYSTEM
659
if (!mkdtemp(socket_name))
661
log_error ("can't create directory `%s': %s\n",
662
socket_name, strerror(errno) );
668
if (strchr (socket_name, ':') )
670
log_error ("colons are not allowed in the socket name\n");
673
if (strlen (socket_name)+1 >= sizeof serv_addr.sun_path )
675
log_error ("name of socket to long\n");
680
#ifdef HAVE_W32_SYSTEM
681
fd = _w32_sock_new (AF_UNIX, SOCK_STREAM, 0);
683
fd = socket (AF_UNIX, SOCK_STREAM, 0);
687
log_error ("can't create socket: %s\n", strerror(errno) );
691
memset (&serv_addr, 0, sizeof serv_addr);
692
serv_addr.sun_family = AF_UNIX;
693
strcpy (serv_addr.sun_path, socket_name);
694
len = (offsetof (struct sockaddr_un, sun_path)
695
+ strlen(serv_addr.sun_path) + 1);
698
#ifdef HAVE_W32_SYSTEM
703
(fd, (struct sockaddr*)&serv_addr, len) == -1)
705
log_error ("error binding socket to `%s': %s\n",
706
serv_addr.sun_path, strerror (errno) );
711
if (listen (fd, 5 ) == -1)
713
log_error ("listen() failed: %s\n", strerror (errno));
719
log_info ("listening on socket `%s'\n", socket_name );
723
#ifndef HAVE_W32_SYSTEM
725
if (pid == (pid_t)-1)
727
log_fatal ("fork failed: %s\n", strerror (errno) );
731
{ /* we are the parent */
736
/* create the info string: <name>:<pid>:<protocol_version> */
737
if (asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
738
socket_name, (ulong)pid ) < 0)
740
log_error ("out of core\n");
744
*socket_name = 0; /* don't let cleanup() remove the socket -
745
the child should do this from now on */
747
{ /* run the program given on the commandline */
748
if (putenv (infostr))
750
log_error ("failed to set environment: %s\n",
752
kill (pid, SIGTERM );
755
execvp (argv[0], argv);
756
log_error ("failed to run the command: %s\n", strerror (errno));
762
/* print the environment string, so that the caller can use
763
shell's eval to set it */
766
*strchr (infostr, '=') = ' ';
767
printf ( "setenv %s\n", infostr);
771
printf ( "%s; export SCDAEMON_INFO;\n", infostr);
779
/* this is the child */
781
/* detach from tty and put process into a new session */
783
{ /* close stdin, stdout and stderr unless it is the log stream */
784
for (i=0; i <= 2; i++)
786
if ( log_get_fd () != i)
791
log_error ("setsid() failed: %s\n", strerror(errno) );
799
struct sigaction oact, nact;
801
nact.sa_handler = cleanup_sh;
802
sigemptyset (&nact.sa_mask);
805
sigaction (SIGHUP, NULL, &oact);
806
if (oact.sa_handler != SIG_IGN)
807
sigaction (SIGHUP, &nact, NULL);
808
sigaction( SIGTERM, NULL, &oact );
809
if (oact.sa_handler != SIG_IGN)
810
sigaction (SIGTERM, &nact, NULL);
811
nact.sa_handler = SIG_IGN;
812
sigaction (SIGPIPE, &nact, NULL);
813
sigaction (SIGINT, &nact, NULL);
818
log_error ("chdir to / failed: %s\n", strerror (errno));
822
#endif /*!HAVE_W32_SYSTEM*/
824
scd_command_handler (fd);
836
#warning no update_random_seed_file
837
update_random_seed_file();
840
/* at this time a bit annoying */
841
if (opt.debug & DBG_MEMSTAT_VALUE)
843
gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
844
gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
847
gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
849
gcry_control (GCRYCTL_TERM_SECMEM );
850
rc = rc? rc : log_get_errorcount(0)? 2 : 0;
856
scd_init_default_ctrl (CTRL ctrl)
858
ctrl->reader_slot = -1;
866
handle_signal (int signo)
870
#ifndef HAVE_W32_SYSTEM
872
log_info ("SIGHUP received - "
873
"re-reading configuration and resetting cards\n");
874
/* reread_configuration (); */
878
log_info ("SIGUSR1 received - no action defined\n");
882
log_info ("SIGUSR2 received - no action defined\n");
886
if (!shutdown_pending)
887
log_info ("SIGTERM received - shutting down ...\n");
889
log_info ("SIGTERM received - still %ld running threads\n",
890
pth_ctrl( PTH_CTRL_GETTHREADS ));
892
if (shutdown_pending > 2)
894
log_info ("shutdown forced\n");
895
log_info ("%s %s stopped\n", strusage(11), strusage(13) );
902
log_info ("SIGINT received - immediate shutdown\n");
903
log_info( "%s %s stopped\n", strusage(11), strusage(13));
907
#endif /*!HAVE_W32_SYSTEM*/
910
log_info ("signal %d received - no action defined\n", signo);
917
scd_update_reader_status_file ();
921
ticker_thread (void *dummy_arg)
923
pth_event_t sigs_ev, time_ev = NULL;
927
#ifndef HAVE_W32_SYSTEM /* fixme */
928
sigemptyset (&sigs );
929
sigaddset (&sigs, SIGHUP);
930
sigaddset (&sigs, SIGUSR1);
931
sigaddset (&sigs, SIGUSR2);
932
sigaddset (&sigs, SIGINT);
933
sigaddset (&sigs, SIGTERM);
934
sigs_ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
943
time_ev = pth_event (PTH_EVENT_TIME, pth_timeout (2, 0));
945
pth_event_concat (sigs_ev, time_ev, NULL);
948
if (pth_wait (sigs_ev) < 1)
952
#ifdef PTH_STATUS_OCCURRED /* This is Pth 2 */
953
pth_event_status (sigs_ev) == PTH_STATUS_OCCURRED
955
pth_event_occurred (sigs_ev)
958
handle_signal (signo);
960
/* Always run the ticker. */
961
if (!shutdown_pending)
963
pth_event_isolate (sigs_ev);
964
pth_event_free (time_ev, PTH_FREE_ALL);
970
pth_event_free (sigs_ev, PTH_FREE_ALL);
972
#endif /*USE_GNU_PTH*/
973
#endif /*!HAVE_OPENSC*/