1 /* trustlist.c - Maintain the list of trusted keys
2 * Copyright (C) 2002, 2004, 2006, 2007, 2009,
3 * 2012 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
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.
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.
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/>.
33 #include <assuan.h> /* fixme: need a way to avoid assuan calls here */
34 #include "../common/i18n.h"
37 /* A structure to store the information from the trust file. */
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
47 int cm:1; /* Use chain model for validation. */
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 npth_mutex_t trusttable_lock;
60 static const char headerblurb[] =
61 "# This is the list of trusted keys. Comment lines, like this one, as\n"
62 "# well as empty lines are ignored. Lines have a length limit but this\n"
63 "# is not a serious limitation as the format of the entries is fixed and\n"
64 "# checked by gpg-agent. A non-comment line starts with optional white\n"
65 "# space, followed by the SHA-1 fingerpint in hex, followed by a flag\n"
66 "# which may be one of 'P', 'S' or '*' and optionally followed by a list of\n"
67 "# other flags. The fingerprint may be prefixed with a '!' to mark the\n"
68 "# key as not trusted. You should give the gpg-agent a HUP or run the\n"
69 "# command \"gpgconf --reload gpg-agent\" after changing this file.\n"
71 "# Include the default trust list\n"
76 /* This function must be called once to initialize this module. This
77 has to be done before a second thread is spawned. We can't do the
78 static initialization because Pth emulation code might not be able
79 to do a static init; in particular, it is not possible for W32. */
81 initialize_module_trustlist (void)
83 static int initialized;
88 err = npth_mutex_init (&trusttable_lock, NULL);
90 log_fatal ("failed to init mutex in %s: %s\n", __FILE__,strerror (err));
99 lock_trusttable (void)
103 err = npth_mutex_lock (&trusttable_lock);
105 log_fatal ("failed to acquire mutex in %s: %s\n", __FILE__, strerror (err));
110 unlock_trusttable (void)
114 err = npth_mutex_unlock (&trusttable_lock);
116 log_fatal ("failed to release mutex in %s: %s\n", __FILE__, strerror (err));
120 /* Clear the trusttable. The caller needs to make sure that the
121 trusttable is locked. */
123 clear_trusttable (void)
131 /* Return the name of the system trustlist. Caller must free. */
133 make_sys_trustlist_name (void)
135 if (opt.sys_trustlist_name
136 && (strchr (opt.sys_trustlist_name, '/')
137 || strchr (opt.sys_trustlist_name, '\\')
138 || (*opt.sys_trustlist_name == '~'
139 && opt.sys_trustlist_name[1] == '/')))
140 return make_absfilename (opt.sys_trustlist_name, NULL);
142 return make_filename (gnupg_sysconfdir (),
143 (opt.sys_trustlist_name ?
144 opt.sys_trustlist_name : "trustlist.txt"),
150 read_one_trustfile (const char *fname, int systrust,
151 trustitem_t **addr_of_table,
152 size_t *addr_of_tablesize,
153 int *addr_of_tableidx)
159 trustitem_t *table, *ti;
164 table = *addr_of_table;
165 tablesize = *addr_of_tablesize;
166 tableidx = *addr_of_tableidx;
168 fp = es_fopen (fname, "r");
171 err = gpg_error_from_syserror ();
172 log_error (_("error opening '%s': %s\n"), fname, gpg_strerror (err));
176 while (es_fgets (line, DIM(line)-1, fp))
181 if (!n || line[n-1] != '\n')
183 /* Eat until end of line. */
184 while ( (c=es_getc (fp)) != EOF && c != '\n')
186 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
187 : GPG_ERR_INCOMPLETE_LINE);
188 log_error (_("file '%s', line %d: %s\n"),
189 fname, lnr, gpg_strerror (err));
192 line[--n] = 0; /* Chop the LF. */
193 if (n && line[n-1] == '\r')
194 line[--n] = 0; /* Chop an optional CR. */
196 /* Allow for empty lines and spaces */
197 for (p=line; spacep (p); p++)
199 if (!*p || *p == '#')
202 if (!strncmp (p, "include-default", 15)
203 && (!p[15] || spacep (p+15)))
211 log_error (_("statement \"%s\" ignored in '%s', line %d\n"),
212 "include-default", fname, lnr);
215 /* fixme: Should check for trailing garbage. */
217 etcname = make_sys_trustlist_name ();
218 if ( !strcmp (etcname, fname) ) /* Same file. */
219 log_info (_("statement \"%s\" ignored in '%s', line %d\n"),
220 "include-default", fname, lnr);
221 else if ((ec=gnupg_access (etcname, F_OK)) && ec == GPG_ERR_ENOENT)
223 /* A non existent system trustlist is not an error.
224 Just print a note. */
225 log_info (_("system trustlist '%s' not available\n"), etcname);
229 err2 = read_one_trustfile (etcname, 1,
230 &table, &tablesize, &tableidx);
239 if (tableidx == tablesize) /* Need more space. */
244 tmplen = tablesize + 20;
245 tmp = xtryrealloc (table, tmplen * sizeof *table);
248 err = gpg_error_from_syserror ();
255 ti = table + tableidx;
257 memset (&ti->flags, 0, sizeof ti->flags);
260 ti->flags.disabled = 1;
266 n = hexcolon2bin (p, ti->fpr, 20);
269 log_error (_("bad fingerprint in '%s', line %d\n"), fname, lnr);
270 err = gpg_error (GPG_ERR_BAD_DATA);
274 for (; spacep (p); p++)
277 /* Process the first flag which needs to be the first for
278 backward compatibility. */
279 if (!*p || *p == '*' )
281 ti->flags.for_smime = 1;
282 ti->flags.for_pgp = 1;
284 else if ( *p == 'P' || *p == 'p')
286 ti->flags.for_pgp = 1;
288 else if ( *p == 'S' || *p == 's')
290 ti->flags.for_smime = 1;
294 log_error (_("invalid keyflag in '%s', line %d\n"), fname, lnr);
295 err = gpg_error (GPG_ERR_BAD_DATA);
299 if ( *p && !spacep (p) )
301 log_error (_("invalid keyflag in '%s', line %d\n"), fname, lnr);
302 err = gpg_error (GPG_ERR_BAD_DATA);
306 /* Now check for more key-value pairs of the form NAME[=VALUE]. */
309 for (; spacep (p); p++)
313 n = strcspn (p, "= \t");
316 log_error ("assigning a value to a flag is not yet supported; "
317 "in '%s', line %d\n", fname, lnr);
318 err = gpg_error (GPG_ERR_BAD_DATA);
321 else if (n == 5 && !memcmp (p, "relax", 5))
323 else if (n == 2 && !memcmp (p, "cm", 2))
326 log_error ("flag '%.*s' in '%s', line %d ignored\n",
332 if ( !err && !es_feof (fp) )
334 err = gpg_error_from_syserror ();
335 log_error (_("error reading '%s', line %d: %s\n"),
336 fname, lnr, gpg_strerror (err));
341 *addr_of_table = table;
342 *addr_of_tablesize = tablesize;
343 *addr_of_tableidx = tableidx;
348 /* Read the trust files and update the global table on success. The
349 trusttable is assumed to be locked. */
351 read_trustfiles (void)
354 trustitem_t *table, *ti;
362 table = xtrycalloc (tablesize, sizeof *table);
364 return gpg_error_from_syserror ();
367 if (opt.no_user_trustlist)
371 fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
374 err = gpg_error_from_syserror ();
380 if (!fname || (ec = gnupg_access (fname, F_OK)))
383 ; /* --no-user-trustlist active. */
384 else if ( ec == GPG_ERR_ENOENT )
385 ; /* Silently ignore a non-existing trustfile. */
388 err = gpg_error (ec);
389 log_error (_("error opening '%s': %s\n"), fname, gpg_strerror (err));
392 fname = make_sys_trustlist_name ();
395 err = read_one_trustfile (fname, systrust, &table, &tablesize, &tableidx);
401 if (gpg_err_code (err) == GPG_ERR_ENOENT)
403 /* Take a missing trustlist as an empty one. */
410 /* Fixme: we should drop duplicates and sort the table. */
411 ti = xtryrealloc (table, (tableidx?tableidx:1) * sizeof *table);
414 err = gpg_error_from_syserror ();
419 /* Replace the trusttable. */
422 trusttablesize = tableidx;
427 /* Check whether the given fpr is in our trustdb. We expect FPR to be
428 an all uppercase hexstring of 40 characters. If ALREADY_LOCKED is
429 true the function assumes that the trusttable is already locked. */
431 istrusted_internal (ctrl_t ctrl, const char *fpr, int *r_disabled,
435 int locked = already_locked;
438 unsigned char fprbin[20];
443 if ( hexcolon2bin (fpr, fprbin, 20) < 0 )
445 err = gpg_error (GPG_ERR_INV_VALUE);
457 err = read_trustfiles ();
460 log_error (_("error reading list of trusted root certificates\n"));
467 for (ti=trusttable, len = trusttablesize; len; ti++, len--)
468 if (!memcmp (ti->fpr, fprbin, 20))
470 if (ti->flags.disabled && r_disabled)
473 /* Print status messages only if we have not been called
474 in a locked state. */
477 else if (ti->flags.relax)
479 unlock_trusttable ();
481 err = agent_write_status (ctrl, "TRUSTLISTFLAG", "relax", NULL);
483 else if (ti->flags.cm)
485 unlock_trusttable ();
487 err = agent_write_status (ctrl, "TRUSTLISTFLAG", "cm", NULL);
491 err = ti->flags.disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
495 err = gpg_error (GPG_ERR_NOT_TRUSTED);
498 if (locked && !already_locked)
499 unlock_trusttable ();
504 /* Check whether the given fpr is in our trustdb. We expect FPR to be
505 an all uppercase hexstring of 40 characters. */
507 agent_istrusted (ctrl_t ctrl, const char *fpr, int *r_disabled)
509 return istrusted_internal (ctrl, fpr, r_disabled, 0);
513 /* Write all trust entries to FP. */
515 agent_listtrusted (void *assuan_context)
525 err = read_trustfiles ();
528 unlock_trusttable ();
529 log_error (_("error reading list of trusted root certificates\n"));
536 for (ti=trusttable, len = trusttablesize; len; ti++, len--)
538 if (ti->flags.disabled)
540 bin2hex (ti->fpr, 20, key);
542 key[41] = ((ti->flags.for_smime && ti->flags.for_pgp)? '*'
543 : ti->flags.for_smime? 'S': ti->flags.for_pgp? 'P':' ');
545 assuan_send_data (assuan_context, key, 43);
546 assuan_send_data (assuan_context, NULL, 0); /* flush */
550 unlock_trusttable ();
555 /* Create a copy of string with colons inserted after each two bytes.
556 Caller needs to release the string. In case of a memory failure,
559 insert_colons (const char *string)
562 size_t n = strlen (string);
563 size_t nnew = n + (n+1)/2;
565 p = buffer = xtrymalloc ( nnew + 1 );
579 assert (strlen (buffer) <= nnew);
585 /* To pretty print DNs in the Pinentry, we replace slashes by
586 REPLSTRING. The caller needs to free the returned string. NULL is
587 returned on error with ERRNO set. */
589 reformat_name (const char *name, const char *replstring)
595 size_t replstringlen = strlen (replstring);
597 /* If the name does not start with a slash it is not a preformatted
598 DN and thus we don't bother to reformat it. */
600 return xtrystrdup (name);
602 /* Count the names. Note that a slash contained in a DN part is
603 expected to be C style escaped and thus the slashes we see here
604 are the actual part delimiters. */
605 for (s=name+1, count=0; *s; s++)
608 newname = xtrymalloc (strlen (name) + count*replstringlen + 1);
611 for (s=name+1, d=newname; *s; s++)
613 d = stpcpy (d, replstring);
621 /* Insert the given fpr into our trustdb. We expect FPR to be an all
622 uppercase hexstring of 40 characters. FLAG is either 'P' or 'C'.
623 This function does first check whether that key has already been
624 put into the trustdb and returns success in this case. Before a
625 FPR actually gets inserted, the user is asked by means of the
626 Pinentry whether this is actual what he wants to do. */
628 agent_marktrusted (ctrl_t ctrl, const char *name, const char *fpr, int flag)
640 /* Check whether we are at all allowed to modify the trustlist.
641 This is useful so that the trustlist may be a symlink to a global
642 trustlist with only admin privileges to modify it. Of course
643 this is not a secure way of denying access, but it avoids the
644 usual clicking on an Okay button most users are used to. */
645 fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
647 return gpg_error_from_syserror ();
649 if ((ec = access (fname, W_OK)) && ec != GPG_ERR_ENOENT)
652 return gpg_error (GPG_ERR_EPERM);
656 if (!agent_istrusted (ctrl, fpr, &is_disabled))
658 return 0; /* We already got this fingerprint. Silently return
662 /* This feature must explicitly been enabled. */
663 if (!opt.allow_mark_trusted)
664 return gpg_error (GPG_ERR_NOT_SUPPORTED);
668 /* There is an disabled entry in the trustlist. Return an error
669 so that the user won't be asked again for that one. Changing
670 this flag with the integrated marktrusted feature is and will
671 not be made possible. */
672 return gpg_error (GPG_ERR_NOT_TRUSTED);
676 /* Insert a new one. */
677 nameformatted = reformat_name (name, "%0A ");
679 return gpg_error_from_syserror ();
681 /* First a general question whether this is trusted. */
682 desc = xtryasprintf (
683 /* TRANSLATORS: This prompt is shown by the Pinentry
684 and has one special property: A "%%0A" is used by
685 Pinentry to insert a line break. The double
686 percent sign is actually needed because it is also
687 a printf format string. If you need to insert a
688 plain % sign, you need to encode it as "%%25". The
689 "%s" gets replaced by the name as stored in the
691 L_("Do you ultimately trust%%0A"
693 "to correctly certify user certificates?"),
697 xfree (nameformatted);
698 return out_of_core ();
700 err = agent_get_confirmation (ctrl, desc, L_("Yes"), L_("No"), 1);
704 else if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
708 xfree (nameformatted);
713 fprformatted = insert_colons (fpr);
716 xfree (nameformatted);
717 return out_of_core ();
720 /* If the user trusts this certificate he has to verify the
721 fingerprint of course. */
726 /* TRANSLATORS: This prompt is shown by the Pinentry and has
727 one special property: A "%%0A" is used by Pinentry to
728 insert a line break. The double percent sign is actually
729 needed because it is also a printf format string. If you
730 need to insert a plain % sign, you need to encode it as
731 "%%25". The second "%s" gets replaced by a hexdecimal
732 fingerprint string whereas the first one receives the name
733 as stored in the certificate. */
734 L_("Please verify that the certificate identified as:%%0A"
736 "has the fingerprint:%%0A"
737 " %s"), nameformatted, fprformatted);
740 xfree (fprformatted);
741 xfree (nameformatted);
742 return out_of_core ();
745 /* TRANSLATORS: "Correct" is the label of a button and intended
746 to be hit if the fingerprint matches the one of the CA. The
747 other button is "the default "Cancel" of the Pinentry. */
748 err = agent_get_confirmation (ctrl, desc, L_("Correct"), L_("Wrong"), 1);
750 if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
754 xfree (fprformatted);
755 xfree (nameformatted);
761 /* Now check again to avoid duplicates. We take the lock to make
762 sure that nobody else plays with our file and force a reread. */
765 if (!istrusted_internal (ctrl, fpr, &is_disabled, 1) || is_disabled)
767 unlock_trusttable ();
768 xfree (fprformatted);
769 xfree (nameformatted);
770 return is_disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
773 fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
776 err = gpg_error_from_syserror ();
777 unlock_trusttable ();
778 xfree (fprformatted);
779 xfree (nameformatted);
782 if ((ec = access (fname, F_OK)) && ec == GPG_ERR_ENOENT)
784 fp = es_fopen (fname, "wx,mode=-rw-r");
787 err = gpg_error (ec);
788 log_error ("can't create '%s': %s\n", fname, gpg_strerror (err));
790 unlock_trusttable ();
791 xfree (fprformatted);
792 xfree (nameformatted);
795 es_fputs (headerblurb, fp);
798 fp = es_fopen (fname, "a+,mode=-rw-r");
801 err = gpg_error_from_syserror ();
802 log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
804 unlock_trusttable ();
805 xfree (fprformatted);
806 xfree (nameformatted);
810 /* Append the key. */
811 es_fputs ("\n# ", fp);
812 xfree (nameformatted);
813 nameformatted = reformat_name (name, "\n# ");
814 if (!nameformatted || strchr (name, '\n'))
816 /* Note that there should never be a LF in NAME but we better
817 play safe and print a sanitized version in this case. */
818 es_write_sanitized (fp, name, strlen (name), NULL, NULL);
821 es_fputs (nameformatted, fp);
822 es_fprintf (fp, "\n%s%s %c%s\n", yes_i_trust?"":"!", fprformatted, flag,
823 flag == 'S'? " relax":"");
825 err = gpg_error_from_syserror ();
828 err = gpg_error_from_syserror ();
832 unlock_trusttable ();
833 xfree (fprformatted);
834 xfree (nameformatted);
836 bump_key_eventcounter ();
841 /* This function may be called to force reloading of the
844 agent_reload_trustlist (void)
846 /* All we need to do is to delete the trusttable. At the next
847 access it will get re-read. */
850 unlock_trusttable ();
851 bump_key_eventcounter ();