Prepare for OpenPGP cards with extended length support.
[gnupg.git] / agent / trustlist.c
blob5fd364cc6fbc17b21c7f43b0a90f6faf3e94dd3c
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"
36 /* A structure to store the information from the trust file. */
37 struct trustitem_s
39 struct
41 int disabled:1; /* This entry is disabled. */
42 int for_pgp:1; /* Set by '*' or 'P' as first flag. */
43 int for_smime:1; /* Set by '*' or 'S' as first flag. */
44 int relax:1; /* Relax checking of root certificate
45 constraints. */
46 int cm:1; /* Use chain model for validation. */
47 } flags;
48 unsigned char fpr[20]; /* The binary fingerprint. */
50 typedef struct trustitem_s trustitem_t;
52 /* Malloced table and its allocated size with all trust items. */
53 static trustitem_t *trusttable;
54 static size_t trusttablesize;
55 /* A mutex used to protect the table. */
56 static pth_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"
70 "\n\n"
71 "# Include the default trust list\n"
72 "include-default\n"
73 "\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. */
80 void
81 initialize_module_trustlist (void)
83 static int initialized;
85 if (!initialized)
87 if (!pth_mutex_init (&trusttable_lock))
88 log_fatal ("error initializing mutex: %s\n", strerror (errno));
89 initialized = 1;
96 static void
97 lock_trusttable (void)
99 if (!pth_mutex_acquire (&trusttable_lock, 0, NULL))
100 log_fatal ("failed to acquire mutex in %s\n", __FILE__);
103 static void
104 unlock_trusttable (void)
106 if (!pth_mutex_release (&trusttable_lock))
107 log_fatal ("failed to release mutex in %s\n", __FILE__);
112 static gpg_error_t
113 read_one_trustfile (const char *fname, int allow_include,
114 trustitem_t **addr_of_table,
115 size_t *addr_of_tablesize,
116 int *addr_of_tableidx)
118 gpg_error_t err = 0;
119 FILE *fp;
120 int n, c;
121 char *p, line[256];
122 trustitem_t *table, *ti;
123 int tableidx;
124 size_t tablesize;
125 int lnr = 0;
127 table = *addr_of_table;
128 tablesize = *addr_of_tablesize;
129 tableidx = *addr_of_tableidx;
131 fp = fopen (fname, "r");
132 if (!fp)
134 err = gpg_error_from_syserror ();
135 log_error (_("error opening `%s': %s\n"), fname, gpg_strerror (err));
136 goto leave;
139 while (fgets (line, DIM(line)-1, fp))
141 lnr++;
143 if (!*line || line[strlen(line)-1] != '\n')
145 /* Eat until end of line. */
146 while ( (c=getc (fp)) != EOF && c != '\n')
148 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
149 : GPG_ERR_INCOMPLETE_LINE);
150 log_error (_("file `%s', line %d: %s\n"),
151 fname, lnr, gpg_strerror (err));
152 continue;
154 line[strlen(line)-1] = 0; /* Chop the LF. */
156 /* Allow for empty lines and spaces */
157 for (p=line; spacep (p); p++)
159 if (!*p || *p == '#')
160 continue;
162 if (!strncmp (p, "include-default", 15)
163 && (!p[15] || spacep (p+15)))
165 char *etcname;
166 gpg_error_t err2;
168 if (!allow_include)
170 log_error (_("statement \"%s\" ignored in `%s', line %d\n"),
171 "include-default", fname, lnr);
172 continue;
174 /* fixme: Should check for trailing garbage. */
176 etcname = make_filename (gnupg_sysconfdir (), "trustlist.txt", NULL);
177 if ( !strcmp (etcname, fname) ) /* Same file. */
178 log_info (_("statement \"%s\" ignored in `%s', line %d\n"),
179 "include-default", fname, lnr);
180 else if ( access (etcname, F_OK) && errno == ENOENT )
182 /* A non existent system trustlist is not an error.
183 Just print a note. */
184 log_info (_("system trustlist `%s' not available\n"), etcname);
186 else
188 err2 = read_one_trustfile (etcname, 0,
189 &table, &tablesize, &tableidx);
190 if (err2)
191 err = err2;
193 xfree (etcname);
195 continue;
198 if (tableidx == tablesize) /* Need more space. */
200 trustitem_t *tmp;
201 size_t tmplen;
203 tmplen = tablesize + 20;
204 tmp = xtryrealloc (table, tmplen * sizeof *table);
205 if (!tmp)
207 err = gpg_error_from_syserror ();
208 goto leave;
210 table = tmp;
211 tablesize = tmplen;
214 ti = table + tableidx;
216 memset (&ti->flags, 0, sizeof ti->flags);
217 if (*p == '!')
219 ti->flags.disabled = 1;
220 p++;
221 while (spacep (p))
222 p++;
225 n = hexcolon2bin (p, ti->fpr, 20);
226 if (n < 0)
228 log_error (_("bad fingerprint in `%s', line %d\n"), fname, lnr);
229 err = gpg_error (GPG_ERR_BAD_DATA);
230 continue;
232 p += n;
233 for (; spacep (p); p++)
236 /* Process the first flag which needs to be the first for
237 backward compatibility. */
238 if (!*p || *p == '*' )
240 ti->flags.for_smime = 1;
241 ti->flags.for_pgp = 1;
243 else if ( *p == 'P' || *p == 'p')
245 ti->flags.for_pgp = 1;
247 else if ( *p == 'S' || *p == 's')
249 ti->flags.for_smime = 1;
251 else
253 log_error (_("invalid keyflag in `%s', line %d\n"), fname, lnr);
254 err = gpg_error (GPG_ERR_BAD_DATA);
255 continue;
257 p++;
258 if ( *p && !spacep (p) )
260 log_error (_("invalid keyflag in `%s', line %d\n"), fname, lnr);
261 err = gpg_error (GPG_ERR_BAD_DATA);
262 continue;
265 /* Now check for more key-value pairs of the form NAME[=VALUE]. */
266 while (*p)
268 for (; spacep (p); p++)
270 if (!*p)
271 break;
272 n = strcspn (p, "= \t");
273 if (p[n] == '=')
275 log_error ("assigning a value to a flag is not yet supported; "
276 "in `%s', line %d\n", fname, lnr);
277 err = gpg_error (GPG_ERR_BAD_DATA);
278 p++;
280 else if (n == 5 && !memcmp (p, "relax", 5))
281 ti->flags.relax = 1;
282 else if (n == 2 && !memcmp (p, "cm", 2))
283 ti->flags.cm = 1;
284 else
285 log_error ("flag `%.*s' in `%s', line %d ignored\n",
286 n, p, fname, lnr);
287 p += n;
289 tableidx++;
291 if ( !err && !feof (fp) )
293 err = gpg_error_from_syserror ();
294 log_error (_("error reading `%s', line %d: %s\n"),
295 fname, lnr, gpg_strerror (err));
298 leave:
299 if (fp)
300 fclose (fp);
301 *addr_of_table = table;
302 *addr_of_tablesize = tablesize;
303 *addr_of_tableidx = tableidx;
304 return err;
308 /* Read the trust files and update the global table on success. */
309 static gpg_error_t
310 read_trustfiles (void)
312 gpg_error_t err;
313 trustitem_t *table, *ti;
314 int tableidx;
315 size_t tablesize;
316 char *fname;
317 int allow_include = 1;
319 tablesize = 20;
320 table = xtrycalloc (tablesize, sizeof *table);
321 if (!table)
322 return gpg_error_from_syserror ();
323 tableidx = 0;
325 fname = make_filename (opt.homedir, "trustlist.txt", NULL);
326 if ( access (fname, F_OK) )
328 if ( errno == ENOENT )
329 ; /* Silently ignore a non-existing trustfile. */
330 else
332 err = gpg_error_from_syserror ();
333 log_error (_("error opening `%s': %s\n"), fname, gpg_strerror (err));
335 xfree (fname);
336 fname = make_filename (gnupg_sysconfdir (), "trustlist.txt", NULL);
337 allow_include = 0;
339 err = read_one_trustfile (fname, allow_include,
340 &table, &tablesize, &tableidx);
341 xfree (fname);
343 if (err)
345 xfree (table);
346 if (gpg_err_code (err) == GPG_ERR_ENOENT)
348 /* Take a missing trustlist as an empty one. */
349 lock_trusttable ();
350 xfree (trusttable);
351 trusttable = NULL;
352 trusttablesize = 0;
353 unlock_trusttable ();
354 err = 0;
356 return err;
359 /* Fixme: we should drop duplicates and sort the table. */
360 ti = xtryrealloc (table, (tableidx?tableidx:1) * sizeof *table);
361 if (!ti)
363 xfree (table);
364 return err;
367 lock_trusttable ();
368 xfree (trusttable);
369 trusttable = table;
370 trusttablesize = tableidx;
371 unlock_trusttable ();
372 return 0;
377 /* Check whether the given fpr is in our trustdb. We expect FPR to be
378 an all uppercase hexstring of 40 characters. */
379 gpg_error_t
380 agent_istrusted (ctrl_t ctrl, const char *fpr, int *r_disabled)
382 gpg_error_t err;
383 trustitem_t *ti;
384 size_t len;
385 unsigned char fprbin[20];
387 if (r_disabled)
388 *r_disabled = 0;
390 if ( hexcolon2bin (fpr, fprbin, 20) < 0 )
391 return gpg_error (GPG_ERR_INV_VALUE);
393 if (!trusttable)
395 err = read_trustfiles ();
396 if (err)
398 log_error (_("error reading list of trusted root certificates\n"));
399 return err;
403 if (trusttable)
405 for (ti=trusttable, len = trusttablesize; len; ti++, len--)
406 if (!memcmp (ti->fpr, fprbin, 20))
408 if (ti->flags.disabled && r_disabled)
409 *r_disabled = 1;
411 if (ti->flags.relax)
413 err = agent_write_status (ctrl,
414 "TRUSTLISTFLAG", "relax",
415 NULL);
416 if (err)
417 return err;
419 else if (ti->flags.cm)
421 err = agent_write_status (ctrl,
422 "TRUSTLISTFLAG", "cm",
423 NULL);
424 if (err)
425 return err;
427 return ti->flags.disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
430 return gpg_error (GPG_ERR_NOT_TRUSTED);
434 /* Write all trust entries to FP. */
435 gpg_error_t
436 agent_listtrusted (void *assuan_context)
438 trustitem_t *ti;
439 char key[51];
440 gpg_error_t err;
441 size_t len;
443 if (!trusttable)
445 err = read_trustfiles ();
446 if (err)
448 log_error (_("error reading list of trusted root certificates\n"));
449 return err;
453 if (trusttable)
455 /* We need to lock the table because the scheduler may interrupt
456 assuan_send_data and an other thread may then re-read the table. */
457 lock_trusttable ();
458 for (ti=trusttable, len = trusttablesize; len; ti++, len--)
460 if (ti->flags.disabled)
461 continue;
462 bin2hex (ti->fpr, 20, key);
463 key[40] = ' ';
464 key[41] = ((ti->flags.for_smime && ti->flags.for_pgp)? '*'
465 : ti->flags.for_smime? 'S': ti->flags.for_pgp? 'P':' ');
466 key[42] = '\n';
467 assuan_send_data (assuan_context, key, 43);
468 assuan_send_data (assuan_context, NULL, 0); /* flush */
470 unlock_trusttable ();
473 return 0;
477 /* Create a copy of string with colons inserted after each two bytes.
478 Caller needs to release the string. In case of a memory failure,
479 NULL is returned. */
480 static char *
481 insert_colons (const char *string)
483 char *buffer, *p;
484 size_t n = strlen (string);
485 size_t nnew = n + (n+1)/2;
487 p = buffer = xtrymalloc ( nnew + 1 );
488 if (!buffer)
489 return NULL;
490 while (*string)
492 *p++ = *string++;
493 if (*string)
495 *p++ = *string++;
496 if (*string)
497 *p++ = ':';
500 *p = 0;
501 assert (strlen (buffer) <= nnew);
503 return buffer;
507 /* To pretty print DNs in the Pinentry, we replace slashes by
508 REPLSTRING. The caller needs to free the returned string. NULL is
509 returned on error with ERRNO set. */
510 static char *
511 reformat_name (const char *name, const char *replstring)
513 const char *s;
514 char *newname;
515 char *d;
516 size_t count;
517 size_t replstringlen = strlen (replstring);
519 /* If the name does not start with a slash it is not a preformatted
520 DN and thus we don't bother to reformat it. */
521 if (*name != '/')
522 return xtrystrdup (name);
524 /* Count the names. Note that a slash contained in a DN part is
525 expected to be C style escaped and thus the slashes we see here
526 are the actual part delimiters. */
527 for (s=name+1, count=0; *s; s++)
528 if (*s == '/')
529 count++;
530 newname = xtrymalloc (strlen (name) + count*replstringlen + 1);
531 if (!newname)
532 return NULL;
533 for (s=name+1, d=newname; *s; s++)
534 if (*s == '/')
535 d = stpcpy (d, replstring);
536 else
537 *d++ = *s;
538 *d = 0;
539 return newname;
543 /* Insert the given fpr into our trustdb. We expect FPR to be an all
544 uppercase hexstring of 40 characters. FLAG is either 'P' or 'C'.
545 This function does first check whether that key has already been put
546 into the trustdb and returns success in this case. Before a FPR
547 actually gets inserted, the user is asked by means of the Pinentry
548 whether this is actual want he wants to do. */
549 gpg_error_t
550 agent_marktrusted (ctrl_t ctrl, const char *name, const char *fpr, int flag)
552 gpg_error_t err = 0;
553 char *desc;
554 char *fname;
555 FILE *fp;
556 char *fprformatted;
557 char *nameformatted;
558 int is_disabled;
559 int yes_i_trust;
561 /* Check whether we are at all allowed to modify the trustlist.
562 This is useful so that the trustlist may be a symlink to a global
563 trustlist with only admin priviliges to modify it. Of course
564 this is not a secure way of denying access, but it avoids the
565 usual clicking on an Okay button most users are used to. */
566 fname = make_filename (opt.homedir, "trustlist.txt", NULL);
567 if ( access (fname, W_OK) && errno != ENOENT)
569 xfree (fname);
570 return gpg_error (GPG_ERR_EPERM);
572 xfree (fname);
574 if (!agent_istrusted (ctrl, fpr, &is_disabled))
576 return 0; /* We already got this fingerprint. Silently return
577 success. */
580 /* This feature must explicitly been enabled. */
581 if (!opt.allow_mark_trusted)
582 return gpg_error (GPG_ERR_NOT_SUPPORTED);
584 if (is_disabled)
586 /* There is an disabled entry in the trustlist. Return an error
587 so that the user won't be asked again for that one. Changing
588 this flag with the integrated marktrusted feature is and will
589 not be made possible. */
590 return gpg_error (GPG_ERR_NOT_TRUSTED);
594 /* Insert a new one. */
595 nameformatted = reformat_name (name, "%0A ");
596 if (!nameformatted)
597 return gpg_error_from_syserror ();
599 /* First a general question whether this is trusted. */
600 desc = xtryasprintf (
601 /* TRANSLATORS: This prompt is shown by the Pinentry
602 and has one special property: A "%%0A" is used by
603 Pinentry to insert a line break. The double
604 percent sign is actually needed because it is also
605 a printf format string. If you need to insert a
606 plain % sign, you need to encode it as "%%25". The
607 "%s" gets replaced by the name as stored in the
608 certificate. */
609 _("Do you ultimately trust%%0A"
610 " \"%s\"%%0A"
611 "to correctly certify user certificates?"),
612 nameformatted);
613 if (!desc)
615 xfree (nameformatted);
616 return out_of_core ();
618 err = agent_get_confirmation (ctrl, desc, _("Yes"), _("No"));
619 xfree (desc);
620 if (!err)
621 yes_i_trust = 1;
622 else if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
623 yes_i_trust = 0;
624 else
626 xfree (nameformatted);
627 return err;
631 fprformatted = insert_colons (fpr);
632 if (!fprformatted)
634 xfree (nameformatted);
635 return out_of_core ();
638 /* If the user trusts this certificate he has to verify the
639 fingerprint of course. */
640 if (yes_i_trust)
642 desc = xtryasprintf
644 /* TRANSLATORS: This prompt is shown by the Pinentry and has
645 one special property: A "%%0A" is used by Pinentry to
646 insert a line break. The double percent sign is actually
647 needed because it is also a printf format string. If you
648 need to insert a plain % sign, you need to encode it as
649 "%%25". The second "%s" gets replaced by a hexdecimal
650 fingerprint string whereas the first one receives the name
651 as stored in the certificate. */
652 _("Please verify that the certificate identified as:%%0A"
653 " \"%s\"%%0A"
654 "has the fingerprint:%%0A"
655 " %s"), nameformatted, fprformatted);
656 if (!desc)
658 xfree (fprformatted);
659 xfree (nameformatted);
660 return out_of_core ();
663 /* TRANSLATORS: "Correct" is the label of a button and intended
664 to be hit if the fingerprint matches the one of the CA. The
665 other button is "the default "Cancel" of the Pinentry. */
666 err = agent_get_confirmation (ctrl, desc, _("Correct"), _("Wrong"));
667 xfree (desc);
668 if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
669 yes_i_trust = 0;
670 else if (err)
672 xfree (fprformatted);
673 xfree (nameformatted);
674 return err;
679 /* Now check again to avoid duplicates. We take the lock to make
680 sure that nobody else plays with our file and force a reread. */
681 lock_trusttable ();
682 agent_reload_trustlist ();
683 if (!agent_istrusted (ctrl, fpr, &is_disabled) || is_disabled)
685 unlock_trusttable ();
686 xfree (fprformatted);
687 xfree (nameformatted);
688 return is_disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
691 fname = make_filename (opt.homedir, "trustlist.txt", NULL);
692 if ( access (fname, F_OK) && errno == ENOENT)
694 fp = fopen (fname, "wx"); /* Warning: "x" is a GNU extension. */
695 if (!fp)
697 err = gpg_error_from_syserror ();
698 log_error ("can't create `%s': %s\n", fname, gpg_strerror (err));
699 xfree (fname);
700 unlock_trusttable ();
701 xfree (fprformatted);
702 xfree (nameformatted);
703 return err;
705 fputs (headerblurb, fp);
706 fclose (fp);
708 fp = fopen (fname, "a+");
709 if (!fp)
711 err = gpg_error_from_syserror ();
712 log_error ("can't open `%s': %s\n", fname, gpg_strerror (err));
713 xfree (fname);
714 unlock_trusttable ();
715 xfree (fprformatted);
716 xfree (nameformatted);
717 return err;
720 /* Append the key. */
721 fputs ("\n# ", fp);
722 xfree (nameformatted);
723 nameformatted = reformat_name (name, "\n# ");
724 if (!nameformatted || strchr (name, '\n'))
726 /* Note that there should never be a LF in NAME but we better
727 play safe and print a sanitized version in this case. */
728 print_sanitized_string (fp, name, 0);
730 else
731 fputs (nameformatted, fp);
732 fprintf (fp, "\n%s%s %c\n", yes_i_trust?"":"!", fprformatted, flag);
733 if (ferror (fp))
734 err = gpg_error_from_syserror ();
736 if (fclose (fp))
737 err = gpg_error_from_syserror ();
739 agent_reload_trustlist ();
740 xfree (fname);
741 unlock_trusttable ();
742 xfree (fprformatted);
743 xfree (nameformatted);
744 return err;
748 /* This function may be called to force reloading of the
749 trustlist. */
750 void
751 agent_reload_trustlist (void)
753 /* All we need to do is to delete the trusttable. At the next
754 access it will get re-read. */
755 lock_trusttable ();
756 xfree (trusttable);
757 trusttable = NULL;
758 trusttablesize = 0;
759 unlock_trusttable ();
760 bump_key_eventcounter ();