1 /* call-daemon - Common code for the call-XXX.c modules
2  * Copyright (C) 2001, 2002, 2005, 2007, 2010,
3  *               2011 Free Software Foundation, Inc.
4  * Copyright (C) 2013 Werner Koch
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  * SPDX-License-Identifier: GPL-3.0-or-later
21  */
22 
23 #include <config.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <ctype.h>
29 #include <unistd.h>
30 #ifdef HAVE_SIGNAL_H
31 # include <signal.h>
32 #endif
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #ifndef HAVE_W32_SYSTEM
36 #include <sys/wait.h>
37 #endif
38 #include <npth.h>
39 
40 #include "agent.h"
41 #include <assuan.h>
42 #include "../common/strlist.h"
43 
44 /* Daemon type to module mapping.  Make sure that they are added in the
45  * same order as given by the daemon_type enum.  */
46 static const int daemon_modules[DAEMON_MAX_TYPE] =
47   {
48     GNUPG_MODULE_NAME_SCDAEMON,
49     GNUPG_MODULE_NAME_TPM2DAEMON
50   };
51 
52 /* Definition of module local data of the CTRL structure.  */
53 struct daemon_local_s
54 {
55   /* We keep a list of all allocated context with an anchor at
56      DAEMON_LOCAL_LIST (see below). */
57   struct daemon_local_s *next_local;
58 
59   /* Link back to the global structure.  */
60   struct daemon_global_s *g;
61 
62   assuan_context_t ctx;   /* NULL or session context for the daemon
63                              used with this connection. */
64   unsigned int in_use: 1; /* CTX is in use.  */
65   unsigned int invalid:1; /* CTX is invalid, should be released.  */
66 };
67 
68 
69 /* Primary holder of all the started daemons */
70 struct daemon_global_s
71 {
72   /* To keep track of all active daemon contexts, we keep a linked list
73      anchored at this variable. */
74   struct daemon_local_s *local_list;
75   /* A malloced string with the name of the socket to be used for
76      additional connections.  May be NULL if not provided by
77      daemon. */
78   char *socket_name;
79 
80   /* The context of the primary connection.  This is also used as a flag
81      to indicate whether the daemon has been started. */
82   assuan_context_t primary_ctx;
83 
84   /* To allow reuse of the primary connection, the following flag is set
85      to true if the primary context has been reset and is not in use by
86      any connection. */
87   int primary_ctx_reusable;
88 };
89 
90 static struct daemon_global_s daemon_global[DAEMON_MAX_TYPE];
91 
92 
93 /* A Mutex used inside the start_daemon function. */
94 static npth_mutex_t start_daemon_lock;
95 
96 
97 /* Communication object for wait_child_thread.  */
98 struct wait_child_thread_parm_s
99 {
100   enum daemon_type type;
101   pid_t pid;
102 };
103 
104 
105 /* Thread to wait for daemon termination and cleanup of resources.  */
106 static void *
wait_child_thread(void * arg)107 wait_child_thread (void *arg)
108 {
109   int err;
110   struct wait_child_thread_parm_s *parm = arg;
111   enum daemon_type type = parm->type;
112   pid_t pid =  parm->pid;
113 #ifndef HAVE_W32_SYSTEM
114   int wstatus;
115 #endif
116   const char *name = gnupg_module_name (daemon_modules[type]);
117   struct daemon_global_s *g = &daemon_global[type];
118   struct daemon_local_s *sl;
119 
120   xfree (parm);  /* We have copied all data to the stack.  */
121 
122 #ifdef HAVE_W32_SYSTEM
123   npth_unprotect ();
124   /* Note that although we use a pid_t here, it is actually a HANDLE.  */
125   WaitForSingleObject ((HANDLE)pid, INFINITE);
126   npth_protect ();
127   log_info ("daemon %s finished\n", name);
128 #else /* !HAVE_W32_SYSTEM*/
129 
130  again:
131   npth_unprotect ();
132   err = waitpid (pid, &wstatus, 0);
133   npth_protect ();
134 
135   if (err < 0)
136     {
137       if (errno == EINTR)
138         goto again;
139       log_error ("waitpid for %s failed: %s\n", name, strerror (errno));
140       return NULL;
141     }
142   else
143     {
144       if (WIFEXITED (wstatus))
145         log_info ("daemon %s finished (status %d)\n",
146                   name, WEXITSTATUS (wstatus));
147       else if (WIFSIGNALED (wstatus))
148         log_info ("daemon %s killed by signal %d\n", name, WTERMSIG (wstatus));
149       else
150         {
151           if (WIFSTOPPED (wstatus))
152             log_info ("daemon %s stopped by signal %d\n",
153                       name, WSTOPSIG (wstatus));
154           goto again;
155         }
156     }
157 #endif /*!HAVE_W32_SYSTEM*/
158 
159   agent_flush_cache (1);  /* Flush the PIN cache.  */
160 
161   err = npth_mutex_lock (&start_daemon_lock);
162   if (err)
163     {
164       log_error ("failed to acquire the start_daemon lock: %s\n",
165                  strerror (err));
166     }
167   else
168     {
169       assuan_set_flag (g->primary_ctx, ASSUAN_NO_WAITPID, 1);
170 
171       for (sl = g->local_list; sl; sl = sl->next_local)
172         {
173           sl->invalid = 1;
174           if (!sl->in_use && sl->ctx)
175             {
176               assuan_release (sl->ctx);
177               sl->ctx = NULL;
178             }
179         }
180 
181       g->primary_ctx = NULL;
182       g->primary_ctx_reusable = 0;
183 
184       xfree (g->socket_name);
185       g->socket_name = NULL;
186 
187       err = npth_mutex_unlock (&start_daemon_lock);
188       if (err)
189         log_error ("failed to release the start_daemon lock"
190                    " after waitpid for %s: %s\n", name, strerror (err));
191     }
192 
193   return NULL;
194 }
195 
196 
197 /* This function shall be called after having accessed the daemon.  It
198  * is currently not very useful but gives an opportunity to keep track
199  * of connections currently calling daemon.  Note that the "lock"
200  * operation is done by the daemon_start function which must be called
201  * and error checked before any daemon operation.  CTRL is the usual
202  * connection context and RC the error code to be passed through the
203  * function. */
204 gpg_error_t
daemon_unlock(enum daemon_type type,ctrl_t ctrl,gpg_error_t rc)205 daemon_unlock (enum daemon_type type, ctrl_t ctrl, gpg_error_t rc)
206 {
207   gpg_error_t err;
208 
209   if (ctrl->d_local[type]->in_use == 0)
210     {
211       log_error ("%s: CTX for type %d is not in use\n", __func__, (int)type);
212       if (!rc)
213         rc = gpg_error (GPG_ERR_INTERNAL);
214     }
215   err = npth_mutex_lock (&start_daemon_lock);
216   if (err)
217     {
218       log_error ("failed to acquire the start_daemon lock: %s\n",
219                  strerror (err));
220       return gpg_error (GPG_ERR_INTERNAL);
221     }
222   ctrl->d_local[type]->in_use = 0;
223   if (ctrl->d_local[type]->invalid)
224     {
225       assuan_release (ctrl->d_local[type]->ctx);
226       ctrl->d_local[type]->ctx = NULL;
227       ctrl->d_local[type]->invalid = 0;
228     }
229   err = npth_mutex_unlock (&start_daemon_lock);
230   if (err)
231     {
232       log_error ("failed to release the start_daemon lock: %s\n",
233                  strerror (err));
234       return gpg_error (GPG_ERR_INTERNAL);
235     }
236   return rc;
237 }
238 
239 
240 /* To make sure we leave no secrets in our image after forking of the
241    daemon, we use this callback. */
242 static void
atfork_cb(void * opaque,int where)243 atfork_cb (void *opaque, int where)
244 {
245   (void)opaque;
246 
247   if (!where)
248     gcry_control (GCRYCTL_TERM_SECMEM);
249 }
250 
251 
252 /* Fork off the daemon if this has not already been done.  Lock the
253  * daemon and make sure that a proper context has been setup in CTRL.
254  * This function might also lock the daemon, which means that the
255  * caller must call unlock_daemon after this function has returned
256  * success and the actual Assuan transaction been done. */
257 gpg_error_t
daemon_start(enum daemon_type type,ctrl_t ctrl)258 daemon_start (enum daemon_type type, ctrl_t ctrl)
259 {
260   gpg_error_t err = 0;
261   const char *pgmname;
262   assuan_context_t ctx = NULL;
263   const char *argv[5];
264   assuan_fd_t no_close_list[3];
265   int i;
266   int rc;
267   char *abs_homedir = NULL;
268   struct daemon_global_s *g = &daemon_global[type];
269   const char *name = gnupg_module_name (daemon_modules[type]);
270 
271   log_assert (type < DAEMON_MAX_TYPE);
272   /* if this fails, you forgot to add your new type to daemon_modules */
273   log_assert (DAEMON_MAX_TYPE == DIM (daemon_modules));
274 
275   if (opt.disable_daemon[type])
276     return gpg_error (GPG_ERR_NOT_SUPPORTED);
277 
278   if (ctrl->d_local[type] && ctrl->d_local[type]->ctx)
279     {
280       ctrl->d_local[type]->in_use = 1;
281       return 0; /* Okay, the context is fine.  */
282     }
283 
284   if (ctrl->d_local[type] && ctrl->d_local[type]->in_use)
285     {
286       log_error ("%s: CTX of type %d is in use\n", __func__, type);
287       return gpg_error (GPG_ERR_INTERNAL);
288     }
289 
290   /* We need to serialize the access to scd_local_list and primary_scd_ctx. */
291   rc = npth_mutex_lock (&start_daemon_lock);
292   if (rc)
293     {
294       log_error ("failed to acquire the start_daemon lock: %s\n",
295                  strerror (rc));
296       return gpg_error (GPG_ERR_INTERNAL);
297     }
298 
299   /* If this is the first call for this session, setup the local data
300      structure. */
301   if (!ctrl->d_local[type])
302     {
303       ctrl->d_local[type] = xtrycalloc (1, sizeof *ctrl->d_local[type]);
304       if (!ctrl->d_local[type])
305         {
306           err = gpg_error_from_syserror ();
307           rc = npth_mutex_unlock (&start_daemon_lock);
308           if (rc)
309             log_error ("failed to release the start_daemon lock: %s\n",
310                        strerror (rc));
311           return err;
312         }
313       ctrl->d_local[type]->g = g;
314       ctrl->d_local[type]->next_local = g->local_list;
315       g->local_list = ctrl->d_local[type];  /* FIXME: CHECK the G thing */
316     }
317 
318   ctrl->d_local[type]->in_use = 1;
319 
320   /* Check whether the pipe server has already been started and in
321      this case either reuse a lingering pipe connection or establish a
322      new socket based one. */
323   if (g->primary_ctx && g->primary_ctx_reusable)
324     {
325       ctx = g->primary_ctx;
326       g->primary_ctx_reusable = 0;
327       if (opt.verbose)
328         log_info ("new connection to %s daemon established (reusing)\n",
329 		  name);
330       goto leave;
331     }
332 
333   rc = assuan_new (&ctx);
334   if (rc)
335     {
336       log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
337       err = rc;
338       goto leave;
339     }
340 
341   if (g->socket_name)
342     {
343       rc = assuan_socket_connect (ctx, g->socket_name, 0, 0);
344       if (rc)
345         {
346           log_error ("can't connect to socket '%s': %s\n",
347                      g->socket_name, gpg_strerror (rc));
348           err = gpg_error (GPG_ERR_NO_SCDAEMON);
349           goto leave;
350         }
351 
352       if (opt.verbose)
353         log_info ("new connection to %s daemon established\n",
354 		  name);
355       goto leave;
356     }
357 
358   if (g->primary_ctx)
359     {
360       log_info ("%s daemon is running but won't accept further connections\n",
361 		name);
362       err = gpg_error (GPG_ERR_NO_SCDAEMON);
363       goto leave;
364     }
365 
366   /* Nope, it has not been started.  Fire it up now. */
367   if (opt.verbose)
368     log_info ("no running %s daemon - starting it\n", name);
369 
370   agent_flush_cache (1);  /* Make sure the PIN cache is flushed.  */
371 
372   if (fflush (NULL))
373     {
374 #ifndef HAVE_W32_SYSTEM
375       err = gpg_error_from_syserror ();
376 #endif
377       log_error ("error flushing pending output: %s\n", strerror (errno));
378       /* At least Windows XP fails here with EBADF.  According to docs
379          and Wine an fflush(NULL) is the same as _flushall.  However
380          the Wime implementation does not flush stdin,stdout and stderr
381          - see above.  Lets try to ignore the error. */
382 #ifndef HAVE_W32_SYSTEM
383       goto leave;
384 #endif
385     }
386 
387   if (!opt.daemon_program[type] || !*opt.daemon_program[type])
388     opt.daemon_program[type] = gnupg_module_name (daemon_modules[type]);
389 
390   if ( !(pgmname = strrchr (opt.daemon_program[type], '/')))
391     pgmname = opt.daemon_program[type];
392   else
393     pgmname++;
394 
395   argv[0] = pgmname;
396   argv[1] = "--multi-server";
397   if (gnupg_default_homedir_p ())
398     argv[2] = NULL;
399   else
400     {
401       abs_homedir = make_absfilename_try (gnupg_homedir (), NULL);
402       if (!abs_homedir)
403         {
404           log_error ("error building filename: %s\n",
405                      gpg_strerror (gpg_error_from_syserror ()));
406           goto leave;
407         }
408 
409       argv[2] = "--homedir";
410       argv[3] = abs_homedir;
411       argv[4] = NULL;
412     }
413 
414   i=0;
415   if (!opt.running_detached)
416     {
417       if (log_get_fd () != -1)
418         no_close_list[i++] = assuan_fd_from_posix_fd (log_get_fd ());
419       no_close_list[i++] = assuan_fd_from_posix_fd (fileno (stderr));
420     }
421   no_close_list[i] = ASSUAN_INVALID_FD;
422 
423   /* Connect to the daemon and perform initial handshaking.  Use
424      detached flag so that under Windows DAEMON does not show up a
425      new window.  */
426   rc = assuan_pipe_connect (ctx, opt.daemon_program[type], argv,
427 			    no_close_list, atfork_cb, NULL,
428                             ASSUAN_PIPE_CONNECT_DETACHED);
429   if (rc)
430     {
431       log_error ("can't connect to the daemon %s: %s\n",
432                  name, gpg_strerror (rc));
433       err = gpg_error (GPG_ERR_NO_SCDAEMON);
434       goto leave;
435     }
436 
437   if (opt.verbose)
438     log_info ("first connection to daemon %s established\n", name);
439 
440 
441   /* Get the name of the additional socket opened by daemon. */
442   {
443     membuf_t data;
444     unsigned char *databuf;
445     size_t datalen;
446 
447     xfree (g->socket_name);
448     g->socket_name = NULL;
449     init_membuf (&data, 256);
450     assuan_transact (ctx, "GETINFO socket_name",
451                      put_membuf_cb, &data, NULL, NULL, NULL, NULL);
452 
453     databuf = get_membuf (&data, &datalen);
454     if (databuf && datalen)
455       {
456         g->socket_name = xtrymalloc (datalen + 1);
457         if (!g->socket_name)
458           log_error ("warning: can't store socket name: %s\n",
459                      strerror (errno));
460         else
461           {
462             memcpy (g->socket_name, databuf, datalen);
463             g->socket_name[datalen] = 0;
464             if (DBG_IPC)
465               log_debug ("additional connections at '%s'\n", g->socket_name);
466           }
467       }
468     xfree (databuf);
469   }
470 
471   /* Tell the daemon we want him to send us an event signal.  We
472      don't support this for W32CE.  */
473 #ifndef HAVE_W32CE_SYSTEM
474   if (opt.sigusr2_enabled)
475     {
476       char buf[100];
477 
478 #ifdef HAVE_W32_SYSTEM
479       snprintf (buf, sizeof buf, "OPTION event-signal=%lx",
480                 (unsigned long)get_agent_daemon_notify_event ());
481 #else
482       snprintf (buf, sizeof buf, "OPTION event-signal=%d", SIGUSR2);
483 #endif
484       assuan_transact (ctx, buf, NULL, NULL, NULL, NULL, NULL, NULL);
485     }
486 #endif /*HAVE_W32CE_SYSTEM*/
487 
488   g->primary_ctx = ctx;
489   g->primary_ctx_reusable = 0;
490 
491   {
492     npth_t thread;
493     npth_attr_t tattr;
494     struct wait_child_thread_parm_s *wctp;
495 
496     wctp = xtrymalloc (sizeof *wctp);
497     if (!wctp)
498       {
499         err = gpg_error_from_syserror ();
500         log_error ("error preparing wait_child_thread: %s\n", strerror (err));
501         goto leave;
502       }
503 
504     wctp->type = type;
505     wctp->pid = assuan_get_pid (g->primary_ctx);
506     err = npth_attr_init (&tattr);
507     if (!err)
508       {
509         npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
510         err = npth_create (&thread, &tattr, wait_child_thread, wctp);
511         if (err)
512           log_error ("error spawning wait_child_thread: %s\n", strerror (err));
513         npth_attr_destroy (&tattr);
514       }
515     else
516       xfree (wctp);
517   }
518 
519  leave:
520   rc = npth_mutex_unlock (&start_daemon_lock);
521   if (rc)
522     log_error ("failed to release the start_daemon lock: %s\n", strerror (rc));
523 
524   xfree (abs_homedir);
525   if (err)
526     {
527       daemon_unlock (type, ctrl, err);
528       if (ctx)
529 	assuan_release (ctx);
530     }
531   else
532     {
533       ctrl->d_local[type]->ctx = ctx;
534       ctrl->d_local[type]->invalid = 0;
535     }
536   return err;
537 }
538 
539 
540 /* This function must be called once to initialize this module.  This
541    has to be done before a second thread is spawned.  We can't do the
542    static initialization because NPth emulation code might not be able
543    to do a static init; in particular, it is not possible for W32. */
544 void
initialize_module_daemon(void)545 initialize_module_daemon (void)
546 {
547   static int initialized;
548   int err;
549 
550   if (!initialized)
551     {
552       err = npth_mutex_init (&start_daemon_lock, NULL);
553       if (err)
554 	log_fatal ("error initializing mutex: %s\n", strerror (err));
555       initialized = 1;
556     }
557 }
558 
559 
560 /* This function may be called to print information pertaining to the
561    current state of this module to the log. */
562 void
agent_daemon_dump_state(void)563 agent_daemon_dump_state (void)
564 {
565   int i;
566 
567   for (i = 0; i < DAEMON_MAX_TYPE; i++) {
568     struct daemon_global_s *g = &daemon_global[i];
569 
570     log_info ("%s: name %s primary_ctx=%p pid=%ld reusable=%d\n", __func__,
571 	      gnupg_module_name (daemon_modules[i]),
572 	      g->primary_ctx,
573 	      (long)assuan_get_pid (g->primary_ctx),
574 	      g->primary_ctx_reusable);
575     if (g->socket_name)
576       log_info ("%s: socket='%s'\n", __func__, g->socket_name);
577   }
578 }
579 
580 
581 /* Check whether the daemon is active.  This is a fast check without
582  * any locking and might give a wrong result if another thread is
583  * about to start the daemon or the daemon is about to be stopped. */
584 int
agent_daemon_check_running(enum daemon_type type)585 agent_daemon_check_running (enum daemon_type type)
586 {
587   return !!daemon_global[type].primary_ctx;
588 }
589 
590 
591 /* Send a kill command to the daemon of TYPE */
592 void
agent_kill_daemon(enum daemon_type type)593 agent_kill_daemon (enum daemon_type type)
594 {
595   struct daemon_global_s *g = &daemon_global[type];
596 
597   if (g->primary_ctx == NULL)
598     return;
599   /* FIXME: This assumes SCdaemon; we should add a new command
600    * (e.g. SHUTDOWN) so that there is no need to have a daemon
601    * specific command.  */
602   assuan_transact (g->primary_ctx, "KILLSCD",
603                    NULL, NULL, NULL, NULL, NULL, NULL);
604   agent_flush_cache (1);  /* 1 := Flush the PIN cache.  */
605 }
606 
607 
608 /* Reset the daemons if they have been used.  Actually it is not a
609    reset but a cleanup of resources used by the current connection. */
610 void
agent_reset_daemon(ctrl_t ctrl)611 agent_reset_daemon (ctrl_t ctrl)
612 {
613   int i;
614   int rc;
615 
616   rc = npth_mutex_lock (&start_daemon_lock);
617   if (rc)
618     {
619       log_error ("failed to acquire the start_daemon lock: %s\n",
620                  strerror (rc));
621       return;
622     }
623 
624 
625   for (i = 0; i < DAEMON_MAX_TYPE; i++)
626     if (ctrl->d_local[i])
627       {
628         struct daemon_global_s *g = ctrl->d_local[i]->g;
629 
630 	if (ctrl->d_local[i]->ctx)
631 	  {
632             /* For the primary connection we send a reset and keep
633              * that connection open for reuse. */
634             if (ctrl->d_local[i]->ctx == g->primary_ctx)
635 	      {
636 		/* Send a RESTART to the daemon.  This is required for the
637 		   primary connection as a kind of virtual EOF; we don't
638 		   have another way to tell it that the next command
639 		   should be viewed as if a new connection has been
640 		   made.  For the non-primary connections this is not
641 		   needed as we simply close the socket.  We don't check
642 		   for an error here because the RESTART may fail for
643 		   example if the daemon has already been terminated.
644 		   Anyway, we need to set the reusable flag to make sure
645 		   that the aliveness check can clean it up. */
646 		assuan_transact (g->primary_ctx, "RESTART",
647 				 NULL, NULL, NULL, NULL, NULL, NULL);
648 		g->primary_ctx_reusable = 1;
649 	      }
650 	    else /* Secondary connections.  */
651 	      assuan_release (ctrl->d_local[i]->ctx);
652 	    ctrl->d_local[i]->ctx = NULL;
653 	  }
654 
655 	/* Remove the local context from our list and release it. */
656 	if (!g->local_list)
657 	  BUG ();
658 	else if (g->local_list == ctrl->d_local[i])
659 	  g->local_list = ctrl->d_local[i]->next_local;
660 	else
661 	  {
662 	    struct daemon_local_s *sl;
663 
664 	    for (sl=g->local_list; sl->next_local; sl = sl->next_local)
665 	      if (sl->next_local == ctrl->d_local[i])
666 		break;
667 	    if (!sl->next_local)
668 	      BUG ();
669 	    sl->next_local = ctrl->d_local[i]->next_local;
670 	  }
671 	xfree (ctrl->d_local[i]);
672 	ctrl->d_local[i] = NULL;
673       }
674 
675 
676   rc = npth_mutex_unlock (&start_daemon_lock);
677   if (rc)
678     log_error ("failed to release the start_daemon lock: %s\n", strerror (rc));
679 }
680 
681 
682 assuan_context_t
daemon_type_ctx(enum daemon_type type,ctrl_t ctrl)683 daemon_type_ctx (enum daemon_type type, ctrl_t ctrl)
684 {
685   return ctrl->d_local[type]->ctx;
686 }
687