Imported Upstream version 2.0.19
[platform/upstream/gpg2.git] / agent / trustlist.c
1 /* trustlist.c - Maintain the list of trusted keys
2  * Copyright (C) 2002, 2004, 2006, 2007, 2009 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
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 3 of the License, or
9  * (at your option) any later version.
10  *
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.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <assert.h>
27 #include <unistd.h>
28 #include <sys/stat.h>
29 #include <pth.h>
30
31 #include "agent.h"
32 #include <assuan.h> /* fixme: need a way to avoid assuan calls here */
33 #include "i18n.h"
34 #include "estream.h"
35
36
37 /* A structure to store the information from the trust file. */
38 struct trustitem_s
39 {
40   struct
41   {
42     int disabled:1;       /* This entry is disabled.  */
43     int for_pgp:1;        /* Set by '*' or 'P' as first flag. */
44     int for_smime:1;      /* Set by '*' or 'S' as first flag. */
45     int relax:1;          /* Relax checking of root certificate
46                              constraints. */
47     int cm:1;             /* Use chain model for validation. */
48   } flags;
49   unsigned char fpr[20];  /* The binary fingerprint. */
50 };
51 typedef struct trustitem_s trustitem_t;
52
53 /* Malloced table and its allocated size with all trust items. */
54 static trustitem_t *trusttable; 
55 static size_t trusttablesize; 
56 /* A mutex used to protect the table. */
57 static pth_mutex_t trusttable_lock;
58
59
60
61 static const char headerblurb[] =
62 "# This is the list of trusted keys.  Comment lines, like this one, as\n"
63 "# well as empty lines are ignored.  Lines have a length limit but this\n"
64 "# is not a serious limitation as the format of the entries is fixed and\n"
65 "# checked by gpg-agent.  A non-comment line starts with optional white\n"
66 "# space, followed by the SHA-1 fingerpint in hex, followed by a flag\n"
67 "# which may be one of 'P', 'S' or '*' and optionally followed by a list of\n"
68 "# other flags.  The fingerprint may be prefixed with a '!' to mark the\n"
69 "# key as not trusted.  You should give the gpg-agent a HUP or run the\n"
70 "# command \"gpgconf --reload gpg-agent\" after changing this file.\n"
71 "\n\n"
72 "# Include the default trust list\n"
73 "include-default\n"
74 "\n";
75
76
77 /* This function must be called once to initialize this module.  This
78    has to be done before a second thread is spawned.  We can't do the
79    static initialization because Pth emulation code might not be able
80    to do a static init; in particular, it is not possible for W32. */
81 void
82 initialize_module_trustlist (void)
83 {
84   static int initialized;
85
86   if (!initialized)
87     {
88       if (!pth_mutex_init (&trusttable_lock))
89         log_fatal ("error initializing mutex: %s\n", strerror (errno));
90       initialized = 1;
91     }
92 }
93
94
95
96 \f
97 static void
98 lock_trusttable (void)
99 {
100   if (!pth_mutex_acquire (&trusttable_lock, 0, NULL))
101     log_fatal ("failed to acquire mutex in %s\n", __FILE__);
102 }
103
104 static void
105 unlock_trusttable (void)
106 {
107   if (!pth_mutex_release (&trusttable_lock))
108     log_fatal ("failed to release mutex in %s\n", __FILE__);
109 }
110
111
112
113 static gpg_error_t
114 read_one_trustfile (const char *fname, int allow_include,
115                     trustitem_t **addr_of_table, 
116                     size_t *addr_of_tablesize,
117                     int *addr_of_tableidx)
118 {
119   gpg_error_t err = 0;
120   FILE *fp;
121   int n, c;
122   char *p, line[256];
123   trustitem_t *table, *ti;
124   int tableidx;
125   size_t tablesize;
126   int lnr = 0;
127   
128   table = *addr_of_table;
129   tablesize = *addr_of_tablesize;
130   tableidx = *addr_of_tableidx;
131
132   fp = fopen (fname, "r");
133   if (!fp)
134     {
135       err = gpg_error_from_syserror ();
136       log_error (_("error opening `%s': %s\n"), fname, gpg_strerror (err));
137       goto leave;
138     }
139
140   while (fgets (line, DIM(line)-1, fp))
141     {
142       lnr++;
143       
144       if (!*line || line[strlen(line)-1] != '\n')
145         {
146           /* Eat until end of line. */
147           while ( (c=getc (fp)) != EOF && c != '\n')
148             ;
149           err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
150                            : GPG_ERR_INCOMPLETE_LINE);
151           log_error (_("file `%s', line %d: %s\n"),
152                      fname, lnr, gpg_strerror (err));
153           continue;
154         }
155       line[strlen(line)-1] = 0; /* Chop the LF. */
156       
157       /* Allow for empty lines and spaces */
158       for (p=line; spacep (p); p++)
159         ;
160       if (!*p || *p == '#')
161         continue;
162   
163       if (!strncmp (p, "include-default", 15)
164           && (!p[15] || spacep (p+15)))
165         {
166           char *etcname;
167           gpg_error_t err2;
168
169           if (!allow_include)
170             {
171               log_error (_("statement \"%s\" ignored in `%s', line %d\n"),
172                          "include-default", fname, lnr);
173               continue;
174             }
175           /* fixme: Should check for trailing garbage.  */
176
177           etcname = make_filename (gnupg_sysconfdir (), "trustlist.txt", NULL);
178           if ( !strcmp (etcname, fname) ) /* Same file. */
179             log_info (_("statement \"%s\" ignored in `%s', line %d\n"),
180                       "include-default", fname, lnr);
181           else if ( access (etcname, F_OK) && errno == ENOENT )
182             {
183               /* A non existent system trustlist is not an error.
184                  Just print a note. */
185               log_info (_("system trustlist `%s' not available\n"), etcname);
186             }
187           else
188             {
189               err2 = read_one_trustfile (etcname, 0,
190                                          &table, &tablesize, &tableidx);
191               if (err2)
192                 err = err2;
193             }
194           xfree (etcname);
195           
196           continue;
197         }
198
199       if (tableidx == tablesize)  /* Need more space. */
200         {
201           trustitem_t *tmp;
202           size_t tmplen;
203           
204           tmplen = tablesize + 20;
205           tmp = xtryrealloc (table, tmplen * sizeof *table);
206           if (!tmp)
207             {
208               err = gpg_error_from_syserror ();
209               goto leave;
210             }
211           table = tmp;
212           tablesize = tmplen;
213         }
214
215       ti = table + tableidx;
216
217       memset (&ti->flags, 0, sizeof ti->flags);
218       if (*p == '!')
219         {
220           ti->flags.disabled = 1;
221           p++;
222           while (spacep (p))
223             p++;
224         }
225
226       n = hexcolon2bin (p, ti->fpr, 20);
227       if (n < 0)
228         {
229           log_error (_("bad fingerprint in `%s', line %d\n"), fname, lnr);
230           err = gpg_error (GPG_ERR_BAD_DATA); 
231           continue;
232         }
233       p += n;
234       for (; spacep (p); p++)
235         ;
236       
237       /* Process the first flag which needs to be the first for
238          backward compatibility. */
239       if (!*p || *p == '*' )
240         {
241           ti->flags.for_smime = 1;
242           ti->flags.for_pgp = 1;
243         }
244       else if ( *p == 'P' || *p == 'p')
245         {
246           ti->flags.for_pgp = 1;
247         }
248       else if ( *p == 'S' || *p == 's')
249         {
250           ti->flags.for_smime = 1;
251         }
252       else
253         {
254           log_error (_("invalid keyflag in `%s', line %d\n"), fname, lnr);
255           err = gpg_error (GPG_ERR_BAD_DATA);
256           continue;
257         }
258       p++;
259       if ( *p && !spacep (p) )
260         {
261           log_error (_("invalid keyflag in `%s', line %d\n"), fname, lnr);
262           err = gpg_error (GPG_ERR_BAD_DATA);
263           continue;
264         }
265
266       /* Now check for more key-value pairs of the form NAME[=VALUE]. */
267       while (*p)
268         {
269           for (; spacep (p); p++)
270             ;
271           if (!*p)
272             break;
273           n = strcspn (p, "= \t");
274           if (p[n] == '=')
275             {
276               log_error ("assigning a value to a flag is not yet supported; "
277                          "in `%s', line %d\n", fname, lnr);
278               err = gpg_error (GPG_ERR_BAD_DATA);
279               p++;
280             }
281           else if (n == 5 && !memcmp (p, "relax", 5))
282             ti->flags.relax = 1;
283           else if (n == 2 && !memcmp (p, "cm", 2))
284             ti->flags.cm = 1;
285           else
286             log_error ("flag `%.*s' in `%s', line %d ignored\n",
287                        n, p, fname, lnr);
288           p += n;
289         }
290       tableidx++;
291     }
292   if ( !err && !feof (fp) )
293     {
294       err = gpg_error_from_syserror ();
295       log_error (_("error reading `%s', line %d: %s\n"),
296                  fname, lnr, gpg_strerror (err));
297     }
298
299  leave:
300   if (fp)
301     fclose (fp);
302   *addr_of_table = table;
303   *addr_of_tablesize = tablesize;
304   *addr_of_tableidx = tableidx;
305   return err;
306 }
307
308
309 /* Read the trust files and update the global table on success.  */
310 static gpg_error_t
311 read_trustfiles (void)
312 {
313   gpg_error_t err;
314   trustitem_t *table, *ti;
315   int tableidx;
316   size_t tablesize;
317   char *fname;
318   int allow_include = 1;
319
320   tablesize = 20;
321   table = xtrycalloc (tablesize, sizeof *table);
322   if (!table)
323     return gpg_error_from_syserror ();
324   tableidx = 0;
325
326   fname = make_filename (opt.homedir, "trustlist.txt", NULL);
327   if ( access (fname, F_OK) )
328     {
329       if ( errno == ENOENT )
330         ; /* Silently ignore a non-existing trustfile.  */
331       else
332         {
333           err = gpg_error_from_syserror ();
334           log_error (_("error opening `%s': %s\n"), fname, gpg_strerror (err));
335         }
336       xfree (fname);
337       fname = make_filename (gnupg_sysconfdir (), "trustlist.txt", NULL);
338       allow_include = 0;
339     }
340   err = read_one_trustfile (fname, allow_include,
341                             &table, &tablesize, &tableidx);
342   xfree (fname);
343
344   if (err)
345     {
346       xfree (table);
347       if (gpg_err_code (err) == GPG_ERR_ENOENT)
348         {
349           /* Take a missing trustlist as an empty one.  */
350           lock_trusttable ();
351           xfree (trusttable);
352           trusttable = NULL;
353           trusttablesize = 0;
354           unlock_trusttable ();
355           err = 0;
356         }
357       return err;
358     }
359
360   /* Fixme: we should drop duplicates and sort the table. */
361   ti = xtryrealloc (table, (tableidx?tableidx:1) * sizeof *table);
362   if (!ti)
363     {
364       err = gpg_error_from_syserror ();
365       xfree (table);
366       return err;
367     }
368
369   lock_trusttable ();
370   xfree (trusttable);
371   trusttable = ti;
372   trusttablesize = tableidx;
373   unlock_trusttable ();
374   return 0;
375 }
376
377
378
379 /* Check whether the given fpr is in our trustdb.  We expect FPR to be
380    an all uppercase hexstring of 40 characters. */
381 gpg_error_t 
382 agent_istrusted (ctrl_t ctrl, const char *fpr, int *r_disabled)
383 {
384   gpg_error_t err;
385   trustitem_t *ti;
386   size_t len;
387   unsigned char fprbin[20];
388
389   if (r_disabled)
390     *r_disabled = 0;
391
392   if ( hexcolon2bin (fpr, fprbin, 20) < 0 )
393     return gpg_error (GPG_ERR_INV_VALUE);
394
395   if (!trusttable)
396     {
397       err = read_trustfiles ();
398       if (err)
399         {
400           log_error (_("error reading list of trusted root certificates\n"));
401           return err;
402         }
403     }
404
405   if (trusttable)
406     {
407       for (ti=trusttable, len = trusttablesize; len; ti++, len--)
408         if (!memcmp (ti->fpr, fprbin, 20))
409           {
410             if (ti->flags.disabled && r_disabled)
411               *r_disabled = 1;
412
413             if (ti->flags.relax)
414               {
415                 err = agent_write_status (ctrl,
416                                           "TRUSTLISTFLAG", "relax", 
417                                           NULL);
418                 if (err)
419                   return err;
420               }
421             else if (ti->flags.cm)
422               {
423                 err = agent_write_status (ctrl,
424                                           "TRUSTLISTFLAG", "cm", 
425                                           NULL);
426                 if (err)
427                   return err;
428               }
429             return ti->flags.disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
430           }
431     }
432   return gpg_error (GPG_ERR_NOT_TRUSTED);
433 }
434
435
436 /* Write all trust entries to FP. */
437 gpg_error_t 
438 agent_listtrusted (void *assuan_context)
439 {
440   trustitem_t *ti;
441   char key[51];
442   gpg_error_t err;
443   size_t len;
444
445   if (!trusttable)
446     {
447       err = read_trustfiles ();
448       if (err)
449         {
450           log_error (_("error reading list of trusted root certificates\n"));
451           return err;
452         }
453     }
454
455   if (trusttable)
456     {
457       /* We need to lock the table because the scheduler may interrupt
458          assuan_send_data and an other thread may then re-read the table. */
459       lock_trusttable ();
460       for (ti=trusttable, len = trusttablesize; len; ti++, len--)
461         {
462           if (ti->flags.disabled)
463             continue;
464           bin2hex (ti->fpr, 20, key);
465           key[40] = ' ';
466           key[41] = ((ti->flags.for_smime && ti->flags.for_pgp)? '*'
467                      : ti->flags.for_smime? 'S': ti->flags.for_pgp? 'P':' ');
468           key[42] = '\n';
469           assuan_send_data (assuan_context, key, 43);
470           assuan_send_data (assuan_context, NULL, 0); /* flush */
471         }
472       unlock_trusttable ();
473     }
474
475   return 0;
476 }
477
478
479 /* Create a copy of string with colons inserted after each two bytes.
480    Caller needs to release the string.  In case of a memory failure,
481    NULL is returned.  */
482 static char *
483 insert_colons (const char *string)
484 {
485   char *buffer, *p;
486   size_t n = strlen (string);
487   size_t nnew = n + (n+1)/2;
488
489   p = buffer = xtrymalloc ( nnew + 1 );
490   if (!buffer)
491     return NULL;
492   while (*string)
493     {
494       *p++ = *string++;
495       if (*string)
496         {
497           *p++ = *string++;
498           if (*string)
499             *p++ = ':';
500         }
501     }
502   *p = 0;
503   assert (strlen (buffer) <= nnew);
504
505   return buffer;
506 }
507
508
509 /* To pretty print DNs in the Pinentry, we replace slashes by
510    REPLSTRING.  The caller needs to free the returned string.  NULL is
511    returned on error with ERRNO set.  */
512 static char *
513 reformat_name (const char *name, const char *replstring)
514 {
515   const char *s;
516   char *newname;
517   char *d;
518   size_t count;
519   size_t replstringlen = strlen (replstring);
520
521   /* If the name does not start with a slash it is not a preformatted
522      DN and thus we don't bother to reformat it.  */
523   if (*name != '/')
524     return xtrystrdup (name);
525
526   /* Count the names.  Note that a slash contained in a DN part is
527      expected to be C style escaped and thus the slashes we see here
528      are the actual part delimiters.  */
529   for (s=name+1, count=0; *s; s++)
530     if (*s == '/')
531       count++;
532   newname = xtrymalloc (strlen (name) + count*replstringlen + 1);
533   if (!newname)
534     return NULL; 
535   for (s=name+1, d=newname; *s; s++)
536     if (*s == '/')
537       d = stpcpy (d, replstring);
538     else
539       *d++ = *s;
540   *d = 0;
541   return newname;
542 }
543
544
545 /* Insert the given fpr into our trustdb.  We expect FPR to be an all
546    uppercase hexstring of 40 characters. FLAG is either 'P' or 'C'.
547    This function does first check whether that key has already been put
548    into the trustdb and returns success in this case.  Before a FPR
549    actually gets inserted, the user is asked by means of the Pinentry
550    whether this is actual want he wants to do.  */
551 gpg_error_t
552 agent_marktrusted (ctrl_t ctrl, const char *name, const char *fpr, int flag)
553 {
554   gpg_error_t err = 0;
555   char *desc;
556   char *fname;
557   estream_t fp;
558   char *fprformatted;
559   char *nameformatted;
560   int is_disabled;
561   int yes_i_trust;
562
563   /* Check whether we are at all allowed to modify the trustlist.
564      This is useful so that the trustlist may be a symlink to a global
565      trustlist with only admin priviliges to modify it.  Of course
566      this is not a secure way of denying access, but it avoids the
567      usual clicking on an Okay button most users are used to. */
568   fname = make_filename (opt.homedir, "trustlist.txt", NULL);
569   if ( access (fname, W_OK) && errno != ENOENT)
570     {
571       xfree (fname);
572       return gpg_error (GPG_ERR_EPERM);
573     }    
574   xfree (fname);
575
576   if (!agent_istrusted (ctrl, fpr, &is_disabled))
577     {
578       return 0; /* We already got this fingerprint.  Silently return
579                    success. */
580     }
581   
582   /* This feature must explicitly been enabled. */
583   if (!opt.allow_mark_trusted)
584     return gpg_error (GPG_ERR_NOT_SUPPORTED);
585
586   if (is_disabled)
587     {
588       /* There is an disabled entry in the trustlist.  Return an error
589          so that the user won't be asked again for that one.  Changing
590          this flag with the integrated marktrusted feature is and will
591          not be made possible.  */
592       return gpg_error (GPG_ERR_NOT_TRUSTED);
593     }
594
595
596   /* Insert a new one. */
597   nameformatted = reformat_name (name, "%0A   ");
598   if (!nameformatted)
599     return gpg_error_from_syserror ();
600
601   /* First a general question whether this is trusted.  */
602   desc = xtryasprintf (
603                 /* TRANSLATORS: This prompt is shown by the Pinentry
604                    and has one special property: A "%%0A" is used by
605                    Pinentry to insert a line break.  The double
606                    percent sign is actually needed because it is also
607                    a printf format string.  If you need to insert a
608                    plain % sign, you need to encode it as "%%25".  The
609                    "%s" gets replaced by the name as stored in the
610                    certificate. */
611                 _("Do you ultimately trust%%0A"
612                   "  \"%s\"%%0A"
613                   "to correctly certify user certificates?"),
614                 nameformatted);
615   if (!desc)
616     {
617       xfree (nameformatted);
618       return out_of_core ();
619     }
620   err = agent_get_confirmation (ctrl, desc, _("Yes"), _("No"), 1);
621   xfree (desc);
622   if (!err)
623     yes_i_trust = 1;
624   else if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
625     yes_i_trust = 0;
626   else
627     {
628       xfree (nameformatted);
629       return err;
630     }
631     
632
633   fprformatted = insert_colons (fpr);
634   if (!fprformatted)
635     {
636       xfree (nameformatted);
637       return out_of_core ();
638     }
639
640   /* If the user trusts this certificate he has to verify the
641      fingerprint of course.  */
642   if (yes_i_trust)
643     {
644       desc = xtryasprintf 
645         (
646          /* TRANSLATORS: This prompt is shown by the Pinentry and has
647             one special property: A "%%0A" is used by Pinentry to
648             insert a line break.  The double percent sign is actually
649             needed because it is also a printf format string.  If you
650             need to insert a plain % sign, you need to encode it as
651             "%%25".  The second "%s" gets replaced by a hexdecimal
652             fingerprint string whereas the first one receives the name
653             as stored in the certificate. */
654          _("Please verify that the certificate identified as:%%0A"
655            "  \"%s\"%%0A"
656            "has the fingerprint:%%0A"
657            "  %s"), nameformatted, fprformatted);
658       if (!desc)
659         {
660           xfree (fprformatted);
661           xfree (nameformatted);
662           return out_of_core ();
663         }
664       
665       /* TRANSLATORS: "Correct" is the label of a button and intended
666          to be hit if the fingerprint matches the one of the CA.  The
667          other button is "the default "Cancel" of the Pinentry. */
668       err = agent_get_confirmation (ctrl, desc, _("Correct"), _("Wrong"), 1);
669       xfree (desc);
670       if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
671         yes_i_trust = 0;
672       else if (err)
673         {
674           xfree (fprformatted);
675           xfree (nameformatted);
676           return err;
677         }
678     }
679
680
681   /* Now check again to avoid duplicates.  We take the lock to make
682      sure that nobody else plays with our file and force a reread.  */
683   lock_trusttable ();
684   agent_reload_trustlist ();
685   if (!agent_istrusted (ctrl, fpr, &is_disabled) || is_disabled)
686     {
687       unlock_trusttable ();
688       xfree (fprformatted);
689       xfree (nameformatted);
690       return is_disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0; 
691     }
692
693   fname = make_filename (opt.homedir, "trustlist.txt", NULL);
694   if ( access (fname, F_OK) && errno == ENOENT)
695     {
696       fp = es_fopen (fname, "wx");
697       if (!fp)
698         {
699           err = gpg_error_from_syserror ();
700           log_error ("can't create `%s': %s\n", fname, gpg_strerror (err));
701           xfree (fname);
702           unlock_trusttable ();
703           xfree (fprformatted);
704           xfree (nameformatted);
705           return err;
706         }
707       es_fputs (headerblurb, fp);
708       es_fclose (fp);
709     }
710   fp = es_fopen (fname, "a+");
711   if (!fp)
712     {
713       err = gpg_error_from_syserror ();
714       log_error ("can't open `%s': %s\n", fname, gpg_strerror (err));
715       xfree (fname);
716       unlock_trusttable ();
717       xfree (fprformatted);
718       xfree (nameformatted);
719       return err;
720     }
721
722   /* Append the key. */
723   es_fputs ("\n# ", fp);
724   xfree (nameformatted);
725   nameformatted = reformat_name (name, "\n# ");
726   if (!nameformatted || strchr (name, '\n'))
727     {
728       /* Note that there should never be a LF in NAME but we better
729          play safe and print a sanitized version in this case.  */
730       es_write_sanitized (fp, name, strlen (name), NULL, NULL);
731     }
732   else
733     es_fputs (nameformatted, fp);
734   es_fprintf (fp, "\n%s%s %c\n", yes_i_trust?"":"!", fprformatted, flag);
735   if (es_ferror (fp))
736     err = gpg_error_from_syserror ();
737   
738   if (es_fclose (fp))
739     err = gpg_error_from_syserror ();
740
741   agent_reload_trustlist ();
742   xfree (fname);
743   unlock_trusttable ();
744   xfree (fprformatted);
745   xfree (nameformatted);
746   return err;
747 }
748
749
750 /* This function may be called to force reloading of the
751    trustlist.  */
752 void
753 agent_reload_trustlist (void)
754 {
755   /* All we need to do is to delete the trusttable.  At the next
756      access it will get re-read. */
757   lock_trusttable ();
758   xfree (trusttable);
759   trusttable = NULL;
760   trusttablesize = 0;
761   unlock_trusttable ();
762   bump_key_eventcounter ();
763 }