Rename encode.c to encrypt.c.
[gnupg.git] / agent / trustlist.c
bloba0b23b51f9d19b9771303431e7cfe62e22384276
1 /* trustlist.c - Maintain the list of trusted keys
2 * Copyright (C) 2002, 2004, 2006, 2007, 2009 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 3 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, see <http://www.gnu.org/licenses/>.
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>
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"
37 /* A structure to store the information from the trust file. */
38 struct trustitem_s
40 struct
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. */
51 typedef struct trustitem_s trustitem_t;
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;
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";
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)
84 static int initialized;
86 if (!initialized)
88 if (!pth_mutex_init (&trusttable_lock))
89 log_fatal ("error initializing mutex: %s\n", strerror (errno));
90 initialized = 1;
97 static void
98 lock_trusttable (void)
100 if (!pth_mutex_acquire (&trusttable_lock, 0, NULL))
101 log_fatal ("failed to acquire mutex in %s\n", __FILE__);
104 static void
105 unlock_trusttable (void)
107 if (!pth_mutex_release (&trusttable_lock))
108 log_fatal ("failed to release mutex in %s\n", __FILE__);
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)
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;
128 table = *addr_of_table;
129 tablesize = *addr_of_tablesize;
130 tableidx = *addr_of_tableidx;
132 fp = fopen (fname, "r");
133 if (!fp)
135 err = gpg_error_from_syserror ();
136 log_error (_("error opening `%s': %s\n"), fname, gpg_strerror (err));
137 goto leave;
140 while (fgets (line, DIM(line)-1, fp))
142 lnr++;
144 if (!*line || line[strlen(line)-1] != '\n')
146 /* Eat until end of line. */
147 while ( (c=getc (fp)) != EOF && c != '\n')
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;
155 line[strlen(line)-1] = 0; /* Chop the LF. */
157 /* Allow for empty lines and spaces */
158 for (p=line; spacep (p); p++)
160 if (!*p || *p == '#')
161 continue;
163 if (!strncmp (p, "include-default", 15)
164 && (!p[15] || spacep (p+15)))
166 char *etcname;
167 gpg_error_t err2;
169 if (!allow_include)
171 log_error (_("statement \"%s\" ignored in `%s', line %d\n"),
172 "include-default", fname, lnr);
173 continue;
175 /* fixme: Should check for trailing garbage. */
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 )
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);
187 else
189 err2 = read_one_trustfile (etcname, 0,
190 &table, &tablesize, &tableidx);
191 if (err2)
192 err = err2;
194 xfree (etcname);
196 continue;
199 if (tableidx == tablesize) /* Need more space. */
201 trustitem_t *tmp;
202 size_t tmplen;
204 tmplen = tablesize + 20;
205 tmp = xtryrealloc (table, tmplen * sizeof *table);
206 if (!tmp)
208 err = gpg_error_from_syserror ();
209 goto leave;
211 table = tmp;
212 tablesize = tmplen;
215 ti = table + tableidx;
217 memset (&ti->flags, 0, sizeof ti->flags);
218 if (*p == '!')
220 ti->flags.disabled = 1;
221 p++;
222 while (spacep (p))
223 p++;
226 n = hexcolon2bin (p, ti->fpr, 20);
227 if (n < 0)
229 log_error (_("bad fingerprint in `%s', line %d\n"), fname, lnr);
230 err = gpg_error (GPG_ERR_BAD_DATA);
231 continue;
233 p += n;
234 for (; spacep (p); p++)
237 /* Process the first flag which needs to be the first for
238 backward compatibility. */
239 if (!*p || *p == '*' )
241 ti->flags.for_smime = 1;
242 ti->flags.for_pgp = 1;
244 else if ( *p == 'P' || *p == 'p')
246 ti->flags.for_pgp = 1;
248 else if ( *p == 'S' || *p == 's')
250 ti->flags.for_smime = 1;
252 else
254 log_error (_("invalid keyflag in `%s', line %d\n"), fname, lnr);
255 err = gpg_error (GPG_ERR_BAD_DATA);
256 continue;
258 p++;
259 if ( *p && !spacep (p) )
261 log_error (_("invalid keyflag in `%s', line %d\n"), fname, lnr);
262 err = gpg_error (GPG_ERR_BAD_DATA);
263 continue;
266 /* Now check for more key-value pairs of the form NAME[=VALUE]. */
267 while (*p)
269 for (; spacep (p); p++)
271 if (!*p)
272 break;
273 n = strcspn (p, "= \t");
274 if (p[n] == '=')
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++;
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;
290 tableidx++;
292 if ( !err && !feof (fp) )
294 err = gpg_error_from_syserror ();
295 log_error (_("error reading `%s', line %d: %s\n"),
296 fname, lnr, gpg_strerror (err));
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;
309 /* Read the trust files and update the global table on success. */
310 static gpg_error_t
311 read_trustfiles (void)
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;
320 tablesize = 20;
321 table = xtrycalloc (tablesize, sizeof *table);
322 if (!table)
323 return gpg_error_from_syserror ();
324 tableidx = 0;
326 fname = make_filename (opt.homedir, "trustlist.txt", NULL);
327 if ( access (fname, F_OK) )
329 if ( errno == ENOENT )
330 ; /* Silently ignore a non-existing trustfile. */
331 else
333 err = gpg_error_from_syserror ();
334 log_error (_("error opening `%s': %s\n"), fname, gpg_strerror (err));
336 xfree (fname);
337 fname = make_filename (gnupg_sysconfdir (), "trustlist.txt", NULL);
338 allow_include = 0;
340 err = read_one_trustfile (fname, allow_include,
341 &table, &tablesize, &tableidx);
342 xfree (fname);
344 if (err)
346 xfree (table);
347 if (gpg_err_code (err) == GPG_ERR_ENOENT)
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;
357 return err;
360 /* Fixme: we should drop duplicates and sort the table. */
361 ti = xtryrealloc (table, (tableidx?tableidx:1) * sizeof *table);
362 if (!ti)
364 xfree (table);
365 return err;
368 lock_trusttable ();
369 xfree (trusttable);
370 trusttable = table;
371 trusttablesize = tableidx;
372 unlock_trusttable ();
373 return 0;
378 /* Check whether the given fpr is in our trustdb. We expect FPR to be
379 an all uppercase hexstring of 40 characters. */
380 gpg_error_t
381 agent_istrusted (ctrl_t ctrl, const char *fpr, int *r_disabled)
383 gpg_error_t err;
384 trustitem_t *ti;
385 size_t len;
386 unsigned char fprbin[20];
388 if (r_disabled)
389 *r_disabled = 0;
391 if ( hexcolon2bin (fpr, fprbin, 20) < 0 )
392 return gpg_error (GPG_ERR_INV_VALUE);
394 if (!trusttable)
396 err = read_trustfiles ();
397 if (err)
399 log_error (_("error reading list of trusted root certificates\n"));
400 return err;
404 if (trusttable)
406 for (ti=trusttable, len = trusttablesize; len; ti++, len--)
407 if (!memcmp (ti->fpr, fprbin, 20))
409 if (ti->flags.disabled && r_disabled)
410 *r_disabled = 1;
412 if (ti->flags.relax)
414 err = agent_write_status (ctrl,
415 "TRUSTLISTFLAG", "relax",
416 NULL);
417 if (err)
418 return err;
420 else if (ti->flags.cm)
422 err = agent_write_status (ctrl,
423 "TRUSTLISTFLAG", "cm",
424 NULL);
425 if (err)
426 return err;
428 return ti->flags.disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
431 return gpg_error (GPG_ERR_NOT_TRUSTED);
435 /* Write all trust entries to FP. */
436 gpg_error_t
437 agent_listtrusted (void *assuan_context)
439 trustitem_t *ti;
440 char key[51];
441 gpg_error_t err;
442 size_t len;
444 if (!trusttable)
446 err = read_trustfiles ();
447 if (err)
449 log_error (_("error reading list of trusted root certificates\n"));
450 return err;
454 if (trusttable)
456 /* We need to lock the table because the scheduler may interrupt
457 assuan_send_data and an other thread may then re-read the table. */
458 lock_trusttable ();
459 for (ti=trusttable, len = trusttablesize; len; ti++, len--)
461 if (ti->flags.disabled)
462 continue;
463 bin2hex (ti->fpr, 20, key);
464 key[40] = ' ';
465 key[41] = ((ti->flags.for_smime && ti->flags.for_pgp)? '*'
466 : ti->flags.for_smime? 'S': ti->flags.for_pgp? 'P':' ');
467 key[42] = '\n';
468 assuan_send_data (assuan_context, key, 43);
469 assuan_send_data (assuan_context, NULL, 0); /* flush */
471 unlock_trusttable ();
474 return 0;
478 /* Create a copy of string with colons inserted after each two bytes.
479 Caller needs to release the string. In case of a memory failure,
480 NULL is returned. */
481 static char *
482 insert_colons (const char *string)
484 char *buffer, *p;
485 size_t n = strlen (string);
486 size_t nnew = n + (n+1)/2;
488 p = buffer = xtrymalloc ( nnew + 1 );
489 if (!buffer)
490 return NULL;
491 while (*string)
493 *p++ = *string++;
494 if (*string)
496 *p++ = *string++;
497 if (*string)
498 *p++ = ':';
501 *p = 0;
502 assert (strlen (buffer) <= nnew);
504 return buffer;
508 /* To pretty print DNs in the Pinentry, we replace slashes by
509 REPLSTRING. The caller needs to free the returned string. NULL is
510 returned on error with ERRNO set. */
511 static char *
512 reformat_name (const char *name, const char *replstring)
514 const char *s;
515 char *newname;
516 char *d;
517 size_t count;
518 size_t replstringlen = strlen (replstring);
520 /* If the name does not start with a slash it is not a preformatted
521 DN and thus we don't bother to reformat it. */
522 if (*name != '/')
523 return xtrystrdup (name);
525 /* Count the names. Note that a slash contained in a DN part is
526 expected to be C style escaped and thus the slashes we see here
527 are the actual part delimiters. */
528 for (s=name+1, count=0; *s; s++)
529 if (*s == '/')
530 count++;
531 newname = xtrymalloc (strlen (name) + count*replstringlen + 1);
532 if (!newname)
533 return NULL;
534 for (s=name+1, d=newname; *s; s++)
535 if (*s == '/')
536 d = stpcpy (d, replstring);
537 else
538 *d++ = *s;
539 *d = 0;
540 return newname;
544 /* Insert the given fpr into our trustdb. We expect FPR to be an all
545 uppercase hexstring of 40 characters. FLAG is either 'P' or 'C'.
546 This function does first check whether that key has already been put
547 into the trustdb and returns success in this case. Before a FPR
548 actually gets inserted, the user is asked by means of the Pinentry
549 whether this is actual want he wants to do. */
550 gpg_error_t
551 agent_marktrusted (ctrl_t ctrl, const char *name, const char *fpr, int flag)
553 gpg_error_t err = 0;
554 char *desc;
555 char *fname;
556 estream_t fp;
557 char *fprformatted;
558 char *nameformatted;
559 int is_disabled;
560 int yes_i_trust;
562 /* Check whether we are at all allowed to modify the trustlist.
563 This is useful so that the trustlist may be a symlink to a global
564 trustlist with only admin priviliges to modify it. Of course
565 this is not a secure way of denying access, but it avoids the
566 usual clicking on an Okay button most users are used to. */
567 fname = make_filename (opt.homedir, "trustlist.txt", NULL);
568 if ( access (fname, W_OK) && errno != ENOENT)
570 xfree (fname);
571 return gpg_error (GPG_ERR_EPERM);
573 xfree (fname);
575 if (!agent_istrusted (ctrl, fpr, &is_disabled))
577 return 0; /* We already got this fingerprint. Silently return
578 success. */
581 /* This feature must explicitly been enabled. */
582 if (!opt.allow_mark_trusted)
583 return gpg_error (GPG_ERR_NOT_SUPPORTED);
585 if (is_disabled)
587 /* There is an disabled entry in the trustlist. Return an error
588 so that the user won't be asked again for that one. Changing
589 this flag with the integrated marktrusted feature is and will
590 not be made possible. */
591 return gpg_error (GPG_ERR_NOT_TRUSTED);
595 /* Insert a new one. */
596 nameformatted = reformat_name (name, "%0A ");
597 if (!nameformatted)
598 return gpg_error_from_syserror ();
600 /* First a general question whether this is trusted. */
601 desc = xtryasprintf (
602 /* TRANSLATORS: This prompt is shown by the Pinentry
603 and has one special property: A "%%0A" is used by
604 Pinentry to insert a line break. The double
605 percent sign is actually needed because it is also
606 a printf format string. If you need to insert a
607 plain % sign, you need to encode it as "%%25". The
608 "%s" gets replaced by the name as stored in the
609 certificate. */
610 _("Do you ultimately trust%%0A"
611 " \"%s\"%%0A"
612 "to correctly certify user certificates?"),
613 nameformatted);
614 if (!desc)
616 xfree (nameformatted);
617 return out_of_core ();
619 err = agent_get_confirmation (ctrl, desc, _("Yes"), _("No"), 1);
620 xfree (desc);
621 if (!err)
622 yes_i_trust = 1;
623 else if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
624 yes_i_trust = 0;
625 else
627 xfree (nameformatted);
628 return err;
632 fprformatted = insert_colons (fpr);
633 if (!fprformatted)
635 xfree (nameformatted);
636 return out_of_core ();
639 /* If the user trusts this certificate he has to verify the
640 fingerprint of course. */
641 if (yes_i_trust)
643 desc = xtryasprintf
645 /* TRANSLATORS: This prompt is shown by the Pinentry and has
646 one special property: A "%%0A" is used by Pinentry to
647 insert a line break. The double percent sign is actually
648 needed because it is also a printf format string. If you
649 need to insert a plain % sign, you need to encode it as
650 "%%25". The second "%s" gets replaced by a hexdecimal
651 fingerprint string whereas the first one receives the name
652 as stored in the certificate. */
653 _("Please verify that the certificate identified as:%%0A"
654 " \"%s\"%%0A"
655 "has the fingerprint:%%0A"
656 " %s"), nameformatted, fprformatted);
657 if (!desc)
659 xfree (fprformatted);
660 xfree (nameformatted);
661 return out_of_core ();
664 /* TRANSLATORS: "Correct" is the label of a button and intended
665 to be hit if the fingerprint matches the one of the CA. The
666 other button is "the default "Cancel" of the Pinentry. */
667 err = agent_get_confirmation (ctrl, desc, _("Correct"), _("Wrong"), 1);
668 xfree (desc);
669 if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
670 yes_i_trust = 0;
671 else if (err)
673 xfree (fprformatted);
674 xfree (nameformatted);
675 return err;
680 /* Now check again to avoid duplicates. We take the lock to make
681 sure that nobody else plays with our file and force a reread. */
682 lock_trusttable ();
683 agent_reload_trustlist ();
684 if (!agent_istrusted (ctrl, fpr, &is_disabled) || is_disabled)
686 unlock_trusttable ();
687 xfree (fprformatted);
688 xfree (nameformatted);
689 return is_disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
692 fname = make_filename (opt.homedir, "trustlist.txt", NULL);
693 if ( access (fname, F_OK) && errno == ENOENT)
695 fp = es_fopen (fname, "wx");
696 if (!fp)
698 err = gpg_error_from_syserror ();
699 log_error ("can't create `%s': %s\n", fname, gpg_strerror (err));
700 xfree (fname);
701 unlock_trusttable ();
702 xfree (fprformatted);
703 xfree (nameformatted);
704 return err;
706 es_fputs (headerblurb, fp);
707 es_fclose (fp);
709 fp = es_fopen (fname, "a+");
710 if (!fp)
712 err = gpg_error_from_syserror ();
713 log_error ("can't open `%s': %s\n", fname, gpg_strerror (err));
714 xfree (fname);
715 unlock_trusttable ();
716 xfree (fprformatted);
717 xfree (nameformatted);
718 return err;
721 /* Append the key. */
722 es_fputs ("\n# ", fp);
723 xfree (nameformatted);
724 nameformatted = reformat_name (name, "\n# ");
725 if (!nameformatted || strchr (name, '\n'))
727 /* Note that there should never be a LF in NAME but we better
728 play safe and print a sanitized version in this case. */
729 es_write_sanitized (fp, name, strlen (name), NULL, NULL);
731 else
732 es_fputs (nameformatted, fp);
733 es_fprintf (fp, "\n%s%s %c\n", yes_i_trust?"":"!", fprformatted, flag);
734 if (es_ferror (fp))
735 err = gpg_error_from_syserror ();
737 if (es_fclose (fp))
738 err = gpg_error_from_syserror ();
740 agent_reload_trustlist ();
741 xfree (fname);
742 unlock_trusttable ();
743 xfree (fprformatted);
744 xfree (nameformatted);
745 return err;
749 /* This function may be called to force reloading of the
750 trustlist. */
751 void
752 agent_reload_trustlist (void)
754 /* All we need to do is to delete the trusttable. At the next
755 access it will get re-read. */
756 lock_trusttable ();
757 xfree (trusttable);
758 trusttable = NULL;
759 trusttablesize = 0;
760 unlock_trusttable ();
761 bump_key_eventcounter ();