1 /* tpm2daemon.c  -  The GnuPG tpm2 Daemon
2  * Copyright (C) 2001-2002, 2004-2005, 2007-2009 Free Software Foundation, Inc.
3  * Copyright (C) 2001-2002, 2004-2005, 2007-2014 Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  * SPDX-License-Identifier: GPL-3.0-or-later
20  */
21 
22 #include <config.h>
23 
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stddef.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <assert.h>
31 #include <time.h>
32 #include <fcntl.h>
33 #ifndef HAVE_W32_SYSTEM
34 #include <sys/socket.h>
35 #include <sys/un.h>
36 #endif /*HAVE_W32_SYSTEM*/
37 #include <unistd.h>
38 #include <signal.h>
39 #include <npth.h>
40 
41 #define INCLUDED_BY_MAIN_MODULE 1
42 #define GNUPG_COMMON_NEED_AFLOCAL
43 #include "tpm2daemon.h"
44 #include <gcrypt.h>
45 
46 #include <assuan.h> /* malloc hooks */
47 
48 #include "../common/i18n.h"
49 #include "../common/sysutils.h"
50 #include "../common/gc-opt-flags.h"
51 #include "../common/asshelp.h"
52 #include "../common/exechelp.h"
53 #include "../common/init.h"
54 
55 #ifndef ENAMETOOLONG
56 # define ENAMETOOLONG EINVAL
57 #endif
58 
59 enum cmd_and_opt_values
60 { aNull = 0,
61   oCsh            = 'c',
62   oQuiet          = 'q',
63   oSh             = 's',
64   oVerbose        = 'v',
65 
66   oNoVerbose = 500,
67   aGPGConfList,
68   aGPGConfTest,
69   oOptions,
70   oDebug,
71   oDebugAll,
72   oDebugLevel,
73   oDebugWait,
74   oDebugAllowCoreDump,
75   oDebugLogTid,
76   oDebugAssuanLogCats,
77   oNoGreeting,
78   oNoOptions,
79   oHomedir,
80   oNoDetach,
81   oNoGrab,
82   oLogFile,
83   oServer,
84   oMultiServer,
85   oDaemon,
86   oListenBacklog,
87   oParent
88 };
89 
90 
91 
92 static gpgrt_opt_t opts[] = {
93   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
94   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
95 
96   ARGPARSE_group (301, N_("@Options:\n ")),
97 
98   ARGPARSE_s_n (oServer,"server", N_("run in server mode (foreground)")),
99   ARGPARSE_s_n (oMultiServer, "multi-server",
100                 N_("run in multi server mode (foreground)")),
101   ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
102   ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
103   ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
104   ARGPARSE_s_n (oSh,    "sh", N_("sh-style command output")),
105   ARGPARSE_s_n (oCsh,   "csh", N_("csh-style command output")),
106   ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
107   ARGPARSE_s_s (oDebug, "debug", "@"),
108   ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
109   ARGPARSE_s_s (oDebugLevel, "debug-level" ,
110                 N_("|LEVEL|set the debugging level to LEVEL")),
111   ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
112   ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
113   ARGPARSE_s_n (oDebugLogTid, "debug-log-tid", "@"),
114   ARGPARSE_p_u (oDebugAssuanLogCats, "debug-assuan-log-cats", "@"),
115   ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
116   ARGPARSE_s_s (oLogFile,  "log-file", N_("|FILE|write a log to FILE")),
117   ARGPARSE_s_s (oHomedir,    "homedir",      "@"),
118   ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
119   ARGPARSE_p_u (oParent, "tpm2-parent",
120 		N_("Specify tpm2 parent for key")),
121 
122   ARGPARSE_end ()
123 };
124 
125 
126 /* The list of supported debug flags.  */
127 static struct debug_flags_s debug_flags [] =
128   {
129     { DBG_MPI_VALUE    , "mpi"     },
130     { DBG_CRYPTO_VALUE , "crypto"  },
131     { DBG_IPC_VALUE    , "ipc"     },
132     { 0, NULL }
133   };
134 
135 
136 /* The timer tick used to check card removal.
137 
138    We poll every 500ms to let the user immediately know a status
139    change.
140 
141    For a card reader with an interrupt endpoint, this timer is not
142    used with the internal CCID driver.
143 
144    This is not too good for power saving but given that there is no
145    easy way to block on card status changes it is the best we can do.
146    For PC/SC we could in theory use an extra thread to wait for status
147    changes but that requires a native thread because there is no way
148    to make the underlying PC/SC card change function block using a Npth
149    mechanism.  Given that a native thread could only be used under W32
150    we don't do that at all.  */
151 #define TIMERTICK_INTERVAL_SEC     (0)
152 #define TIMERTICK_INTERVAL_USEC    (500000)
153 
154 /* Flag to indicate that a shutdown was requested. */
155 static int shutdown_pending;
156 
157 /* It is possible that we are currently running under setuid permissions */
158 static int maybe_setuid = 1;
159 
160 /* Flag telling whether we are running as a pipe server.  */
161 static int pipe_server;
162 
163 /* Name of the communication socket */
164 static char *socket_name;
165 /* Name of the redirected socket or NULL.  */
166 static char *redir_socket_name;
167 
168 /* We need to keep track of the server's nonces (these are dummies for
169    POSIX systems). */
170 static assuan_sock_nonce_t socket_nonce;
171 
172 /* Value for the listen() backlog argument.  Change at runtime with
173  * --listen-backlog.  */
174 static int listen_backlog = 64;
175 
176 #ifdef HAVE_W32_SYSTEM
177 static HANDLE the_event;
178 #else
179 /* PID to notify update of usb devices.  */
180 static pid_t main_thread_pid;
181 #endif
182 #ifdef HAVE_PSELECT_NO_EINTR
183 /* FD to notify changes.  */
184 static int notify_fd;
185 #endif
186 
187 static char *create_socket_name (char *standard_name);
188 static gnupg_fd_t create_server_socket (const char *name,
189                                         char **r_redir_name,
190                                         assuan_sock_nonce_t *nonce);
191 
192 static void *start_connection_thread (void *arg);
193 static void handle_connections (int listen_fd);
194 
195 /* Pth wrapper function definitions. */
196 ASSUAN_SYSTEM_NPTH_IMPL;
197 
198 static int active_connections;
199 
200 
201 static char *
make_libversion(const char * libname,const char * (* getfnc)(const char *))202 make_libversion (const char *libname, const char *(*getfnc)(const char*))
203 {
204   const char *s;
205   char *result;
206 
207   if (maybe_setuid)
208     {
209       gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
210       maybe_setuid = 0;
211     }
212   s = getfnc (NULL);
213   result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
214   strcpy (stpcpy (stpcpy (result, libname), " "), s);
215   return result;
216 }
217 
218 
219 static const char *
my_strusage(int level)220 my_strusage (int level)
221 {
222   static char *ver_gcry;
223   const char *p;
224 
225   switch (level)
226     {
227     case 11: p = "@TPM2DAEMON@ (@GNUPG@)";
228       break;
229     case 13: p = VERSION; break;
230     case 17: p = PRINTABLE_OS_NAME; break;
231     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
232 
233     case 20:
234       if (!ver_gcry)
235         ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
236       p = ver_gcry;
237       break;
238     case 1:
239     case 40: p =  _("Usage: @TPM2DAEMON@ [options] (-h for help)");
240       break;
241     case 41: p =  _("Syntax: tpm2daemon [options] [command [args]]\n"
242                     "TPM2 daemon for @GNUPG@\n");
243     break;
244 
245     default: p = NULL;
246     }
247   return p;
248 }
249 
250 
251 static int
tid_log_callback(unsigned long * rvalue)252 tid_log_callback (unsigned long *rvalue)
253 {
254   int len = sizeof (*rvalue);
255   npth_t thread;
256 
257   thread = npth_self ();
258   if (sizeof (thread) < len)
259     len = sizeof (thread);
260   memcpy (rvalue, &thread, len);
261 
262   return 2; /* Use use hex representation.  */
263 }
264 
265 
266 /* Setup the debugging.  With a LEVEL of NULL only the active debug
267    flags are propagated to the subsystems.  With LEVEL set, a specific
268    set of debug flags is set; thus overriding all flags already
269    set. */
270 static void
set_debug(const char * level)271 set_debug (const char *level)
272 {
273   int numok = (level && digitp (level));
274   int numlvl = numok? atoi (level) : 0;
275 
276   if (!level)
277     ;
278   else if (!strcmp (level, "none") || (numok && numlvl < 1))
279     opt.debug = 0;
280   else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
281     opt.debug = DBG_IPC_VALUE;
282   else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
283     opt.debug = DBG_IPC_VALUE;
284   else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
285     opt.debug = DBG_IPC_VALUE;
286   else if (!strcmp (level, "guru") || numok)
287       opt.debug = ~0;
288   else
289     {
290       log_error (_("invalid debug-level '%s' given\n"), level);
291       tpm2d_exit (2);
292     }
293 
294 
295   if (opt.debug && !opt.verbose)
296     opt.verbose = 1;
297   if (opt.debug && opt.quiet)
298     opt.quiet = 0;
299 
300   if (opt.debug & DBG_MPI_VALUE)
301     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
302   if (opt.debug & DBG_CRYPTO_VALUE )
303     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
304   gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
305 
306   if (opt.debug)
307     parse_debug_flag (NULL, &opt.debug, debug_flags);
308 }
309 
310 
311 
312 static void
cleanup(void)313 cleanup (void)
314 {
315   if (socket_name && *socket_name)
316     {
317       char *name;
318 
319       name = redir_socket_name? redir_socket_name : socket_name;
320 
321       gnupg_remove (name);
322       *socket_name = 0;
323     }
324 }
325 
326 
327 
328 int
main(int argc,char ** argv)329 main (int argc, char **argv )
330 {
331   gpgrt_argparse_t pargs;
332   int orig_argc;
333   char **orig_argv;
334   char *last_configname = NULL;
335   const char *configname = NULL;
336   const char *shell;
337   int parse_debug = 0;
338   const char *debug_level = NULL;
339   int greeting = 0;
340   int nogreeting = 0;
341   int multi_server = 0;
342   int is_daemon = 0;
343   int nodetach = 0;
344   int csh_style = 0;
345   char *logfile = NULL;
346   int debug_wait = 0;
347   int gpgconf_list = 0;
348   char *config_filename = NULL;
349   int allow_coredump = 0;
350   struct assuan_malloc_hooks malloc_hooks;
351   int res;
352   npth_t pipecon_handler;
353 
354   early_system_init ();
355   gpgrt_set_strusage (my_strusage);
356   gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
357   /* Please note that we may running SUID(ROOT), so be very CAREFUL
358      when adding any stuff between here and the call to INIT_SECMEM()
359      somewhere after the option parsing */
360   log_set_prefix ("tpm2daemon", GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
361 
362   /* Make sure that our subsystems are ready.  */
363   i18n_init ();
364   init_common_subsystems (&argc, &argv);
365 
366   malloc_hooks.malloc = gcry_malloc;
367   malloc_hooks.realloc = gcry_realloc;
368   malloc_hooks.free = gcry_free;
369   assuan_set_malloc_hooks (&malloc_hooks);
370   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
371   assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
372   assuan_sock_init ();
373   setup_libassuan_logging (&opt.debug, NULL);
374 
375   setup_libgcrypt_logging ();
376   gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
377 
378   disable_core_dumps ();
379 
380   /* Set default options. */
381   opt.parent = 0;		/* 0 means TPM uses default */
382 
383   shell = getenv ("SHELL");
384   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
385     csh_style = 1;
386 
387   /* Check whether we have a config file on the commandline */
388   orig_argc = argc;
389   orig_argv = argv;
390   pargs.argc = &argc;
391   pargs.argv = &argv;
392   pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
393   while (gpgrt_argparse (NULL, &pargs, opts))
394     {
395       switch (pargs.r_opt)
396         {
397         case oDebug:
398         case oDebugAll:
399           parse_debug++;
400           break;
401         case oHomedir:
402           gnupg_set_homedir (pargs.r.ret_str);
403           break;
404         }
405     }
406   /* Reset the flags.  */
407   pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
408 
409   /* initialize the secure memory. */
410   gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
411   maybe_setuid = 0;
412 
413   /*
414      Now we are working under our real uid
415   */
416 
417 
418   /* The configuraton directories for use by gpgrt_argparser.  */
419   gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
420   gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
421 
422   /* We are re-using the struct, thus the reset flag.  We OR the
423    * flags so that the internal intialized flag won't be cleared. */
424   argc = orig_argc;
425   argv = orig_argv;
426   pargs.argc = &argc;
427   pargs.argv = &argv;
428   pargs.flags |=  (ARGPARSE_FLAG_RESET
429                    | ARGPARSE_FLAG_KEEP
430                    | ARGPARSE_FLAG_SYS
431                    | ARGPARSE_FLAG_USER);
432   while (gpgrt_argparser (&pargs, opts, TPM2DAEMON_NAME EXTSEP_S "conf"))
433     {
434       switch (pargs.r_opt)
435         {
436         case ARGPARSE_CONFFILE:
437           if (parse_debug)
438             log_info (_("reading options from '%s'\n"),
439                       pargs.r_type? pargs.r.ret_str: "[cmdline]");
440           if (pargs.r_type)
441             {
442               xfree (last_configname);
443               last_configname = xstrdup (pargs.r.ret_str);
444               configname = last_configname;
445             }
446           else
447             configname = NULL;
448           break;
449 
450         case aGPGConfList: gpgconf_list = 1; break;
451         case aGPGConfTest: gpgconf_list = 2; break;
452         case oQuiet: opt.quiet = 1; break;
453         case oVerbose: opt.verbose++; break;
454 
455         case oDebug:
456           if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
457             {
458               pargs.r_opt = ARGPARSE_INVALID_ARG;
459               pargs.err = ARGPARSE_PRINT_ERROR;
460             }
461           break;
462         case oDebugAll: opt.debug = ~0; break;
463         case oDebugLevel: debug_level = pargs.r.ret_str; break;
464         case oDebugWait: debug_wait = pargs.r.ret_int; break;
465         case oDebugAllowCoreDump:
466           enable_core_dumps ();
467           allow_coredump = 1;
468           break;
469         case oDebugLogTid:
470           log_set_pid_suffix_cb (tid_log_callback);
471           break;
472         case oDebugAssuanLogCats:
473           set_libassuan_log_cats (pargs.r.ret_ulong);
474           break;
475 
476         case oNoGreeting: nogreeting = 1; break;
477         case oNoVerbose: opt.verbose = 0; break;
478         case oNoOptions: break; /* no-options */
479         case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
480         case oNoDetach: nodetach = 1; break;
481         case oLogFile: logfile = pargs.r.ret_str; break;
482         case oCsh: csh_style = 1; break;
483         case oSh: csh_style = 0; break;
484         case oServer: pipe_server = 1; break;
485         case oMultiServer: pipe_server = 1; multi_server = 1; break;
486         case oDaemon: is_daemon = 1; break;
487 
488         case oListenBacklog:
489           listen_backlog = pargs.r.ret_int;
490           break;
491 
492 	case oParent:
493 	  opt.parent = pargs.r.ret_ulong;
494 	  break;
495 
496         default:
497           if (configname)
498             pargs.err = ARGPARSE_PRINT_WARNING;
499           else
500             pargs.err = ARGPARSE_PRINT_ERROR;
501           break;
502         }
503     }
504   gpgrt_argparse (NULL, &pargs, NULL);  /* Release internal state.  */
505 
506   if (!last_configname)
507     config_filename = gpgrt_fnameconcat (gnupg_homedir (),
508                                          TPM2DAEMON_NAME EXTSEP_S "conf",
509                                          NULL);
510   else
511     {
512       config_filename = last_configname;
513       last_configname = NULL;
514     }
515 
516   if (log_get_errorcount (0))
517     exit (2);
518   if (nogreeting )
519     greeting = 0;
520 
521   if (greeting)
522     {
523       es_fprintf (es_stderr, "%s %s; %s\n",
524                   gpgrt_strusage (11), gpgrt_strusage (13),
525 		  gpgrt_strusage (14) );
526       es_fprintf (es_stderr, "%s\n", gpgrt_strusage (15) );
527     }
528 #ifdef IS_DEVELOPMENT_VERSION
529   log_info ("NOTE: this is a development version!\n");
530 #endif
531 
532   /* Print a warning if an argument looks like an option.  */
533   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
534     {
535       int i;
536 
537       for (i=0; i < argc; i++)
538         if (argv[i][0] == '-' && argv[i][1] == '-')
539           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
540     }
541 
542   if (atexit (cleanup))
543     {
544       log_error ("atexit failed\n");
545       cleanup ();
546       exit (1);
547     }
548 
549   set_debug (debug_level);
550 
551   if (gpgconf_list == 2)
552     tpm2d_exit (0);
553   if (gpgconf_list)
554     {
555       es_printf ("verbose:%lu:\n"
556                  "quiet:%lu:\n"
557                  "debug-level:%lu:\"none:\n"
558                  "log-file:%lu:\n",
559                  GC_OPT_FLAG_NONE,
560                  GC_OPT_FLAG_NONE,
561                  GC_OPT_FLAG_DEFAULT,
562                  GC_OPT_FLAG_NONE );
563 
564       tpm2d_exit (0);
565     }
566 
567   /* Now start with logging to a file if this is desired.  */
568   if (logfile)
569     {
570       log_set_file (logfile);
571       log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
572     }
573 
574   if (debug_wait && pipe_server)
575     {
576       log_debug ("waiting for debugger - my pid is %u .....\n",
577                  (unsigned int)getpid ());
578       gnupg_sleep (debug_wait);
579       log_debug ("... okay\n");
580     }
581 
582   if (pipe_server)
583     {
584       /* This is the simple pipe based server */
585       ctrl_t ctrl;
586       npth_attr_t tattr;
587       int fd = -1;
588 
589 #ifndef HAVE_W32_SYSTEM
590       {
591         struct sigaction sa;
592 
593         sa.sa_handler = SIG_IGN;
594         sigemptyset (&sa.sa_mask);
595         sa.sa_flags = 0;
596         sigaction (SIGPIPE, &sa, NULL);
597       }
598 #endif
599 
600       npth_init ();
601       gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
602 
603       /* If --debug-allow-core-dump has been given we also need to
604          switch the working directory to a place where we can actually
605          write. */
606       if (allow_coredump)
607         {
608           if (chdir ("/tmp"))
609             log_debug ("chdir to '/tmp' failed: %s\n", strerror (errno));
610           else
611             log_debug ("changed working directory to '/tmp'\n");
612         }
613 
614       /* In multi server mode we need to listen on an additional
615          socket.  Create that socket now before starting the handler
616          for the pipe connection.  This allows that handler to send
617          back the name of that socket. */
618       if (multi_server)
619         {
620           socket_name = create_socket_name (TPM2DAEMON_SOCK_NAME);
621           fd = FD2INT (create_server_socket (socket_name,
622 					     &redir_socket_name,
623 					     &socket_nonce));
624         }
625 
626       res = npth_attr_init (&tattr);
627       if (res)
628         {
629           log_error ("error allocating thread attributes: %s\n",
630                      strerror (res));
631           tpm2d_exit (2);
632         }
633       npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
634 
635       ctrl = xtrycalloc (1, sizeof *ctrl);
636       if ( !ctrl )
637         {
638           log_error ("error allocating connection control data: %s\n",
639                      strerror (errno) );
640           tpm2d_exit (2);
641         }
642       ctrl->thread_startup.fd = GNUPG_INVALID_FD;
643       res = npth_create (&pipecon_handler, &tattr, start_connection_thread, ctrl);
644       if (res)
645         {
646           log_error ("error spawning pipe connection handler: %s\n",
647                      strerror (res) );
648           xfree (ctrl);
649           tpm2d_exit (2);
650         }
651       npth_setname_np (pipecon_handler, "pipe-connection");
652       npth_attr_destroy (&tattr);
653 
654       /* We run handle_connection to wait for the shutdown signal and
655          to run the ticker stuff.  */
656       handle_connections (fd);
657       if (fd != -1)
658         close (fd);
659     }
660   else if (!is_daemon)
661     {
662       log_info (_("please use the option '--daemon'"
663                   " to run the program in the background\n"));
664     }
665   else
666     { /* Regular server mode */
667       int fd;
668 #ifndef HAVE_W32_SYSTEM
669       pid_t pid;
670       int i;
671 #endif
672 
673       /* Create the socket.  */
674       socket_name = create_socket_name (TPM2DAEMON_SOCK_NAME);
675       fd = FD2INT (create_server_socket (socket_name,
676                                          &redir_socket_name, &socket_nonce));
677 
678 
679       fflush (NULL);
680 #ifdef HAVE_W32_SYSTEM
681       (void)csh_style;
682       (void)nodetach;
683 #else
684       pid = fork ();
685       if (pid == (pid_t)-1)
686         {
687           log_fatal ("fork failed: %s\n", strerror (errno) );
688           exit (1);
689         }
690       else if (pid)
691         { /* we are the parent */
692           char *infostr;
693 
694           close (fd);
695 
696           /* create the info string: <name>:<pid>:<protocol_version> */
697           if (gpgrt_asprintf (&infostr, "TPM2DAEMON_INFO=%s:%lu:1",
698                               socket_name, (ulong) pid) < 0)
699             {
700               log_error ("out of core\n");
701               kill (pid, SIGTERM);
702               exit (1);
703             }
704           *socket_name = 0; /* don't let cleanup() remove the socket -
705                                the child should do this from now on */
706           if (argc)
707             { /* run the program given on the commandline */
708               if (putenv (infostr))
709                 {
710                   log_error ("failed to set environment: %s\n",
711                              strerror (errno) );
712                   kill (pid, SIGTERM );
713                   exit (1);
714                 }
715               execvp (argv[0], argv);
716               log_error ("failed to run the command: %s\n", strerror (errno));
717               kill (pid, SIGTERM);
718               exit (1);
719             }
720           else
721             {
722               /* Print the environment string, so that the caller can use
723                  shell's eval to set it */
724               if (csh_style)
725                 {
726                   *strchr (infostr, '=') = ' ';
727                   es_printf ( "setenv %s;\n", infostr);
728                 }
729               else
730                 {
731                   es_printf ( "%s; export TPM2DAEMON_INFO;\n", infostr);
732                 }
733               xfree (infostr);
734               exit (0);
735             }
736           /* NOTREACHED */
737         } /* end parent */
738 
739       /* This is the child. */
740 
741       npth_init ();
742       gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
743 
744       /* Detach from tty and put process into a new session. */
745       if (!nodetach )
746         {
747           /* Close stdin, stdout and stderr unless it is the log stream. */
748           for (i=0; i <= 2; i++)
749             {
750               if (!log_test_fd (i) && i != fd )
751                 {
752                   if ( !close (i)
753                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
754                     {
755                       log_error ("failed to open '%s': %s\n",
756                                  "/dev/null", strerror (errno));
757                       cleanup ();
758                       exit (1);
759                     }
760                 }
761             }
762 
763           if (setsid () == -1)
764             {
765               log_error ("setsid() failed: %s\n", strerror (errno) );
766               cleanup ();
767               exit (1);
768             }
769         }
770 
771       {
772         struct sigaction sa;
773 
774         sa.sa_handler = SIG_IGN;
775         sigemptyset (&sa.sa_mask);
776         sa.sa_flags = 0;
777         sigaction (SIGPIPE, &sa, NULL);
778       }
779 
780 #endif /*!HAVE_W32_SYSTEM*/
781 
782       if (gnupg_chdir (gnupg_daemon_rootdir ()))
783         {
784           log_error ("chdir to '%s' failed: %s\n",
785                      gnupg_daemon_rootdir (), strerror (errno));
786           exit (1);
787         }
788 
789       handle_connections (fd);
790 
791       close (fd);
792     }
793 
794   xfree (config_filename);
795   return 0;
796 }
797 
798 void
tpm2d_exit(int rc)799 tpm2d_exit (int rc)
800 {
801   gcry_control (GCRYCTL_TERM_SECMEM );
802   rc = rc? rc : log_get_errorcount (0)? 2 : 0;
803   exit (rc);
804 }
805 
806 
807 static void
tpm2d_init_default_ctrl(ctrl_t ctrl)808 tpm2d_init_default_ctrl (ctrl_t ctrl)
809 {
810   (void)ctrl;
811 }
812 
813 static void
tpm2d_deinit_default_ctrl(ctrl_t ctrl)814 tpm2d_deinit_default_ctrl (ctrl_t ctrl)
815 {
816   if (!ctrl)
817     return;
818   xfree (ctrl->in_data.value);
819   ctrl->in_data.value = NULL;
820   ctrl->in_data.valuelen = 0;
821 }
822 
823 
824 /* Return the name of the socket to be used to connect to this
825    process.  If no socket is available, return NULL. */
826 const char *
tpm2d_get_socket_name(void)827 tpm2d_get_socket_name (void)
828 {
829   if (socket_name && *socket_name)
830     return socket_name;
831   return NULL;
832 }
833 
834 
835 #ifndef HAVE_W32_SYSTEM
836 static void
handle_signal(int signo)837 handle_signal (int signo)
838 {
839   switch (signo)
840     {
841     case SIGHUP:
842       log_info ("SIGHUP received - "
843                 "re-reading configuration\n");
844 /*       reread_configuration (); */
845       break;
846 
847     case SIGUSR1:
848       log_info ("SIGUSR1 received - printing internal information:\n");
849       /* Fixme: We need to see how to integrate pth dumping into our
850          logging system.  */
851       /* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
852 #if 0
853       app_dump_state ();
854 #endif
855       break;
856 
857     case SIGUSR2:
858       log_info ("SIGUSR2 received - no action defined\n");
859       break;
860 
861     case SIGCONT:
862       /* Nothing.  */
863       log_debug ("SIGCONT received - breaking select\n");
864       break;
865 
866     case SIGTERM:
867       if (!shutdown_pending)
868         log_info ("SIGTERM received - shutting down ...\n");
869       else
870         log_info ("SIGTERM received - still %i running threads\n",
871                   active_connections);
872       shutdown_pending++;
873       if (shutdown_pending > 2)
874         {
875           log_info ("shutdown forced\n");
876           log_info ("%s %s stopped\n", gpgrt_strusage (11),
877 		    gpgrt_strusage (13) );
878           cleanup ();
879           tpm2d_exit (0);
880         }
881       break;
882 
883     case SIGINT:
884       log_info ("SIGINT received - immediate shutdown\n");
885       log_info ( "%s %s stopped\n", gpgrt_strusage (11), gpgrt_strusage (13));
886       cleanup ();
887       tpm2d_exit (0);
888       break;
889 
890     default:
891       log_info ("signal %d received - no action defined\n", signo);
892     }
893 }
894 #endif /*!HAVE_W32_SYSTEM*/
895 
896 
897 /* Create a name for the socket.  We check for valid characters as
898    well as against a maximum allowed length for a unix domain socket
899    is done.  The function terminates the process in case of an error.
900    Retunrs: Pointer to an allcoated string with the absolute name of
901    the socket used.  */
902 static char *
create_socket_name(char * standard_name)903 create_socket_name (char *standard_name)
904 {
905   char *name;
906 
907   name = make_filename (gnupg_socketdir (), standard_name, NULL);
908   if (strchr (name, PATHSEP_C))
909     {
910       log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
911       tpm2d_exit (2);
912     }
913   return name;
914 }
915 
916 
917 
918 /* Create a Unix domain socket with NAME.  Returns the file descriptor
919    or terminates the process in case of an error.  If the socket has
920    been redirected the name of the real socket is stored as a malloced
921    string at R_REDIR_NAME. */
922 static gnupg_fd_t
create_server_socket(const char * name,char ** r_redir_name,assuan_sock_nonce_t * nonce)923 create_server_socket (const char *name, char **r_redir_name,
924                       assuan_sock_nonce_t *nonce)
925 {
926   struct sockaddr *addr;
927   struct sockaddr_un *unaddr;
928   socklen_t len;
929   gnupg_fd_t fd;
930   int rc;
931 
932   xfree (*r_redir_name);
933   *r_redir_name = NULL;
934 
935   fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
936   if (fd == GNUPG_INVALID_FD)
937     {
938       log_error (_("can't create socket: %s\n"), strerror (errno));
939       tpm2d_exit (2);
940     }
941 
942   unaddr = xmalloc (sizeof (*unaddr));
943   addr = (struct sockaddr*)unaddr;
944 
945   {
946     int redirected;
947 
948     if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
949       {
950         if (errno == ENAMETOOLONG)
951           log_error (_("socket name '%s' is too long\n"), name);
952         else
953           log_error ("error preparing socket '%s': %s\n",
954                      name, gpg_strerror (gpg_error_from_syserror ()));
955         tpm2d_exit (2);
956       }
957     if (redirected)
958       {
959         *r_redir_name = xstrdup (unaddr->sun_path);
960         if (opt.verbose)
961           log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
962       }
963   }
964 
965   len = SUN_LEN (unaddr);
966 
967   rc = assuan_sock_bind (fd, addr, len);
968   if (rc == -1 && errno == EADDRINUSE)
969     {
970       gnupg_remove (unaddr->sun_path);
971       rc = assuan_sock_bind (fd, addr, len);
972     }
973   if (rc != -1
974       && (rc=assuan_sock_get_nonce (addr, len, nonce)))
975     log_error (_("error getting nonce for the socket\n"));
976  if (rc == -1)
977     {
978       log_error (_("error binding socket to '%s': %s\n"),
979                  unaddr->sun_path,
980                  gpg_strerror (gpg_error_from_syserror ()));
981       assuan_sock_close (fd);
982       tpm2d_exit (2);
983     }
984 
985   if (gnupg_chmod (unaddr->sun_path, "-rwx"))
986     log_error (_("can't set permissions of '%s': %s\n"),
987                unaddr->sun_path, strerror (errno));
988 
989   if (listen (FD2INT (fd), listen_backlog) == -1)
990     {
991       log_error ("listen(fd, %d) failed: %s\n",
992                  listen_backlog, gpg_strerror (gpg_error_from_syserror ()));
993       assuan_sock_close (fd);
994       tpm2d_exit (2);
995     }
996 
997   if (opt.verbose)
998     log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
999 
1000   return fd;
1001 }
1002 
1003 
1004 
1005 /* This is the standard connection thread's main function.  */
1006 static void *
start_connection_thread(void * arg)1007 start_connection_thread (void *arg)
1008 {
1009   ctrl_t ctrl = arg;
1010 
1011   if (ctrl->thread_startup.fd != GNUPG_INVALID_FD
1012       && assuan_sock_check_nonce (ctrl->thread_startup.fd, &socket_nonce))
1013     {
1014       log_info (_("error reading nonce on fd %d: %s\n"),
1015                 FD2INT (ctrl->thread_startup.fd), strerror (errno));
1016       assuan_sock_close (ctrl->thread_startup.fd);
1017       xfree (ctrl);
1018       return NULL;
1019     }
1020 
1021   active_connections++;
1022 
1023   tpm2d_init_default_ctrl (ctrl);
1024   if (opt.verbose)
1025     log_info (_("handler for fd %d started\n"),
1026               FD2INT (ctrl->thread_startup.fd));
1027 
1028   /* If this is a pipe server, we request a shutdown if the command
1029      handler asked for it.  With the next ticker event and given that
1030      no other connections are running the shutdown will then
1031      happen.  */
1032   if (tpm2d_command_handler (ctrl, FD2INT (ctrl->thread_startup.fd))
1033       && pipe_server)
1034     shutdown_pending = 1;
1035 
1036   if (opt.verbose)
1037     log_info (_("handler for fd %d terminated\n"),
1038               FD2INT (ctrl->thread_startup.fd));
1039 
1040   tpm2d_deinit_default_ctrl (ctrl);
1041   xfree (ctrl);
1042 
1043   if (--active_connections == 0)
1044     tpm2d_kick_the_loop ();
1045 
1046   return NULL;
1047 }
1048 
1049 
1050 void
tpm2d_kick_the_loop(void)1051 tpm2d_kick_the_loop (void)
1052 {
1053 #ifdef HAVE_W32_SYSTEM
1054   int ret;
1055 
1056   /* Kick the select loop.  */
1057   ret = SetEvent (the_event);
1058   if (ret == 0)
1059     log_error ("SetEvent for tpm2d_kick_the_loop failed: %s\n",
1060                w32_strerror (-1));
1061 #elif defined(HAVE_PSELECT_NO_EINTR)
1062   write (notify_fd, "", 1);
1063 #else
1064   int ret;
1065 
1066   ret = kill (main_thread_pid, SIGCONT);
1067   if (ret < 0)
1068     log_error ("SetEvent for tpm2d_kick_the_loop failed: %s\n",
1069                gpg_strerror (gpg_error_from_syserror ()));
1070 #endif
1071 }
1072 
1073 /* Connection handler loop.  Wait for connection requests and spawn a
1074    thread after accepting a connection.  LISTEN_FD is allowed to be -1
1075    in which case this code will only do regular timeouts and handle
1076    signals. */
1077 static void
handle_connections(int listen_fd)1078 handle_connections (int listen_fd)
1079 {
1080   npth_attr_t tattr;
1081   struct sockaddr_un paddr;
1082   socklen_t plen;
1083   fd_set fdset, read_fdset;
1084   int nfd;
1085   int ret;
1086   int fd;
1087   struct timespec timeout;
1088   struct timespec *t;
1089   int saved_errno;
1090 #ifdef HAVE_W32_SYSTEM
1091   HANDLE events[2];
1092   unsigned int events_set;
1093 #else
1094   int signo;
1095 #endif
1096 #ifdef HAVE_PSELECT_NO_EINTR
1097   int pipe_fd[2];
1098 
1099   ret = gnupg_create_pipe (pipe_fd);
1100   if (ret)
1101     {
1102       log_error ("pipe creation failed: %s\n", gpg_strerror (ret));
1103       return;
1104     }
1105   notify_fd = pipe_fd[1];
1106 #endif
1107 
1108   ret = npth_attr_init (&tattr);
1109   if (ret)
1110     {
1111       log_error ("npth_attr_init failed: %s\n", strerror (ret));
1112       return;
1113     }
1114 
1115   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1116 
1117 #ifdef HAVE_W32_SYSTEM
1118   {
1119     HANDLE h, h2;
1120     SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
1121 
1122     events[0] = the_event = INVALID_HANDLE_VALUE;
1123     events[1] = INVALID_HANDLE_VALUE;
1124     h = CreateEvent (&sa, TRUE, FALSE, NULL);
1125     if (!h)
1126       log_error ("can't create tpm2d event: %s\n", w32_strerror (-1) );
1127     else if (!DuplicateHandle (GetCurrentProcess (), h,
1128                                GetCurrentProcess (), &h2,
1129                                EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
1130       {
1131         log_error ("setting synchronize for tpm2d_kick_the_loop failed: %s\n",
1132                    w32_strerror (-1) );
1133         CloseHandle (h);
1134       }
1135     else
1136       {
1137         CloseHandle (h);
1138         events[0] = the_event = h2;
1139       }
1140   }
1141 #else
1142   npth_sigev_init ();
1143   npth_sigev_add (SIGHUP);
1144   npth_sigev_add (SIGUSR1);
1145   npth_sigev_add (SIGUSR2);
1146   npth_sigev_add (SIGINT);
1147   npth_sigev_add (SIGCONT);
1148   npth_sigev_add (SIGTERM);
1149   npth_sigev_fini ();
1150   main_thread_pid = getpid ();
1151 #endif
1152 
1153   FD_ZERO (&fdset);
1154   nfd = 0;
1155   if (listen_fd != -1)
1156     {
1157       FD_SET (listen_fd, &fdset);
1158       nfd = listen_fd;
1159     }
1160 
1161   for (;;)
1162     {
1163       int periodical_check;
1164       int max_fd = nfd;
1165 
1166       if (shutdown_pending)
1167         {
1168           if (active_connections == 0)
1169             break; /* ready */
1170 
1171           /* Do not accept anymore connections but wait for existing
1172              connections to terminate. We do this by clearing out all
1173              file descriptors to wait for, so that the select will be
1174              used to just wait on a signal or timeout event. */
1175           FD_ZERO (&fdset);
1176           listen_fd = -1;
1177         }
1178 
1179       periodical_check = 0;
1180 
1181       timeout.tv_sec = TIMERTICK_INTERVAL_SEC;
1182       timeout.tv_nsec = TIMERTICK_INTERVAL_USEC * 1000;
1183 
1184       if (shutdown_pending || periodical_check)
1185         t = &timeout;
1186       else
1187         t = NULL;
1188 
1189       /* POSIX says that fd_set should be implemented as a structure,
1190          thus a simple assignment is fine to copy the entire set.  */
1191       read_fdset = fdset;
1192 
1193 #ifdef HAVE_PSELECT_NO_EINTR
1194       FD_SET (pipe_fd[0], &read_fdset);
1195       if (max_fd < pipe_fd[0])
1196         max_fd = pipe_fd[0];
1197 #endif
1198 
1199 #ifndef HAVE_W32_SYSTEM
1200       ret = npth_pselect (max_fd+1, &read_fdset, NULL, NULL, t,
1201                           npth_sigev_sigmask ());
1202       saved_errno = errno;
1203 
1204       while (npth_sigev_get_pending (&signo))
1205         handle_signal (signo);
1206 #else
1207       ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, t,
1208                           events, &events_set);
1209       saved_errno = errno;
1210       if (events_set & 1)
1211         continue;
1212 #endif
1213 
1214       if (ret == -1 && saved_errno != EINTR)
1215         {
1216           log_error (_("npth_pselect failed: %s - waiting 1s\n"),
1217                      strerror (saved_errno));
1218           gnupg_sleep (1);
1219           continue;
1220         }
1221 
1222       if (ret <= 0)
1223         /* Timeout.  Will be handled when calculating the next timeout.  */
1224         continue;
1225 
1226 #ifdef HAVE_PSELECT_NO_EINTR
1227       if (FD_ISSET (pipe_fd[0], &read_fdset))
1228         {
1229           char buf[256];
1230 
1231           read (pipe_fd[0], buf, sizeof buf);
1232         }
1233 #endif
1234 
1235       if (listen_fd != -1 && FD_ISSET (listen_fd, &read_fdset))
1236         {
1237           ctrl_t ctrl;
1238 
1239           plen = sizeof paddr;
1240           fd = npth_accept (listen_fd, (struct sockaddr *)&paddr, &plen);
1241           if (fd == -1)
1242             {
1243               log_error ("accept failed: %s\n", strerror (errno));
1244             }
1245           else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)) )
1246             {
1247               log_error ("error allocating connection control data: %s\n",
1248                          strerror (errno) );
1249               close (fd);
1250             }
1251           else
1252             {
1253               char threadname[50];
1254               npth_t thread;
1255 
1256               snprintf (threadname, sizeof threadname, "conn fd=%d", fd);
1257               ctrl->thread_startup.fd = INT2FD (fd);
1258               ret = npth_create (&thread, &tattr, start_connection_thread, ctrl);
1259               if (ret)
1260                 {
1261                   log_error ("error spawning connection handler: %s\n",
1262                              strerror (ret));
1263                   xfree (ctrl);
1264                   close (fd);
1265                 }
1266               else
1267                 npth_setname_np (thread, threadname);
1268             }
1269         }
1270     }
1271 
1272 #ifdef HAVE_W32_SYSTEM
1273   if (the_event != INVALID_HANDLE_VALUE)
1274     CloseHandle (the_event);
1275 #endif
1276 #ifdef HAVE_PSELECT_NO_EINTR
1277   close (pipe_fd[0]);
1278   close (pipe_fd[1]);
1279 #endif
1280   cleanup ();
1281   log_info (_("%s %s stopped\n"), gpgrt_strusage (11), gpgrt_strusage (13));
1282   npth_attr_destroy (&tattr);
1283 }
1284 
1285 /* Return the number of active connections. */
1286 int
get_active_connection_count(void)1287 get_active_connection_count (void)
1288 {
1289   return active_connections;
1290 }
1291