1 /* crlcache.c - LDAP access
2 * Copyright (C) 2002 Klarälvdalens Datakonsult AB
3 * Copyright (C) 2003, 2004, 2005, 2008 g10 Code GmbH
5 * This file is part of DirMngr.
7 * DirMngr 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 2 of the License, or
10 * (at your option) any later version.
12 * DirMngr 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/>.
23 1. To keep track of the CRLs actually cached and to store the meta
24 information of the CRLs a simple record oriented text file is
25 used. Fields in the file are colon (':') separated and values
26 containing colons or linefeeds are percent escaped (e.g. a colon
27 itself is represented as "%3A").
29 The first field is a record type identifier, so that the file is
30 useful to keep track of other meta data too.
32 The name of the file is "DIR.txt".
37 Field 1: Constant beginning with "#".
39 Other fields are not defined and such a record is simply
40 skipped during processing.
45 Field 2: Version number of this file. Must be 1.
47 This record must be the first non-comment record record and
48 there shall only exist one record of this type.
52 Field 1: Constant "c", "u" or "i".
53 A "c" or "u" indicate a valid cache entry, however
54 "u" requires that a user root certificate check needs
56 An "i" indicates an invalid cache entry which should
57 not be used but still exists so that it can be
58 updated at NEXT_UPDATE.
59 Field 2: Hexadecimal encoded SHA-1 hash of the issuer DN using
61 Field 3: Issuer DN in RFC-2253 notation.
62 Field 4: URL used to retrieve the corresponding CRL.
63 Field 5: 15 character ISO timestamp with THIS_UPDATE.
64 Field 6: 15 character ISO timestamp with NEXT_UPDATE.
65 Field 7: Hexadecimal encoded MD-5 hash of the DB file to detect
66 accidental modified (i.e. deleted and created) cache files.
67 Field 8: optional CRL number as a hex string.
68 Field 9: AuthorityKeyID.issuer, each Name separated by 0x01
69 Field 10: AuthorityKeyID.serial
70 Field 11: Hex fingerprint of trust anchor if field 1 is 'u'.
72 2. Layout of the standard CRL Cache DB file:
74 We use records of variable length with this structure
76 n bytes Serialnumber (binary) used as key
77 thus there is no need to store the length explicitly with DB2.
78 1 byte Reason for revocation
79 (currently the KSBA reason flags are used)
80 15 bytes ISO date of revocation (e.g. 19980815T142000)
81 Note that there is no terminating 0 stored.
83 The filename used is the hexadecimal (using uppercase letters)
84 SHA-1 hash value of the issuer DN prefixed with a "crl-" and
85 suffixed with a ".db". Thus the length of the filename is 47.
101 #ifndef HAVE_W32_SYSTEM
102 #include <sys/utsname.h>
104 #ifdef MKDIR_TAKES_ONE_ARG
106 #define mkdir(a,b) mkdir(a)
110 #include "validate.h"
111 #include "certcache.h"
112 #include "crlcache.h"
113 #include "crlfetch.h"
117 /* Change this whenever the format changes */
118 #define DBDIR_D "crls.d"
119 #define DBDIRFILE "DIR.txt"
120 #define DBDIRVERSION 1
122 /* The number of DB files we may have open at one time. We need to
123 limit this because there is no guarantee that the number of issuers
124 has a upper limit. We are currently using mmap, so it is a good
125 idea anyway to limit the number of opened cache files. */
126 #define MAX_OPEN_DB_FILES 5
129 static const char oidstr_crlNumber[] = "2.5.29.20";
130 static const char oidstr_issuingDistributionPoint[] = "2.5.29.28";
131 static const char oidstr_authorityKeyIdentifier[] = "2.5.29.35";
134 /* Definition of one cached item. */
135 struct crl_cache_entry_s
137 struct crl_cache_entry_s *next;
138 int deleted; /* True if marked for deletion. */
139 int mark; /* Internally used by update_dir. */
140 unsigned int lineno;/* A 0 indicates a new entry. */
141 char *release_ptr; /* The actual allocated memory. */
142 char *url; /* Points into RELEASE_PTR. */
143 char *issuer; /* Ditto. */
144 char *issuer_hash; /* Ditto. */
145 char *dbfile_hash; /* MD5 sum of the cache file, points into RELEASE_PTR.*/
146 int invalid; /* Can't use this CRL. */
147 int user_trust_req; /* User supplied root certificate required. */
148 char *check_trust_anchor; /* Malloced fingerprint. */
149 ksba_isotime_t this_update;
150 ksba_isotime_t next_update;
151 ksba_isotime_t last_refresh; /* Use for the force_crl_refresh feature. */
153 char *authority_issuer;
154 char *authority_serialno;
156 struct cdb *cdb; /* The cache file handle or NULL if not open. */
158 unsigned int cdb_use_count; /* Current use count. */
159 unsigned int cdb_lru_count; /* Used for LRU purposes. */
160 int dbfile_checked; /* Set to true if the dbfile_hash value has
165 /* Definition of the entire cache object. */
168 crl_cache_entry_t entries;
171 typedef struct crl_cache_s *crl_cache_t;
175 static crl_cache_entry_t find_entry (crl_cache_entry_t first,
176 const char *issuer_hash);
180 /* The currently loaded cache object. This is usually initialized
182 static crl_cache_t current_cache;
188 /* Return the current cache object or bail out if it is has not yet
191 get_current_cache (void)
194 log_fatal ("CRL cache has not yet been initialized\n");
195 return current_cache;
200 Create ae directory if it does not yet exists. Returns on
201 success, or -1 on error.
204 create_directory_if_needed (const char *name)
209 fname = make_filename (opt.homedir_cache, name, NULL);
210 dir = opendir (fname);
213 log_info (_("creating directory '%s'\n"), fname);
214 if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR) )
216 int save_errno = errno;
217 log_error (_("error creating directory '%s': %s\n"),
218 fname, strerror (errno));
220 gpg_err_set_errno (save_errno);
230 /* Remove all files from the cache directory. If FORCE is not true,
231 some sanity checks on the filenames are done. Return 0 if
232 everything went fine. */
234 cleanup_cache_dir (int force)
236 char *dname = make_filename (opt.homedir_cache, DBDIR_D, NULL);
242 { /* Very minor sanity checks. */
243 if (!strcmp (dname, "~/") || !strcmp (dname, "/" ))
245 log_error (_("ignoring database dir '%s'\n"), dname);
251 dir = opendir (dname);
254 log_error (_("error reading directory '%s': %s\n"),
255 dname, strerror (errno));
260 while ((de = readdir (dir)))
262 if (strcmp (de->d_name, "." ) && strcmp (de->d_name, ".."))
264 char *cdbname = make_filename (dname, de->d_name, NULL);
271 okay = (!stat (cdbname, &sbuf) && S_ISREG (sbuf.st_mode));
275 log_info (_("removing cache file '%s'\n"), cdbname);
276 if (gnupg_remove (cdbname))
278 log_error ("failed to remove '%s': %s\n",
279 cdbname, strerror (errno));
284 log_info (_("not removing file '%s'\n"), cdbname);
294 /* Read the next line from the file FP and return the line in an
295 malloced buffer. Return NULL on error or EOF. There is no
296 limitation os the line length. The trailing linefeed has been
297 removed, the function will read the last line of a file, even if
298 that is not terminated by a LF. */
300 next_line_from_file (estream_t fp, gpg_error_t *r_err)
303 char *largebuf = NULL;
312 buflen = sizeof buf - 1;
313 while ((c=es_getc (fp)) != EOF && c != '\n')
320 largebuf = xtrymalloc ( buflen + 1 );
323 *r_err = gpg_error_from_syserror ();
326 memcpy (largebuf, buf, len);
331 tmpbuf = xtryrealloc (largebuf, buflen + 1);
334 *r_err = gpg_error_from_syserror ();
344 if (c == EOF && !len)
349 tmpbuf = xtryrealloc (largebuf, len+1);
351 tmpbuf = xtrystrdup (buf);
354 *r_err = gpg_error_from_syserror ();
361 /* Release one cache entry. */
363 release_one_cache_entry (crl_cache_entry_t entry)
369 int fd = cdb_fileno (entry->cdb);
370 cdb_free (entry->cdb);
373 log_error (_("error closing cache file: %s\n"), strerror(errno));
375 xfree (entry->release_ptr);
376 xfree (entry->check_trust_anchor);
382 /* Release the CACHE object. */
384 release_cache (crl_cache_t cache)
386 crl_cache_entry_t entry, entry2;
391 for (entry = cache->entries; entry; entry = entry2)
393 entry2 = entry->next;
394 release_one_cache_entry (entry);
396 cache->entries = NULL;
401 /* Open the dir file FNAME or create a new one if it does not yet
404 open_dir_file (const char *fname)
408 fp = es_fopen (fname, "r");
411 log_error (_("failed to open cache dir file '%s': %s\n"),
412 fname, strerror (errno));
414 /* Make sure that the directory exists, try to create if otherwise. */
415 if (create_directory_if_needed (NULL)
416 || create_directory_if_needed (DBDIR_D))
418 fp = es_fopen (fname, "w");
421 log_error (_("error creating new cache dir file '%s': %s\n"),
422 fname, strerror (errno));
425 es_fprintf (fp, "v:%d:\n", DBDIRVERSION);
428 log_error (_("error writing new cache dir file '%s': %s\n"),
429 fname, strerror (errno));
435 log_error (_("error closing new cache dir file '%s': %s\n"),
436 fname, strerror (errno));
440 log_info (_("new cache dir file '%s' created\n"), fname);
442 fp = es_fopen (fname, "r");
445 log_error (_("failed to re-open cache dir file '%s': %s\n"),
446 fname, strerror (errno));
454 /* Helper for open_dir. */
456 check_dir_version (estream_t *fpadr, const char *fname,
457 unsigned int *lineno,
458 int cleanup_on_mismatch)
461 gpg_error_t lineerr = 0;
462 estream_t fp = *fpadr;
466 while ((line = next_line_from_file (fp, &lineerr)))
469 if (*line == 'v' && line[1] == ':')
471 else if (*line != '#')
473 log_error (_("first record of '%s' is not the version\n"), fname);
475 return gpg_error (GPG_ERR_CONFIGURATION);
482 /* The !line catches the case of an empty DIR file. We handle this
483 the same as a non-matching version. */
484 if (!line || strtol (line+2, NULL, 10) != DBDIRVERSION)
486 if (!created && cleanup_on_mismatch)
488 log_error (_("old version of cache directory - cleaning up\n"));
491 if (!cleanup_cache_dir (1))
494 fp = *fpadr = open_dir_file (fname);
498 return gpg_error (GPG_ERR_CONFIGURATION);
504 log_error (_("old version of cache directory - giving up\n"));
506 return gpg_error (GPG_ERR_CONFIGURATION);
513 /* Open the dir file and read in all available information. Store
514 that in a newly allocated cache object and return that if
515 everything worked out fine. Create the cache directory and the dir
516 if it does not yet exist. Remove all files in that directory if
517 the version does not match. */
519 open_dir (crl_cache_t *r_cache)
524 gpg_error_t lineerr = 0;
526 crl_cache_entry_t entry, *entrytail;
531 cache = xtrycalloc (1, sizeof *cache);
533 return gpg_error_from_syserror ();
535 fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);
538 fp = open_dir_file (fname);
541 err = gpg_error (GPG_ERR_CONFIGURATION);
545 err = check_dir_version (&fp, fname, &lineno, 1);
550 /* Read in all supported entries from the dir file. */
551 cache->entries = NULL;
552 entrytail = &cache->entries;
554 while ((line = next_line_from_file (fp, &lineerr)))
560 if ( *line == 'c' || *line == 'u' || *line == 'i' )
562 entry = xtrycalloc (1, sizeof *entry);
565 err = gpg_error_from_syserror ();
568 entry->lineno = lineno;
569 entry->release_ptr = line;
572 entry->invalid = atoi (line+1);
573 if (entry->invalid < 1)
576 else if (*line == 'u')
577 entry->user_trust_req = 1;
579 for (fieldno=1, p = line; p; p = endp, fieldno++)
581 endp = strchr (p, ':');
587 case 1: /* record type */ break;
588 case 2: entry->issuer_hash = p; break;
589 case 3: entry->issuer = unpercent_string (p); break;
590 case 4: entry->url = unpercent_string (p); break;
592 strncpy (entry->this_update, p, 15);
593 entry->this_update[15] = 0;
596 strncpy (entry->next_update, p, 15);
597 entry->next_update[15] = 0;
599 case 7: entry->dbfile_hash = p; break;
600 case 8: if (*p) entry->crl_number = p; break;
603 entry->authority_issuer = unpercent_string (p);
607 entry->authority_serialno = unpercent_string (p);
611 entry->check_trust_anchor = xtrystrdup (p);
615 log_info (_("extra field detected in crl record of "
616 "'%s' line %u\n"), fname, lineno);
621 if (!entry->issuer_hash)
623 log_info (_("invalid line detected in '%s' line %u\n"),
628 else if (find_entry (cache->entries, entry->issuer_hash))
630 /* Fixme: The duplicate checking used is not very
631 effective for large numbers of issuers. */
632 log_info (_("duplicate entry detected in '%s' line %u\n"),
641 entrytail = &entry->next;
644 else if (*line == '#')
647 log_info (_("unsupported record type in '%s' line %u skipped\n"),
656 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
661 log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
662 err = gpg_error (GPG_ERR_CONFIGURATION);
666 /* Now do some basic checks on the data. */
667 for (entry = cache->entries; entry; entry = entry->next)
669 assert (entry->lineno);
670 if (strlen (entry->issuer_hash) != 40)
673 log_error (_("invalid issuer hash in '%s' line %u\n"),
674 fname, entry->lineno);
676 else if ( !*entry->issuer )
679 log_error (_("no issuer DN in '%s' line %u\n"),
680 fname, entry->lineno);
682 else if ( check_isotime (entry->this_update)
683 || check_isotime (entry->next_update))
686 log_error (_("invalid timestamp in '%s' line %u\n"),
687 fname, entry->lineno);
690 /* Checks not leading to an immediate fail. */
691 if (strlen (entry->dbfile_hash) != 32)
692 log_info (_("WARNING: invalid cache file hash in '%s' line %u\n"),
693 fname, entry->lineno);
698 log_error (_("detected errors in cache dir file\n"));
699 log_info (_("please check the reason and manually delete that file\n"));
700 err = gpg_error (GPG_ERR_CONFIGURATION);
710 release_cache (cache);
718 write_percented_string (const char *s, estream_t fp)
722 es_fputs ("%3A", fp);
724 es_fputs ("%0A", fp);
726 es_fputs ("%0D", fp);
733 write_dir_line_crl (estream_t fp, crl_cache_entry_t e)
736 es_fprintf (fp, "i%d", e->invalid);
737 else if (e->user_trust_req)
742 es_fputs (e->issuer_hash, fp);
744 write_percented_string (e->issuer, fp);
746 write_percented_string (e->url, fp);
748 es_fwrite (e->this_update, 15, 1, fp);
750 es_fwrite (e->next_update, 15, 1, fp);
752 es_fputs (e->dbfile_hash, fp);
755 es_fputs (e->crl_number, fp);
757 if (e->authority_issuer)
758 write_percented_string (e->authority_issuer, fp);
760 if (e->authority_serialno)
761 es_fputs (e->authority_serialno, fp);
763 if (e->check_trust_anchor && e->user_trust_req)
764 es_fputs (e->check_trust_anchor, fp);
769 /* Update the current dir file using the cache. */
771 update_dir (crl_cache_t cache)
774 char *tmpfname = NULL;
776 gpg_error_t lineerr = 0;
778 estream_t fpout = NULL;
783 fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);
785 /* Fixme: Take an update file lock here. */
787 for (e= cache->entries; e; e = e->next)
791 fp = es_fopen (fname, "r");
794 err = gpg_error_from_errno (errno);
795 log_error (_("failed to open cache dir file '%s': %s\n"),
796 fname, strerror (errno));
799 err = check_dir_version (&fp, fname, &lineno, 0);
805 /* Create a temporary DIR file. */
808 const char *nodename;
809 #ifndef HAVE_W32_SYSTEM
810 struct utsname utsbuf;
813 #ifdef HAVE_W32_SYSTEM
814 nodename = "unknown";
817 nodename = "unknown";
819 nodename = utsbuf.nodename;
822 gpgrt_asprintf (&tmpbuf, "DIR-tmp-%s-%u-%p.txt.tmp",
823 nodename, (unsigned int)getpid (), &tmpbuf);
826 err = gpg_error_from_errno (errno);
827 log_error (_("failed to create temporary cache dir file '%s': %s\n"),
828 tmpfname, strerror (errno));
831 for (p=tmpbuf; *p; p++)
834 tmpfname = make_filename (opt.homedir_cache, DBDIR_D, tmpbuf, NULL);
837 fpout = es_fopen (tmpfname, "w");
840 err = gpg_error_from_errno (errno);
841 log_error (_("failed to create temporary cache dir file '%s': %s\n"),
842 tmpfname, strerror (errno));
846 while ((line = next_line_from_file (fp, &lineerr)))
849 if (*line == 'c' || *line == 'u' || *line == 'i')
851 /* Extract the issuer hash field. */
854 fieldp = strchr (line, ':');
855 endp = fieldp? strchr (++fieldp, ':') : NULL;
858 /* There should be no percent within the issuer hash
859 field, thus we can compare it pretty easily. */
861 e = find_entry ( cache->entries, fieldp);
862 *endp = ':'; /* Restore original line. */
865 /* Marked for deletion, so don't write it. */
870 /* Yep, this is valid entry we know about; write it out */
871 write_dir_line_crl (fpout, e);
875 { /* We ignore entries we don't have in our cache
876 because they may have been added in the meantime
877 by other instances of dirmngr. */
878 es_fprintf (fpout, "# Next line added by "
879 "another process; our pid is %lu\n",
880 (unsigned long)getpid ());
881 es_fputs (line, fpout);
882 es_putc ('\n', fpout);
887 es_fputs ("# Invalid line detected: ", fpout);
888 es_fputs (line, fpout);
889 es_putc ('\n', fpout);
894 /* Write out all non CRL lines as they are. */
895 es_fputs (line, fpout);
896 es_putc ('\n', fpout);
901 if (!es_ferror (fp) && !es_ferror (fpout) && !lineerr)
903 /* Write out the remaining entries. */
904 for (e= cache->entries; e; e = e->next)
908 write_dir_line_crl (fpout, e);
915 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
920 err = gpg_error_from_errno (errno);
921 log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
923 if (es_ferror (fpout))
925 err = gpg_error_from_errno (errno);
926 log_error (_("error writing '%s': %s\n"), tmpfname, strerror (errno));
931 /* Rename the files. */
934 if (es_fclose (fpout))
936 err = gpg_error_from_errno (errno);
937 log_error (_("error closing '%s': %s\n"), tmpfname, strerror (errno));
942 #ifdef HAVE_W32_SYSTEM
943 /* No atomic mv on W32 systems. */
944 gnupg_remove (fname);
946 if (rename (tmpfname, fname))
948 err = gpg_error_from_errno (errno);
949 log_error (_("error renaming '%s' to '%s': %s\n"),
950 tmpfname, fname, strerror (errno));
955 /* Fixme: Relinquish update lock. */
963 gnupg_remove (tmpfname);
972 /* Create the filename for the cache file from the 40 byte ISSUER_HASH
973 string. Caller must release the return string. */
975 make_db_file_name (const char *issuer_hash)
979 assert (strlen (issuer_hash) == 40);
980 memcpy (bname, "crl-", 4);
981 memcpy (bname + 4, issuer_hash, 40);
982 strcpy (bname + 44, ".db");
983 return make_filename (opt.homedir_cache, DBDIR_D, bname, NULL);
987 /* Hash the file FNAME and return the MD5 digest in MD5BUFFER. The
988 caller must allocate MD%buffer wityh at least 16 bytes. Returns 0
991 hash_dbfile (const char *fname, unsigned char *md5buffer)
999 buffer = xtrymalloc (65536);
1000 fp = buffer? es_fopen (fname, "rb") : NULL;
1003 log_error (_("can't hash '%s': %s\n"), fname, strerror (errno));
1008 err = gcry_md_open (&md5, GCRY_MD_MD5, 0);
1011 log_error (_("error setting up MD5 hash context: %s\n"),
1012 gpg_strerror (err));
1018 /* We better hash some information about the cache file layout in. */
1019 sprintf (buffer, "%.100s/%.100s:%d", DBDIR_D, DBDIRFILE, DBDIRVERSION);
1020 gcry_md_write (md5, buffer, strlen (buffer));
1024 n = es_fread (buffer, 1, 65536, fp);
1025 if (n < 65536 && es_ferror (fp))
1027 log_error (_("error hashing '%s': %s\n"), fname, strerror (errno));
1030 gcry_md_close (md5);
1035 gcry_md_write (md5, buffer, n);
1039 gcry_md_final (md5);
1041 memcpy (md5buffer, gcry_md_read (md5, GCRY_MD_MD5), 16);
1042 gcry_md_close (md5);
1046 /* Compare the file FNAME against the dexified MD5 hash MD5HASH and
1047 return 0 if they match. */
1049 check_dbfile (const char *fname, const char *md5hexvalue)
1051 unsigned char buffer1[16], buffer2[16];
1053 if (strlen (md5hexvalue) != 32)
1055 log_error (_("invalid formatted checksum for '%s'\n"), fname);
1058 unhexify (buffer1, md5hexvalue);
1060 if (hash_dbfile (fname, buffer2))
1063 return memcmp (buffer1, buffer2, 16);
1067 /* Open the cache file for ENTRY. This function implements a caching
1068 strategy and might close unused cache files. It is required to use
1069 unlock_db_file after using the file. */
1071 lock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
1076 crl_cache_entry_t e;
1080 entry->cdb_use_count++;
1084 for (open_count = 0, e = cache->entries; e; e = e->next)
1088 /* log_debug ("CACHE: cdb=%p use_count=%u lru_count=%u\n", */
1089 /* e->cdb,e->cdb_use_count,e->cdb_lru_count); */
1092 /* If there are too many file open, find the least recent used DB
1093 file and close it. Note that for Pth thread safeness we need to
1095 while (open_count >= MAX_OPEN_DB_FILES )
1097 crl_cache_entry_t last_e = NULL;
1098 unsigned int last_lru = (unsigned int)(-1);
1100 for (e = cache->entries; e; e = e->next)
1101 if (e->cdb && !e->cdb_use_count && e->cdb_lru_count < last_lru)
1103 last_lru = e->cdb_lru_count;
1108 log_error (_("too many open cache files; can't open anymore\n"));
1112 /* log_debug ("CACHE: closing file at cdb=%p\n", last_e->cdb); */
1114 fd = cdb_fileno (last_e->cdb);
1115 cdb_free (last_e->cdb);
1116 xfree (last_e->cdb);
1119 log_error (_("error closing cache file: %s\n"), strerror(errno));
1124 fname = make_db_file_name (entry->issuer_hash);
1126 log_info (_("opening cache file '%s'\n"), fname );
1128 if (!entry->dbfile_checked)
1130 if (!check_dbfile (fname, entry->dbfile_hash))
1131 entry->dbfile_checked = 1;
1132 /* Note, in case of an error we don't print an error here but
1133 let require the caller to do that check. */
1136 entry->cdb = xtrycalloc (1, sizeof *entry->cdb);
1142 fd = open (fname, O_RDONLY);
1145 log_error (_("error opening cache file '%s': %s\n"),
1146 fname, strerror (errno));
1152 if (cdb_init (entry->cdb, fd))
1154 log_error (_("error initializing cache file '%s' for reading: %s\n"),
1155 fname, strerror (errno));
1164 entry->cdb_use_count = 1;
1165 entry->cdb_lru_count = 0;
1170 /* Unlock a cache file, so that it can be reused. */
1172 unlock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
1175 log_error (_("calling unlock_db_file on a closed file\n"));
1176 else if (!entry->cdb_use_count)
1177 log_error (_("calling unlock_db_file on an unlocked file\n"));
1180 entry->cdb_use_count--;
1181 entry->cdb_lru_count++;
1184 /* If the entry was marked for deletion in the meantime do it now.
1185 We do this for the sake of Pth thread safeness. */
1186 if (!entry->cdb_use_count && entry->deleted)
1188 crl_cache_entry_t eprev, enext;
1190 enext = entry->next;
1191 for (eprev = cache->entries;
1192 eprev && eprev->next != entry; eprev = eprev->next)
1195 if (eprev == cache->entries)
1196 cache->entries = enext;
1198 eprev->next = enext;
1199 /* FIXME: Do we leak ENTRY? */
1204 /* Find ISSUER_HASH in our cache FIRST. This may be used to enumerate
1205 the linked list we use to keep the CRLs of an issuer. */
1206 static crl_cache_entry_t
1207 find_entry (crl_cache_entry_t first, const char *issuer_hash)
1209 while (first && (first->deleted || strcmp (issuer_hash, first->issuer_hash)))
1210 first = first->next;
1215 /* Create a new CRL cache. This function is usually called only once.
1218 crl_cache_init(void)
1220 crl_cache_t cache = NULL;
1225 log_error ("crl cache has already been initialized - not doing twice\n");
1229 err = open_dir (&cache);
1231 log_fatal (_("failed to create a new cache object: %s\n"),
1232 gpg_strerror (err));
1233 current_cache = cache;
1237 /* Remove the cache information and all its resources. Note that we
1238 still keep the cache on disk. */
1240 crl_cache_deinit (void)
1244 release_cache (current_cache);
1245 current_cache = NULL;
1250 /* Delete the cache from disk. Return 0 on success.*/
1252 crl_cache_flush (void)
1256 rc = cleanup_cache_dir (0)? -1 : 0;
1262 /* Check whether the certificate identified by ISSUER_HASH and
1263 SN/SNLEN is valid; i.e. not listed in our cache. With
1264 FORCE_REFRESH set to true, a new CRL will be retrieved even if the
1265 cache has not yet expired. We use a 30 minutes threshold here so
1266 that invoking this function several times won't load the CRL over
1268 static crl_cache_result_t
1269 cache_isvalid (ctrl_t ctrl, const char *issuer_hash,
1270 const unsigned char *sn, size_t snlen,
1273 crl_cache_t cache = get_current_cache ();
1274 crl_cache_result_t retval;
1277 crl_cache_entry_t entry;
1278 gnupg_isotime_t current_time;
1283 entry = find_entry (cache->entries, issuer_hash);
1286 log_info (_("no CRL available for issuer id %s\n"), issuer_hash );
1287 return CRL_CACHE_DONTKNOW;
1290 gnupg_get_isotime (current_time);
1291 if (strcmp (entry->next_update, current_time) < 0 )
1293 log_info (_("cached CRL for issuer id %s too old; update required\n"),
1295 return CRL_CACHE_DONTKNOW;
1299 gnupg_isotime_t tmptime;
1301 if (*entry->last_refresh)
1303 gnupg_copy_time (tmptime, entry->last_refresh);
1304 add_seconds_to_isotime (tmptime, 30 * 60);
1305 if (strcmp (tmptime, current_time) < 0 )
1307 log_info (_("force-crl-refresh active and %d minutes passed for"
1308 " issuer id %s; update required\n"),
1310 return CRL_CACHE_DONTKNOW;
1315 log_info (_("force-crl-refresh active for"
1316 " issuer id %s; update required\n"),
1318 return CRL_CACHE_DONTKNOW;
1324 log_info (_("available CRL for issuer ID %s can't be used\n"),
1326 return CRL_CACHE_CANTUSE;
1329 cdb = lock_db_file (cache, entry);
1331 return CRL_CACHE_DONTKNOW; /* Hmmm, not the best error code. */
1333 if (!entry->dbfile_checked)
1335 log_error (_("cached CRL for issuer id %s tampered; we need to update\n")
1337 unlock_db_file (cache, entry);
1338 return CRL_CACHE_DONTKNOW;
1341 rc = cdb_find (cdb, sn, snlen);
1344 n = cdb_datalen (cdb);
1347 log_error (_("WARNING: invalid cache record length for S/N "));
1349 log_printhex ("", sn, snlen);
1351 else if (opt.verbose)
1353 unsigned char record[16];
1354 char *tmp = hexify_data (sn, snlen, 1);
1356 if (cdb_read (cdb, record, n, cdb_datapos (cdb)))
1357 log_error (_("problem reading cache record for S/N %s: %s\n"),
1358 tmp, strerror (errno));
1360 log_info (_("S/N %s is not valid; reason=%02X date=%.15s\n"),
1361 tmp, *record, record+1);
1364 retval = CRL_CACHE_INVALID;
1370 char *serialno = hexify_data (sn, snlen, 1);
1371 log_info (_("S/N %s is valid, it is not listed in the CRL\n"),
1375 retval = CRL_CACHE_VALID;
1379 log_error (_("error getting data from cache file: %s\n"),
1381 retval = CRL_CACHE_DONTKNOW;
1385 if (entry->user_trust_req
1386 && (retval == CRL_CACHE_VALID || retval == CRL_CACHE_INVALID))
1388 if (!entry->check_trust_anchor)
1390 log_error ("inconsistent data on user trust check\n");
1391 retval = CRL_CACHE_CANTUSE;
1393 else if (get_istrusted_from_client (ctrl, entry->check_trust_anchor))
1396 log_info ("no system trust and client does not trust either\n");
1397 retval = CRL_CACHE_CANTUSE;
1401 /* Okay, the CRL is considered valid by the client and thus
1402 we can return the result as is. */
1406 unlock_db_file (cache, entry);
1412 /* Check whether the certificate identified by ISSUER_HASH and
1413 SERIALNO is valid; i.e. not listed in our cache. With
1414 FORCE_REFRESH set to true, a new CRL will be retrieved even if the
1415 cache has not yet expired. We use a 30 minutes threshold here so
1416 that invoking this function several times won't load the CRL over
1419 crl_cache_isvalid (ctrl_t ctrl, const char *issuer_hash, const char *serialno,
1422 crl_cache_result_t result;
1423 unsigned char snbuf_buffer[50];
1424 unsigned char *snbuf;
1427 n = strlen (serialno)/2+1;
1428 if (n < sizeof snbuf_buffer - 1)
1429 snbuf = snbuf_buffer;
1432 snbuf = xtrymalloc (n);
1434 return CRL_CACHE_DONTKNOW;
1437 n = unhexify (snbuf, serialno);
1439 result = cache_isvalid (ctrl, issuer_hash, snbuf, n, force_refresh);
1441 if (snbuf != snbuf_buffer)
1448 /* Check whether the certificate CERT is valid; i.e. not listed in our
1449 cache. With FORCE_REFRESH set to true, a new CRL will be retrieved
1450 even if the cache has not yet expired. We use a 30 minutes
1451 threshold here so that invoking this function several times won't
1452 load the CRL over and over. */
1454 crl_cache_cert_isvalid (ctrl_t ctrl, ksba_cert_t cert,
1458 crl_cache_result_t result;
1459 unsigned char issuerhash[20];
1460 char issuerhash_hex[41];
1467 /* Compute the hash value of the issuer name. */
1468 tmp = ksba_cert_get_issuer (cert, 0);
1471 log_error ("oops: issuer missing in certificate\n");
1472 return gpg_error (GPG_ERR_INV_CERT_OBJ);
1474 gcry_md_hash_buffer (GCRY_MD_SHA1, issuerhash, tmp, strlen (tmp));
1476 for (i=0,tmp=issuerhash_hex; i < 20; i++, tmp += 2)
1477 sprintf (tmp, "%02X", issuerhash[i]);
1479 /* Get the serial number. */
1480 serial = ksba_cert_get_serial (cert);
1483 log_error ("oops: S/N missing in certificate\n");
1484 return gpg_error (GPG_ERR_INV_CERT_OBJ);
1489 log_error ("oops: invalid S/N\n");
1491 return gpg_error (GPG_ERR_INV_CERT_OBJ);
1494 snlen = strtoul (sn, &endp, 10);
1498 log_error ("oops: invalid S/N\n");
1500 return gpg_error (GPG_ERR_INV_CERT_OBJ);
1504 /* Check the cache. */
1505 result = cache_isvalid (ctrl, issuerhash_hex, sn, snlen, force_refresh);
1508 case CRL_CACHE_VALID:
1511 case CRL_CACHE_INVALID:
1512 err = gpg_error (GPG_ERR_CERT_REVOKED);
1514 case CRL_CACHE_DONTKNOW:
1515 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1517 case CRL_CACHE_CANTUSE:
1518 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1521 log_fatal ("cache_isvalid returned invalid status code %d\n", result);
1529 /* Prepare a hash context for the signature verification. Input is
1530 the CRL and the output is the hash context MD as well as the uses
1531 algorithm identifier ALGO. */
1533 start_sig_check (ksba_crl_t crl, gcry_md_hd_t *md, int *algo)
1538 algoid = ksba_crl_get_digest_algo (crl);
1539 *algo = gcry_md_map_name (algoid);
1542 log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?");
1543 return gpg_error (GPG_ERR_DIGEST_ALGO);
1546 err = gcry_md_open (md, *algo, 0);
1549 log_error (_("gcry_md_open for algorithm %d failed: %s\n"),
1550 *algo, gcry_strerror (err));
1554 gcry_md_debug (*md, "hash.cert");
1556 ksba_crl_set_hash_function (crl, HASH_FNC, *md);
1561 /* Finish a hash context and verify the signature. This function
1562 should return 0 on a good signature, GPG_ERR_BAD_SIGNATURE if the
1563 signature does not verify or any other error code. CRL is the CRL
1564 object we are working on, MD the hash context and ISSUER_CERT the
1565 certificate of the CRL issuer. This function closes MD. */
1567 finish_sig_check (ksba_crl_t crl, gcry_md_hd_t md, int algo,
1568 ksba_cert_t issuer_cert)
1571 ksba_sexp_t sigval = NULL, pubkey = NULL;
1575 gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
1578 /* This also stops debugging on the MD. */
1581 /* Get and convert the signature value. */
1582 sigval = ksba_crl_get_sig_val (crl);
1583 n = gcry_sexp_canon_len (sigval, 0, NULL, NULL);
1586 log_error (_("got an invalid S-expression from libksba\n"));
1587 err = gpg_error (GPG_ERR_INV_SEXP);
1590 err = gcry_sexp_sscan (&s_sig, NULL, sigval, n);
1593 log_error (_("converting S-expression failed: %s\n"),
1594 gcry_strerror (err));
1598 /* Get and convert the public key for the issuer certificate. */
1600 dump_cert ("crl_issuer_cert", issuer_cert);
1601 pubkey = ksba_cert_get_public_key (issuer_cert);
1602 n = gcry_sexp_canon_len (pubkey, 0, NULL, NULL);
1605 log_error (_("got an invalid S-expression from libksba\n"));
1606 err = gpg_error (GPG_ERR_INV_SEXP);
1609 err = gcry_sexp_sscan (&s_pkey, NULL, pubkey, n);
1612 log_error (_("converting S-expression failed: %s\n"),
1613 gcry_strerror (err));
1617 /* Create an S-expression with the actual hash value. */
1618 s = gcry_md_algo_name (algo);
1619 for (i = 0; *s && i < sizeof(algoname) - 1; s++, i++)
1620 algoname[i] = ascii_tolower (*s);
1622 err = gcry_sexp_build (&s_hash, NULL, "(data(flags pkcs1)(hash %s %b))",
1624 gcry_md_get_algo_dlen (algo), gcry_md_read (md, algo));
1627 log_error (_("creating S-expression failed: %s\n"), gcry_strerror (err));
1631 /* Pass this on to the signature verification. */
1632 err = gcry_pk_verify (s_sig, s_hash, s_pkey);
1634 log_debug ("gcry_pk_verify: %s\n", gpg_strerror (err));
1639 gcry_sexp_release (s_sig);
1640 gcry_sexp_release (s_hash);
1641 gcry_sexp_release (s_pkey);
1648 /* Call this to match a start_sig_check that can not be completed
1651 abort_sig_check (ksba_crl_t crl, gcry_md_hd_t md)
1658 /* Workhorse of the CRL loading machinery. The CRL is read using the
1659 CRL object and stored in the data base file DB with the name FNAME
1660 (only used for printing error messages). That DB should be a
1661 temporary one and not the actual one. If the function fails the
1662 caller should delete this temporary database file. CTRL is
1663 required to retrieve certificates using the general dirmngr
1664 callback service. R_CRLISSUER returns an allocated string with the
1665 crl-issuer DN, THIS_UPDATE and NEXT_UPDATE are filled with the
1666 corresponding data from the CRL. Note that these values might get
1667 set even if the CRL processing fails at a later step; thus the
1668 caller should free *R_ISSUER even if the function returns with an
1669 error. R_TRUST_ANCHOR is set on exit to NULL or a string with the
1670 hexified fingerprint of the root certificate, if checking this
1671 certificate for trustiness is required.
1674 crl_parse_insert (ctrl_t ctrl, ksba_crl_t crl,
1675 struct cdb_make *cdb, const char *fname,
1677 ksba_isotime_t thisupdate, ksba_isotime_t nextupdate,
1678 char **r_trust_anchor)
1681 ksba_stop_reason_t stopreason;
1682 ksba_cert_t crlissuer_cert = NULL;
1683 gcry_md_hd_t md = NULL;
1689 *r_crlissuer = NULL;
1690 *thisupdate = *nextupdate = 0;
1691 *r_trust_anchor = NULL;
1693 /* Start of the KSBA parser loop. */
1696 err = ksba_crl_parse (crl, &stopreason);
1699 log_error (_("ksba_crl_parse failed: %s\n"), gpg_strerror (err) );
1705 case KSBA_SR_BEGIN_ITEMS:
1707 err = start_sig_check (crl, &md, &algo);
1711 err = ksba_crl_get_update_times (crl, thisupdate, nextupdate);
1714 log_error (_("error getting update times of CRL: %s\n"),
1715 gpg_strerror (err));
1716 err = gpg_error (GPG_ERR_INV_CRL);
1720 if (opt.verbose || !*nextupdate)
1721 log_info (_("update times of this CRL: this=%s next=%s\n"),
1722 thisupdate, nextupdate);
1725 log_info (_("nextUpdate not given; "
1726 "assuming a validity period of one day\n"));
1727 gnupg_copy_time (nextupdate, thisupdate);
1728 add_seconds_to_isotime (nextupdate, 86400);
1733 case KSBA_SR_GOT_ITEM:
1736 const unsigned char *p;
1737 ksba_isotime_t rdate;
1738 ksba_crl_reason_t reason;
1740 unsigned char record[1+15];
1742 err = ksba_crl_get_item (crl, &serial, rdate, &reason);
1745 log_error (_("error getting CRL item: %s\n"),
1746 gpg_strerror (err));
1747 err = gpg_error (GPG_ERR_INV_CRL);
1751 p = serial_to_buffer (serial, &n);
1754 record[0] = (reason & 0xff);
1755 memcpy (record+1, rdate, 15);
1756 rc = cdb_make_add (cdb, p, n, record, 1+15);
1759 err = gpg_error_from_errno (errno);
1760 log_error (_("error inserting item into "
1761 "temporary cache file: %s\n"),
1770 case KSBA_SR_END_ITEMS:
1777 ksba_sexp_t authidsn;
1780 /* We need to look for the issuer only after having read
1781 all items. The issuer itselfs comes before the items
1782 but the optional authorityKeyIdentifier comes after the
1784 err = ksba_crl_get_issuer (crl, &crlissuer);
1787 log_error (_("no CRL issuer found in CRL: %s\n"),
1788 gpg_strerror (err) );
1789 err = gpg_error (GPG_ERR_INV_CRL);
1792 /* Note: This should be released by ksba_free, not xfree.
1793 May need a memory reallocation dance. */
1794 *r_crlissuer = crlissuer; /* (Do it here so we don't need
1795 to free it later) */
1797 if (!ksba_crl_get_auth_key_id (crl, &keyid, &authid, &authidsn))
1802 log_info (_("locating CRL issuer certificate by "
1803 "authorityKeyIdentifier\n"));
1805 s = ksba_name_enum (authid, 0);
1807 crlissuer_cert = find_cert_bysn (ctrl, s, authidsn);
1808 if (!crlissuer_cert && keyid)
1809 crlissuer_cert = find_cert_bysubject (ctrl,
1812 if (!crlissuer_cert)
1814 log_info ("CRL issuer certificate ");
1818 dump_serial (keyid);
1824 dump_serial (authidsn);
1829 log_printf ("not found\n");
1831 ksba_name_release (authid);
1836 crlissuer_cert = find_cert_bysubject (ctrl, crlissuer, NULL);
1838 if (!crlissuer_cert)
1840 err = gpg_error (GPG_ERR_MISSING_CERT);
1844 err = finish_sig_check (crl, md, algo, crlissuer_cert);
1847 log_error (_("CRL signature verification failed: %s\n"),
1848 gpg_strerror (err));
1853 err = validate_cert_chain (ctrl, crlissuer_cert, NULL,
1854 VALIDATE_MODE_CRL_RECURSIVE,
1858 log_error (_("error checking validity of CRL "
1859 "issuer certificate: %s\n"),
1860 gpg_strerror (err));
1868 log_debug ("crl_parse_insert: unknown stop reason\n");
1869 err = gpg_error (GPG_ERR_BUG);
1873 while (stopreason != KSBA_SR_READY);
1879 abort_sig_check (crl, md);
1880 ksba_cert_release (crlissuer_cert);
1886 /* Return the crlNumber extension as an allocated hex string or NULL
1887 if there is none. */
1889 get_crl_number (ksba_crl_t crl)
1895 err = ksba_crl_get_crl_number (crl, &number);
1898 string = serial_hex (number);
1904 /* Return the authorityKeyIdentifier or NULL if it is not available.
1905 The issuer name may consists of several parts - they are delimted by
1908 get_auth_key_id (ksba_crl_t crl, char **serialno)
1919 err = ksba_crl_get_auth_key_id (crl, NULL, &name, &sn);
1922 *serialno = serial_hex (sn);
1926 return xstrdup ("");
1929 for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
1931 char *p = ksba_name_get_uri (name, idx);
1932 length += strlen (p?p:s) + 1;
1935 string = xtrymalloc (length+1);
1939 for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
1941 char *p = ksba_name_get_uri (name, idx);
1943 strcat (string, "\x01");
1944 strcat (string, p?p:s);
1948 ksba_name_release (name);
1954 /* Insert the CRL retrieved using URL into the cache specified by
1955 CACHE. The CRL itself will be read from the stream FP and is
1956 expected in binary format.
1962 crl_cache_reload_crl
1970 crl_cache_insert (ctrl_t ctrl, const char *url, ksba_reader_t reader)
1972 crl_cache_t cache = get_current_cache ();
1973 gpg_error_t err, err2;
1976 char *newfname = NULL;
1977 struct cdb_make cdb;
1979 char *issuer = NULL;
1980 char *issuer_hash = NULL;
1981 ksba_isotime_t thisupdate, nextupdate;
1982 crl_cache_entry_t entry = NULL;
1983 crl_cache_entry_t e;
1984 gnupg_isotime_t current_time;
1985 char *checksum = NULL;
1986 int invalidate_crl = 0;
1990 char *trust_anchor = NULL;
1992 /* FIXME: We should acquire a mutex for the URL, so that we don't
1993 simultaneously enter the same CRL twice. However this needs to be
1994 interweaved with the checking function.*/
1998 err = ksba_crl_new (&crl);
2001 log_error (_("ksba_crl_new failed: %s\n"), gpg_strerror (err));
2005 err = ksba_crl_set_reader (crl, reader);
2008 log_error (_("ksba_crl_set_reader failed: %s\n"), gpg_strerror (err));
2012 /* Create a temporary cache file to load the CRL into. */
2015 const char *nodename;
2016 #ifndef HAVE_W32_SYSTEM
2017 struct utsname utsbuf;
2020 #ifdef HAVE_W32_SYSTEM
2021 nodename = "unknown";
2023 if (uname (&utsbuf))
2024 nodename = "unknown";
2026 nodename = utsbuf.nodename;
2029 gpgrt_asprintf (&tmpfname, "crl-tmp-%s-%u-%p.db.tmp",
2030 nodename, (unsigned int)getpid (), &tmpfname);
2033 err = gpg_error_from_syserror ();
2036 for (p=tmpfname; *p; p++)
2039 fname = make_filename (opt.homedir_cache, DBDIR_D, tmpfname, NULL);
2041 if (!gnupg_remove (fname))
2042 log_info (_("removed stale temporary cache file '%s'\n"), fname);
2043 else if (errno != ENOENT)
2045 err = gpg_error_from_syserror ();
2046 log_error (_("problem removing stale temporary cache file '%s': %s\n"),
2047 fname, gpg_strerror (err));
2052 fd_cdb = open (fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2055 err = gpg_error_from_errno (errno);
2056 log_error (_("error creating temporary cache file '%s': %s\n"),
2057 fname, strerror (errno));
2060 cdb_make_start(&cdb, fd_cdb);
2062 err = crl_parse_insert (ctrl, crl, &cdb, fname,
2063 &issuer, thisupdate, nextupdate, &trust_anchor);
2066 log_error (_("crl_parse_insert failed: %s\n"), gpg_strerror (err));
2067 /* Error in cleanup ignored. */
2068 cdb_make_finish (&cdb);
2072 /* Finish the database. */
2073 if (cdb_make_finish (&cdb))
2075 err = gpg_error_from_errno (errno);
2076 log_error (_("error finishing temporary cache file '%s': %s\n"),
2077 fname, strerror (errno));
2082 err = gpg_error_from_errno (errno);
2083 log_error (_("error closing temporary cache file '%s': %s\n"),
2084 fname, strerror (errno));
2090 /* Create a checksum. */
2092 unsigned char md5buf[16];
2094 if (hash_dbfile (fname, md5buf))
2096 err = gpg_error (GPG_ERR_CHECKSUM);
2099 checksum = hexify_data (md5buf, 16, 0);
2103 /* Check whether that new CRL is still not expired. */
2104 gnupg_get_isotime (current_time);
2105 if (strcmp (nextupdate, current_time) < 0 )
2108 log_info (_("WARNING: new CRL still too old; it expired on %s "
2109 "- loading anyway\n"), nextupdate);
2112 log_error (_("new CRL still too old; it expired on %s\n"),
2115 err2 = gpg_error (GPG_ERR_CRL_TOO_OLD);
2116 invalidate_crl |= 1;
2120 /* Check for unknown critical extensions. */
2121 for (idx=0; !(err=ksba_crl_get_extension (crl, idx, &oid, &critical,
2122 NULL, NULL)); idx++)
2125 || !strcmp (oid, oidstr_authorityKeyIdentifier)
2126 || !strcmp (oid, oidstr_crlNumber) )
2128 log_error (_("unknown critical CRL extension %s\n"), oid);
2130 err2 = gpg_error (GPG_ERR_INV_CRL);
2131 invalidate_crl |= 2;
2133 if (gpg_err_code (err) == GPG_ERR_EOF
2134 || gpg_err_code (err) == GPG_ERR_NO_DATA )
2138 log_error (_("error reading CRL extensions: %s\n"), gpg_strerror (err));
2139 err = gpg_error (GPG_ERR_INV_CRL);
2143 /* Create an hex encoded SHA-1 hash of the issuer DN to be
2144 used as the key for the cache. */
2145 issuer_hash = hashify_data (issuer, strlen (issuer));
2147 /* Create an ENTRY. */
2148 entry = xtrycalloc (1, sizeof *entry);
2151 err = gpg_error_from_syserror ();
2154 entry->release_ptr = xtrymalloc (strlen (issuer_hash) + 1
2155 + strlen (issuer) + 1
2157 + strlen (checksum) + 1);
2158 if (!entry->release_ptr)
2160 err = gpg_error_from_syserror ();
2165 entry->issuer_hash = entry->release_ptr;
2166 entry->issuer = stpcpy (entry->issuer_hash, issuer_hash) + 1;
2167 entry->url = stpcpy (entry->issuer, issuer) + 1;
2168 entry->dbfile_hash = stpcpy (entry->url, url) + 1;
2169 strcpy (entry->dbfile_hash, checksum);
2170 gnupg_copy_time (entry->this_update, thisupdate);
2171 gnupg_copy_time (entry->next_update, nextupdate);
2172 gnupg_copy_time (entry->last_refresh, current_time);
2173 entry->crl_number = get_crl_number (crl);
2174 entry->authority_issuer = get_auth_key_id (crl, &entry->authority_serialno);
2175 entry->invalid = invalidate_crl;
2176 entry->user_trust_req = !!trust_anchor;
2177 entry->check_trust_anchor = trust_anchor;
2178 trust_anchor = NULL;
2180 /* Check whether we already have an entry for this issuer and mark
2181 it as deleted. We better use a loop, just in case duplicates got
2182 somehow into the list. */
2183 for (e = cache->entries; (e=find_entry (e, entry->issuer_hash)); e = e->next)
2186 /* Rename the temporary DB to the real name. */
2187 newfname = make_db_file_name (entry->issuer_hash);
2189 log_info (_("creating cache file '%s'\n"), newfname);
2191 /* Just in case close unused matching files. Actually we need this
2192 only under Windows but saving file descriptors is never bad. */
2198 for (e = cache->entries; e; e = e->next)
2199 if (!e->cdb_use_count && e->cdb
2200 && !strcmp (e->issuer_hash, entry->issuer_hash))
2202 int fd = cdb_fileno (e->cdb);
2207 log_error (_("error closing cache file: %s\n"),
2215 #ifdef HAVE_W32_SYSTEM
2216 gnupg_remove (newfname);
2218 if (rename (fname, newfname))
2220 err = gpg_error_from_syserror ();
2221 log_error (_("problem renaming '%s' to '%s': %s\n"),
2222 fname, newfname, gpg_strerror (err));
2225 xfree (fname); fname = NULL; /*(let the cleanup code not try to remove it)*/
2227 /* Link the new entry in. */
2228 entry->next = cache->entries;
2229 cache->entries = entry;
2232 err = update_dir (cache);
2235 log_error (_("updating the DIR file failed - "
2236 "cache entry will get lost with the next program start\n"));
2237 err = 0; /* Keep on running. */
2242 release_one_cache_entry (entry);
2247 gnupg_remove (fname);
2251 ksba_crl_release (crl);
2253 xfree (issuer_hash);
2255 xfree (trust_anchor);
2256 return err ? err : err2;
2260 /* Print one cached entry E in a human readable format to stream
2261 FP. Return 0 on success. */
2263 list_one_crl_entry (crl_cache_t cache, crl_cache_entry_t e, estream_t fp)
2265 struct cdb_find cdbfp;
2269 const unsigned char *s;
2271 es_fputs ("--------------------------------------------------------\n", fp );
2272 es_fprintf (fp, _("Begin CRL dump (retrieved via %s)\n"), e->url );
2273 es_fprintf (fp, " Issuer:\t%s\n", e->issuer );
2274 es_fprintf (fp, " Issuer Hash:\t%s\n", e->issuer_hash );
2275 es_fprintf (fp, " This Update:\t%s\n", e->this_update );
2276 es_fprintf (fp, " Next Update:\t%s\n", e->next_update );
2277 es_fprintf (fp, " CRL Number :\t%s\n", e->crl_number? e->crl_number: "none");
2278 es_fprintf (fp, " AuthKeyId :\t%s\n",
2279 e->authority_serialno? e->authority_serialno:"none");
2280 if (e->authority_serialno && e->authority_issuer)
2282 es_fputs (" \t", fp);
2283 for (s=e->authority_issuer; *s; s++)
2285 es_fputs ("\n \t", fp);
2290 es_fprintf (fp, " Trust Check:\t%s\n",
2291 !e->user_trust_req? "[system]" :
2292 e->check_trust_anchor? e->check_trust_anchor:"[missing]");
2294 if ((e->invalid & 1))
2295 es_fprintf (fp, _(" ERROR: The CRL will not be used "
2296 "because it was still too old after an update!\n"));
2297 if ((e->invalid & 2))
2298 es_fprintf (fp, _(" ERROR: The CRL will not be used "
2299 "due to an unknown critical extension!\n"));
2300 if ((e->invalid & ~3))
2301 es_fprintf (fp, _(" ERROR: The CRL will not be used\n"));
2303 cdb = lock_db_file (cache, e);
2305 return gpg_error (GPG_ERR_GENERAL);
2307 if (!e->dbfile_checked)
2308 es_fprintf (fp, _(" ERROR: This cached CRL may have been tampered with!\n"));
2312 rc = cdb_findinit (&cdbfp, cdb, NULL, 0);
2313 while (!rc && (rc=cdb_findnext (&cdbfp)) > 0 )
2315 unsigned char keyrecord[256];
2316 unsigned char record[16];
2323 n = cdb_datalen (cdb);
2326 log_error (_(" WARNING: invalid cache record length\n"));
2331 if (cdb_read (cdb, record, n, cdb_datapos (cdb)))
2333 log_error (_("problem reading cache record: %s\n"),
2339 n = cdb_keylen (cdb);
2340 if (n > sizeof keyrecord)
2341 n = sizeof keyrecord;
2342 if (cdb_read (cdb, keyrecord, n, cdb_keypos (cdb)))
2344 log_error (_("problem reading cache key: %s\n"), strerror (errno));
2351 for (i = 0; i < n; i++)
2352 es_fprintf (fp, "%02X", keyrecord[i]);
2353 es_fputs (":\t reasons( ", fp);
2355 if (reason & KSBA_CRLREASON_UNSPECIFIED)
2356 es_fputs( "unspecified ", fp ), any = 1;
2357 if (reason & KSBA_CRLREASON_KEY_COMPROMISE )
2358 es_fputs( "key_compromise ", fp ), any = 1;
2359 if (reason & KSBA_CRLREASON_CA_COMPROMISE )
2360 es_fputs( "ca_compromise ", fp ), any = 1;
2361 if (reason & KSBA_CRLREASON_AFFILIATION_CHANGED )
2362 es_fputs( "affiliation_changed ", fp ), any = 1;
2363 if (reason & KSBA_CRLREASON_SUPERSEDED )
2364 es_fputs( "superseded", fp ), any = 1;
2365 if (reason & KSBA_CRLREASON_CESSATION_OF_OPERATION )
2366 es_fputs( "cessation_of_operation", fp ), any = 1;
2367 if (reason & KSBA_CRLREASON_CERTIFICATE_HOLD )
2368 es_fputs( "certificate_hold", fp ), any = 1;
2370 es_fputs( "other", fp );
2372 es_fprintf (fp, ") rdate: %.15s\n", record+1);
2375 log_error (_("error reading cache entry from db: %s\n"), strerror (rc));
2377 unlock_db_file (cache, e);
2378 es_fprintf (fp, _("End CRL dump\n") );
2381 return (rc||warn)? gpg_error (GPG_ERR_GENERAL) : 0;
2385 /* Print the contents of the CRL CACHE in a human readable format to
2388 crl_cache_list (estream_t fp)
2390 crl_cache_t cache = get_current_cache ();
2391 crl_cache_entry_t entry;
2392 gpg_error_t err = 0;
2394 for (entry = cache->entries;
2395 entry && !entry->deleted && !err;
2396 entry = entry->next )
2397 err = list_one_crl_entry (cache, entry, fp);
2403 /* Load the CRL containing the file named FILENAME into our CRL cache. */
2405 crl_cache_load (ctrl_t ctrl, const char *filename)
2409 ksba_reader_t reader;
2411 fp = es_fopen (filename, "rb");
2414 err = gpg_error_from_errno (errno);
2415 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2419 err = create_estream_ksba_reader (&reader, fp);
2422 err = crl_cache_insert (ctrl, filename, reader);
2423 ksba_reader_release (reader);
2430 /* Locate the corresponding CRL for the certificate CERT, read and
2431 verify the CRL and store it in the cache. */
2433 crl_cache_reload_crl (ctrl_t ctrl, ksba_cert_t cert)
2436 ksba_reader_t reader = NULL;
2437 char *issuer = NULL;
2438 ksba_name_t distpoint = NULL;
2439 ksba_name_t issuername = NULL;
2440 char *distpoint_uri = NULL;
2441 char *issuername_uri = NULL;
2442 int any_dist_point = 0;
2445 /* Loop over all distribution points, get the CRLs and put them into
2448 log_info ("checking distribution points\n");
2450 while ( !(err = ksba_cert_get_crl_dist_point (cert, seq++,
2452 &issuername, NULL )))
2455 gpg_error_t last_err = 0;
2457 if (!distpoint && !issuername)
2460 log_info ("no issuer name and no distribution point\n");
2461 break; /* Not allowed; i.e. an invalid certificate. We give
2462 up here and hope that the default method returns a
2466 xfree (issuername_uri); issuername_uri = NULL;
2468 /* Get the URIs. We do this in a loop to iterate over all names
2470 for (name_seq=0; ksba_name_enum (distpoint, name_seq); name_seq++)
2472 xfree (distpoint_uri); distpoint_uri = NULL;
2473 distpoint_uri = ksba_name_get_uri (distpoint, name_seq);
2477 if (!strncmp (distpoint_uri, "ldap:", 5)
2478 || !strncmp (distpoint_uri, "ldaps:", 6))
2480 if (opt.ignore_ldap_dp)
2483 else if (!strncmp (distpoint_uri, "http:", 5)
2484 || !strncmp (distpoint_uri, "https:", 6))
2486 if (opt.ignore_http_dp)
2490 continue; /* Skip unknown schemes. */
2495 log_info ("fetching CRL from '%s'\n", distpoint_uri);
2496 err = crl_fetch (ctrl, distpoint_uri, &reader);
2499 log_error (_("crl_fetch via DP failed: %s\n"),
2500 gpg_strerror (err));
2502 continue; /* with the next name. */
2506 log_info ("inserting CRL (reader %p)\n", reader);
2507 err = crl_cache_insert (ctrl, distpoint_uri, reader);
2510 log_error (_("crl_cache_insert via DP failed: %s\n"),
2511 gpg_strerror (err));
2513 continue; /* with the next name. */
2524 ksba_name_release (distpoint); distpoint = NULL;
2526 /* We don't do anything with issuername_uri yet but we keep the
2527 code for documentation. */
2528 issuername_uri = ksba_name_get_uri (issuername, 0);
2529 ksba_name_release (issuername); issuername = NULL;
2531 /* Close the reader. */
2532 crl_close_reader (reader);
2535 if (gpg_err_code (err) == GPG_ERR_EOF)
2538 /* If we did not found any distpoint, try something reasonable. */
2539 if (!any_dist_point )
2542 log_info ("no distribution point - trying issuer name\n");
2544 crl_close_reader (reader);
2547 issuer = ksba_cert_get_issuer (cert, 0);
2550 log_error ("oops: issuer missing in certificate\n");
2551 err = gpg_error (GPG_ERR_INV_CERT_OBJ);
2556 log_info ("fetching CRL from default location\n");
2557 err = crl_fetch_default (ctrl, issuer, &reader);
2560 log_error ("crl_fetch via issuer failed: %s\n",
2561 gpg_strerror (err));
2566 log_info ("inserting CRL (reader %p)\n", reader);
2567 err = crl_cache_insert (ctrl, "default location(s)", reader);
2570 log_error (_("crl_cache_insert via issuer failed: %s\n"),
2571 gpg_strerror (err));
2577 crl_close_reader (reader);
2578 xfree (distpoint_uri);
2579 xfree (issuername_uri);
2580 ksba_name_release (distpoint);
2581 ksba_name_release (issuername);