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 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>
106 #include "validate.h"
107 #include "certcache.h"
108 #include "crlcache.h"
109 #include "crlfetch.h"
113 /* Change this whenever the format changes */
114 #define DBDIR_D "crls.d"
115 #define DBDIRFILE "DIR.txt"
116 #define DBDIRVERSION 1
118 /* The number of DB files we may have open at one time. We need to
119 limit this because there is no guarantee that the number of issuers
120 has a upper limit. We are currently using mmap, so it is a good
121 idea anyway to limit the number of opened cache files. */
122 #define MAX_OPEN_DB_FILES 5
129 /* Reason flags for an invalid CRL. */
130 #define INVCRL_TOO_OLD 1
131 #define INVCRL_UNKNOWN_EXTN 2
132 #define INVCRL_GENERAL 127
135 static const char oidstr_crlNumber[] = "2.5.29.20";
136 /* static const char oidstr_issuingDistributionPoint[] = "2.5.29.28"; */
137 static const char oidstr_authorityKeyIdentifier[] = "2.5.29.35";
140 /* Definition of one cached item. */
141 struct crl_cache_entry_s
143 struct crl_cache_entry_s *next;
144 int deleted; /* True if marked for deletion. */
145 int mark; /* Internally used by update_dir. */
146 unsigned int lineno;/* A 0 indicates a new entry. */
147 char *release_ptr; /* The actual allocated memory. */
148 char *url; /* Points into RELEASE_PTR. */
149 char *issuer; /* Ditto. */
150 char *issuer_hash; /* Ditto. */
151 char *dbfile_hash; /* MD5 sum of the cache file, points into RELEASE_PTR.*/
152 int invalid; /* Can't use this CRL. */
153 int user_trust_req; /* User supplied root certificate required. */
154 char *check_trust_anchor; /* Malloced fingerprint. */
155 ksba_isotime_t this_update;
156 ksba_isotime_t next_update;
157 ksba_isotime_t last_refresh; /* Use for the force_crl_refresh feature. */
159 char *authority_issuer;
160 char *authority_serialno;
162 struct cdb *cdb; /* The cache file handle or NULL if not open. */
164 unsigned int cdb_use_count; /* Current use count. */
165 unsigned int cdb_lru_count; /* Used for LRU purposes. */
166 int dbfile_checked; /* Set to true if the dbfile_hash value has
167 been checked once. */
171 /* Definition of the entire cache object. */
174 crl_cache_entry_t entries;
177 typedef struct crl_cache_s *crl_cache_t;
181 static crl_cache_entry_t find_entry (crl_cache_entry_t first,
182 const char *issuer_hash);
186 /* The currently loaded cache object. This is usually initialized
188 static crl_cache_t current_cache;
194 /* Return the current cache object or bail out if it is has not yet
197 get_current_cache (void)
200 log_fatal ("CRL cache has not yet been initialized\n");
201 return current_cache;
206 Create ae directory if it does not yet exists. Returns on
207 success, or -1 on error.
210 create_directory_if_needed (const char *name)
215 fname = make_filename (opt.homedir_cache, name, NULL);
216 dir = gnupg_opendir (fname);
219 log_info (_("creating directory '%s'\n"), fname);
220 if (gnupg_mkdir (fname, "-rwx"))
222 int save_errno = errno;
223 log_error (_("error creating directory '%s': %s\n"),
224 fname, strerror (errno));
226 gpg_err_set_errno (save_errno);
231 gnupg_closedir (dir);
236 /* Remove all files from the cache directory. If FORCE is not true,
237 some sanity checks on the filenames are done. Return 0 if
238 everything went fine. */
240 cleanup_cache_dir (int force)
242 char *dname = make_filename (opt.homedir_cache, DBDIR_D, NULL);
248 { /* Very minor sanity checks. */
249 if (!strcmp (dname, "~/") || !strcmp (dname, "/" ))
251 log_error (_("ignoring database dir '%s'\n"), dname);
257 dir = gnupg_opendir (dname);
260 log_error (_("error reading directory '%s': %s\n"),
261 dname, strerror (errno));
266 while ((de = gnupg_readdir (dir)))
268 if (strcmp (de->d_name, "." ) && strcmp (de->d_name, ".."))
270 char *cdbname = make_filename (dname, de->d_name, NULL);
277 okay = (!gnupg_stat (cdbname, &sbuf) && S_ISREG (sbuf.st_mode));
281 log_info (_("removing cache file '%s'\n"), cdbname);
282 if (gnupg_remove (cdbname))
284 log_error ("failed to remove '%s': %s\n",
285 cdbname, strerror (errno));
290 log_info (_("not removing file '%s'\n"), cdbname);
295 gnupg_closedir (dir);
300 /* Read the next line from the file FP and return the line in an
301 malloced buffer. Return NULL on error or EOF. There is no
302 limitation os the line length. The trailing linefeed has been
303 removed, the function will read the last line of a file, even if
304 that is not terminated by a LF. */
306 next_line_from_file (estream_t fp, gpg_error_t *r_err)
309 char *largebuf = NULL;
318 buflen = sizeof buf - 1;
319 while ((c=es_getc (fp)) != EOF && c != '\n')
326 largebuf = xtrymalloc ( buflen + 1 );
329 *r_err = gpg_error_from_syserror ();
332 memcpy (largebuf, buf, len);
337 tmpbuf = xtryrealloc (largebuf, buflen + 1);
340 *r_err = gpg_error_from_syserror ();
350 if (c == EOF && !len)
355 tmpbuf = xtryrealloc (largebuf, len+1);
357 tmpbuf = xtrystrdup (buf);
360 *r_err = gpg_error_from_syserror ();
367 /* Release one cache entry. */
369 release_one_cache_entry (crl_cache_entry_t entry)
375 int fd = cdb_fileno (entry->cdb);
376 cdb_free (entry->cdb);
379 log_error (_("error closing cache file: %s\n"), strerror(errno));
381 xfree (entry->release_ptr);
382 xfree (entry->check_trust_anchor);
388 /* Release the CACHE object. */
390 release_cache (crl_cache_t cache)
392 crl_cache_entry_t entry, entry2;
397 for (entry = cache->entries; entry; entry = entry2)
399 entry2 = entry->next;
400 release_one_cache_entry (entry);
402 cache->entries = NULL;
407 /* Open the dir file FNAME or create a new one if it does not yet
410 open_dir_file (const char *fname)
414 fp = es_fopen (fname, "r");
417 log_error (_("failed to open cache dir file '%s': %s\n"),
418 fname, strerror (errno));
420 /* Make sure that the directory exists, try to create if otherwise. */
421 if (create_directory_if_needed (NULL)
422 || create_directory_if_needed (DBDIR_D))
424 fp = es_fopen (fname, "w");
427 log_error (_("error creating new cache dir file '%s': %s\n"),
428 fname, strerror (errno));
431 es_fprintf (fp, "v:%d:\n", DBDIRVERSION);
434 log_error (_("error writing new cache dir file '%s': %s\n"),
435 fname, strerror (errno));
441 log_error (_("error closing new cache dir file '%s': %s\n"),
442 fname, strerror (errno));
446 log_info (_("new cache dir file '%s' created\n"), fname);
448 fp = es_fopen (fname, "r");
451 log_error (_("failed to re-open cache dir file '%s': %s\n"),
452 fname, strerror (errno));
460 /* Helper for open_dir. */
462 check_dir_version (estream_t *fpadr, const char *fname,
463 unsigned int *lineno,
464 int cleanup_on_mismatch)
467 gpg_error_t lineerr = 0;
468 estream_t fp = *fpadr;
472 while ((line = next_line_from_file (fp, &lineerr)))
475 if (*line == 'v' && line[1] == ':')
477 else if (*line != '#')
479 log_error (_("first record of '%s' is not the version\n"), fname);
481 return gpg_error (GPG_ERR_CONFIGURATION);
488 /* The !line catches the case of an empty DIR file. We handle this
489 the same as a non-matching version. */
490 if (!line || strtol (line+2, NULL, 10) != DBDIRVERSION)
492 if (!created && cleanup_on_mismatch)
494 log_error (_("old version of cache directory - cleaning up\n"));
497 if (!cleanup_cache_dir (1))
500 fp = *fpadr = open_dir_file (fname);
504 return gpg_error (GPG_ERR_CONFIGURATION);
510 log_error (_("old version of cache directory - giving up\n"));
512 return gpg_error (GPG_ERR_CONFIGURATION);
519 /* Open the dir file and read in all available information. Store
520 that in a newly allocated cache object and return that if
521 everything worked out fine. Create the cache directory and the dir
522 if it does not yet exist. Remove all files in that directory if
523 the version does not match. */
525 open_dir (crl_cache_t *r_cache)
530 gpg_error_t lineerr = 0;
532 crl_cache_entry_t entry, *entrytail;
537 cache = xtrycalloc (1, sizeof *cache);
539 return gpg_error_from_syserror ();
541 fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);
544 fp = open_dir_file (fname);
547 err = gpg_error (GPG_ERR_CONFIGURATION);
551 err = check_dir_version (&fp, fname, &lineno, 1);
556 /* Read in all supported entries from the dir file. */
557 cache->entries = NULL;
558 entrytail = &cache->entries;
560 while ((line = next_line_from_file (fp, &lineerr)))
566 if ( *line == 'c' || *line == 'u' || *line == 'i' )
568 entry = xtrycalloc (1, sizeof *entry);
571 err = gpg_error_from_syserror ();
574 entry->lineno = lineno;
575 entry->release_ptr = line;
578 entry->invalid = atoi (line+1);
580 entry->invalid = INVCRL_GENERAL;
582 else if (*line == 'u')
583 entry->user_trust_req = 1;
585 for (fieldno=1, p = line; p; p = endp, fieldno++)
587 endp = strchr (p, ':');
593 case 1: /* record type */ break;
594 case 2: entry->issuer_hash = p; break;
595 case 3: entry->issuer = unpercent_string (p); break;
596 case 4: entry->url = unpercent_string (p); break;
598 strncpy (entry->this_update, p, 15);
599 entry->this_update[15] = 0;
602 strncpy (entry->next_update, p, 15);
603 entry->next_update[15] = 0;
605 case 7: entry->dbfile_hash = p; break;
606 case 8: if (*p) entry->crl_number = p; break;
609 entry->authority_issuer = unpercent_string (p);
613 entry->authority_serialno = unpercent_string (p);
617 entry->check_trust_anchor = xtrystrdup (p);
621 log_info (_("extra field detected in crl record of "
622 "'%s' line %u\n"), fname, lineno);
627 if (!entry->issuer_hash)
629 log_info (_("invalid line detected in '%s' line %u\n"),
634 else if (find_entry (cache->entries, entry->issuer_hash))
636 /* Fixme: The duplicate checking used is not very
637 effective for large numbers of issuers. */
638 log_info (_("duplicate entry detected in '%s' line %u\n"),
647 entrytail = &entry->next;
650 else if (*line == '#')
653 log_info (_("unsupported record type in '%s' line %u skipped\n"),
662 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
667 log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
668 err = gpg_error (GPG_ERR_CONFIGURATION);
672 /* Now do some basic checks on the data. */
673 for (entry = cache->entries; entry; entry = entry->next)
675 assert (entry->lineno);
676 if (strlen (entry->issuer_hash) != 40)
679 log_error (_("invalid issuer hash in '%s' line %u\n"),
680 fname, entry->lineno);
682 else if ( !*entry->issuer )
685 log_error (_("no issuer DN in '%s' line %u\n"),
686 fname, entry->lineno);
688 else if ( check_isotime (entry->this_update)
689 || check_isotime (entry->next_update))
692 log_error (_("invalid timestamp in '%s' line %u\n"),
693 fname, entry->lineno);
696 /* Checks not leading to an immediate fail. */
697 if (strlen (entry->dbfile_hash) != 32)
698 log_info (_("WARNING: invalid cache file hash in '%s' line %u\n"),
699 fname, entry->lineno);
704 log_error (_("detected errors in cache dir file\n"));
705 log_info (_("please check the reason and manually delete that file\n"));
706 err = gpg_error (GPG_ERR_CONFIGURATION);
716 release_cache (cache);
724 write_percented_string (const char *s, estream_t fp)
728 es_fputs ("%3A", fp);
730 es_fputs ("%0A", fp);
732 es_fputs ("%0D", fp);
739 write_dir_line_crl (estream_t fp, crl_cache_entry_t e)
742 es_fprintf (fp, "i%d", e->invalid);
743 else if (e->user_trust_req)
748 es_fputs (e->issuer_hash, fp);
750 write_percented_string (e->issuer, fp);
752 write_percented_string (e->url, fp);
754 es_fwrite (e->this_update, 15, 1, fp);
756 es_fwrite (e->next_update, 15, 1, fp);
758 es_fputs (e->dbfile_hash, fp);
761 es_fputs (e->crl_number, fp);
763 if (e->authority_issuer)
764 write_percented_string (e->authority_issuer, fp);
766 if (e->authority_serialno)
767 es_fputs (e->authority_serialno, fp);
769 if (e->check_trust_anchor && e->user_trust_req)
770 es_fputs (e->check_trust_anchor, fp);
775 /* Update the current dir file using the cache. */
777 update_dir (crl_cache_t cache)
780 char *tmpfname = NULL;
782 gpg_error_t lineerr = 0;
784 estream_t fpout = NULL;
789 fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);
791 /* Fixme: Take an update file lock here. */
793 for (e= cache->entries; e; e = e->next)
797 fp = es_fopen (fname, "r");
800 err = gpg_error_from_errno (errno);
801 log_error (_("failed to open cache dir file '%s': %s\n"),
802 fname, strerror (errno));
805 err = check_dir_version (&fp, fname, &lineno, 0);
811 /* Create a temporary DIR file. */
814 const char *nodename;
815 #ifndef HAVE_W32_SYSTEM
816 struct utsname utsbuf;
819 #ifdef HAVE_W32_SYSTEM
820 nodename = "unknown";
823 nodename = "unknown";
825 nodename = utsbuf.nodename;
828 gpgrt_asprintf (&tmpbuf, "DIR-tmp-%s-%u-%p.txt.tmp",
829 nodename, (unsigned int)getpid (), &tmpbuf);
832 err = gpg_error_from_errno (errno);
833 log_error (_("failed to create temporary cache dir file '%s': %s\n"),
834 tmpfname, strerror (errno));
837 for (p=tmpbuf; *p; p++)
840 tmpfname = make_filename (opt.homedir_cache, DBDIR_D, tmpbuf, NULL);
843 fpout = es_fopen (tmpfname, "w");
846 err = gpg_error_from_errno (errno);
847 log_error (_("failed to create temporary cache dir file '%s': %s\n"),
848 tmpfname, strerror (errno));
852 while ((line = next_line_from_file (fp, &lineerr)))
855 if (*line == 'c' || *line == 'u' || *line == 'i')
857 /* Extract the issuer hash field. */
860 fieldp = strchr (line, ':');
861 endp = fieldp? strchr (++fieldp, ':') : NULL;
864 /* There should be no percent within the issuer hash
865 field, thus we can compare it pretty easily. */
867 e = find_entry ( cache->entries, fieldp);
868 *endp = ':'; /* Restore original line. */
871 /* Marked for deletion, so don't write it. */
876 /* Yep, this is valid entry we know about; write it out */
877 write_dir_line_crl (fpout, e);
881 { /* We ignore entries we don't have in our cache
882 because they may have been added in the meantime
883 by other instances of dirmngr. */
884 es_fprintf (fpout, "# Next line added by "
885 "another process; our pid is %lu\n",
886 (unsigned long)getpid ());
887 es_fputs (line, fpout);
888 es_putc ('\n', fpout);
893 es_fputs ("# Invalid line detected: ", fpout);
894 es_fputs (line, fpout);
895 es_putc ('\n', fpout);
900 /* Write out all non CRL lines as they are. */
901 es_fputs (line, fpout);
902 es_putc ('\n', fpout);
907 if (!es_ferror (fp) && !es_ferror (fpout) && !lineerr)
909 /* Write out the remaining entries. */
910 for (e= cache->entries; e; e = e->next)
914 write_dir_line_crl (fpout, e);
921 log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
926 err = gpg_error_from_errno (errno);
927 log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
929 if (es_ferror (fpout))
931 err = gpg_error_from_errno (errno);
932 log_error (_("error writing '%s': %s\n"), tmpfname, strerror (errno));
937 /* Rename the files. */
940 if (es_fclose (fpout))
942 err = gpg_error_from_errno (errno);
943 log_error (_("error closing '%s': %s\n"), tmpfname, strerror (errno));
948 #ifdef HAVE_W32_SYSTEM
949 /* No atomic mv on W32 systems. */
950 gnupg_remove (fname);
952 if (rename (tmpfname, fname))
954 err = gpg_error_from_errno (errno);
955 log_error (_("error renaming '%s' to '%s': %s\n"),
956 tmpfname, fname, strerror (errno));
961 /* Fixme: Relinquish update lock. */
969 gnupg_remove (tmpfname);
978 /* Create the filename for the cache file from the 40 byte ISSUER_HASH
979 string. Caller must release the return string. */
981 make_db_file_name (const char *issuer_hash)
985 assert (strlen (issuer_hash) == 40);
986 memcpy (bname, "crl-", 4);
987 memcpy (bname + 4, issuer_hash, 40);
988 strcpy (bname + 44, ".db");
989 return make_filename (opt.homedir_cache, DBDIR_D, bname, NULL);
993 /* Hash the file FNAME and return the MD5 digest in MD5BUFFER. The
994 * caller must allocate MD5buffer with at least 16 bytes. Returns 0
997 hash_dbfile (const char *fname, unsigned char *md5buffer)
1005 buffer = xtrymalloc (65536);
1006 fp = buffer? es_fopen (fname, "rb") : NULL;
1009 log_error (_("can't hash '%s': %s\n"), fname, strerror (errno));
1014 err = gcry_md_open (&md5, GCRY_MD_MD5, 0);
1017 log_error (_("error setting up MD5 hash context: %s\n"),
1018 gpg_strerror (err));
1024 /* We better hash some information about the cache file layout in. */
1025 sprintf (buffer, "%.100s/%.100s:%d", DBDIR_D, DBDIRFILE, DBDIRVERSION);
1026 gcry_md_write (md5, buffer, strlen (buffer));
1030 n = es_fread (buffer, 1, 65536, fp);
1031 if (n < 65536 && es_ferror (fp))
1033 log_error (_("error hashing '%s': %s\n"), fname, strerror (errno));
1036 gcry_md_close (md5);
1041 gcry_md_write (md5, buffer, n);
1045 gcry_md_final (md5);
1047 memcpy (md5buffer, gcry_md_read (md5, GCRY_MD_MD5), 16);
1048 gcry_md_close (md5);
1052 /* Compare the file FNAME against the dexified MD5 hash MD5HASH and
1053 return 0 if they match. */
1055 check_dbfile (const char *fname, const char *md5hexvalue)
1057 unsigned char buffer1[16], buffer2[16];
1059 if (strlen (md5hexvalue) != 32)
1061 log_error (_("invalid formatted checksum for '%s'\n"), fname);
1064 unhexify (buffer1, md5hexvalue);
1066 if (hash_dbfile (fname, buffer2))
1069 return memcmp (buffer1, buffer2, 16);
1073 /* Open the cache file for ENTRY. This function implements a caching
1074 strategy and might close unused cache files. It is required to use
1075 unlock_db_file after using the file. */
1077 lock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
1082 crl_cache_entry_t e;
1086 entry->cdb_use_count++;
1090 for (open_count = 0, e = cache->entries; e; e = e->next)
1094 /* log_debug ("CACHE: cdb=%p use_count=%u lru_count=%u\n", */
1095 /* e->cdb,e->cdb_use_count,e->cdb_lru_count); */
1098 /* If there are too many file open, find the least recent used DB
1099 file and close it. Note that for Pth thread safeness we need to
1101 while (open_count >= MAX_OPEN_DB_FILES )
1103 crl_cache_entry_t last_e = NULL;
1104 unsigned int last_lru = (unsigned int)(-1);
1106 for (e = cache->entries; e; e = e->next)
1107 if (e->cdb && !e->cdb_use_count && e->cdb_lru_count < last_lru)
1109 last_lru = e->cdb_lru_count;
1114 log_error (_("too many open cache files; can't open anymore\n"));
1118 /* log_debug ("CACHE: closing file at cdb=%p\n", last_e->cdb); */
1120 fd = cdb_fileno (last_e->cdb);
1121 cdb_free (last_e->cdb);
1122 xfree (last_e->cdb);
1125 log_error (_("error closing cache file: %s\n"), strerror(errno));
1130 fname = make_db_file_name (entry->issuer_hash);
1132 log_info (_("opening cache file '%s'\n"), fname );
1134 if (!entry->dbfile_checked)
1136 if (!check_dbfile (fname, entry->dbfile_hash))
1137 entry->dbfile_checked = 1;
1138 /* Note, in case of an error we don't print an error here but
1139 let require the caller to do that check. */
1142 entry->cdb = xtrycalloc (1, sizeof *entry->cdb);
1148 fd = gnupg_open (fname, O_RDONLY | O_BINARY, 0);
1151 log_error (_("error opening cache file '%s': %s\n"),
1152 fname, strerror (errno));
1158 if (cdb_init (entry->cdb, fd))
1160 log_error (_("error initializing cache file '%s' for reading: %s\n"),
1161 fname, strerror (errno));
1170 entry->cdb_use_count = 1;
1171 entry->cdb_lru_count = 0;
1176 /* Unlock a cache file, so that it can be reused. */
1178 unlock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
1181 log_error (_("calling unlock_db_file on a closed file\n"));
1182 else if (!entry->cdb_use_count)
1183 log_error (_("calling unlock_db_file on an unlocked file\n"));
1186 entry->cdb_use_count--;
1187 entry->cdb_lru_count++;
1190 /* If the entry was marked for deletion in the meantime do it now.
1191 We do this for the sake of Pth thread safeness. */
1192 if (!entry->cdb_use_count && entry->deleted)
1194 crl_cache_entry_t eprev, enext;
1196 enext = entry->next;
1197 for (eprev = cache->entries;
1198 eprev && eprev->next != entry; eprev = eprev->next)
1201 if (eprev == cache->entries)
1202 cache->entries = enext;
1204 eprev->next = enext;
1205 /* FIXME: Do we leak ENTRY? */
1210 /* Find ISSUER_HASH in our cache FIRST. This may be used to enumerate
1211 the linked list we use to keep the CRLs of an issuer. */
1212 static crl_cache_entry_t
1213 find_entry (crl_cache_entry_t first, const char *issuer_hash)
1215 while (first && (first->deleted || strcmp (issuer_hash, first->issuer_hash)))
1216 first = first->next;
1221 /* Create a new CRL cache. This function is usually called only once.
1224 crl_cache_init(void)
1226 crl_cache_t cache = NULL;
1231 log_error ("crl cache has already been initialized - not doing twice\n");
1235 err = open_dir (&cache);
1237 log_fatal (_("failed to create a new cache object: %s\n"),
1238 gpg_strerror (err));
1239 current_cache = cache;
1243 /* Remove the cache information and all its resources. Note that we
1244 still keep the cache on disk. */
1246 crl_cache_deinit (void)
1250 release_cache (current_cache);
1251 current_cache = NULL;
1256 /* Delete the cache from disk and memory. Return 0 on success.*/
1258 crl_cache_flush (void)
1262 crl_cache_deinit ();
1263 rc = cleanup_cache_dir (0)? -1 : 0;
1270 /* Check whether the certificate identified by ISSUER_HASH and
1271 SN/SNLEN is valid; i.e. not listed in our cache. With
1272 FORCE_REFRESH set to true, a new CRL will be retrieved even if the
1273 cache has not yet expired. We use a 30 minutes threshold here so
1274 that invoking this function several times won't load the CRL over
1276 static crl_cache_result_t
1277 cache_isvalid (ctrl_t ctrl, const char *issuer_hash,
1278 const unsigned char *sn, size_t snlen,
1281 crl_cache_t cache = get_current_cache ();
1282 crl_cache_result_t retval;
1285 crl_cache_entry_t entry;
1286 gnupg_isotime_t current_time;
1291 entry = find_entry (cache->entries, issuer_hash);
1294 log_info (_("no CRL available for issuer id %s\n"), issuer_hash );
1295 return CRL_CACHE_DONTKNOW;
1298 gnupg_get_isotime (current_time);
1299 if (strcmp (entry->next_update, current_time) < 0 )
1301 log_info (_("cached CRL for issuer id %s too old; update required\n"),
1303 return CRL_CACHE_DONTKNOW;
1307 gnupg_isotime_t tmptime;
1309 if (*entry->last_refresh)
1311 gnupg_copy_time (tmptime, entry->last_refresh);
1312 add_seconds_to_isotime (tmptime, 30 * 60);
1313 if (strcmp (tmptime, current_time) < 0 )
1315 log_info (_("force-crl-refresh active and %d minutes passed for"
1316 " issuer id %s; update required\n"),
1318 return CRL_CACHE_DONTKNOW;
1323 log_info (_("force-crl-refresh active for"
1324 " issuer id %s; update required\n"),
1326 return CRL_CACHE_DONTKNOW;
1332 log_info (_("available CRL for issuer ID %s can't be used\n"),
1334 return CRL_CACHE_CANTUSE;
1337 cdb = lock_db_file (cache, entry);
1339 return CRL_CACHE_DONTKNOW; /* Hmmm, not the best error code. */
1341 if (!entry->dbfile_checked)
1343 log_error (_("cached CRL for issuer id %s tampered; we need to update\n")
1345 unlock_db_file (cache, entry);
1346 return CRL_CACHE_DONTKNOW;
1349 rc = cdb_find (cdb, sn, snlen);
1352 n = cdb_datalen (cdb);
1355 log_error (_("WARNING: invalid cache record length for S/N "));
1357 log_printhex (sn, snlen, "");
1359 else if (opt.verbose)
1361 unsigned char record[16];
1362 char *tmp = hexify_data (sn, snlen, 1);
1364 if (cdb_read (cdb, record, n, cdb_datapos (cdb)))
1365 log_error (_("problem reading cache record for S/N %s: %s\n"),
1366 tmp, strerror (errno));
1368 log_info (_("S/N %s is not valid; reason=%02X date=%.15s\n"),
1369 tmp, *record, record+1);
1372 retval = CRL_CACHE_INVALID;
1378 char *serialno = hexify_data (sn, snlen, 1);
1379 log_info (_("S/N %s is valid, it is not listed in the CRL\n"),
1383 retval = CRL_CACHE_VALID;
1387 log_error (_("error getting data from cache file: %s\n"),
1389 retval = CRL_CACHE_DONTKNOW;
1393 if (entry->user_trust_req
1394 && (retval == CRL_CACHE_VALID || retval == CRL_CACHE_INVALID))
1396 if (!entry->check_trust_anchor)
1398 log_error ("inconsistent data on user trust check\n");
1399 retval = CRL_CACHE_CANTUSE;
1401 else if (get_istrusted_from_client (ctrl, entry->check_trust_anchor))
1404 log_info ("no system trust and client does not trust either\n");
1405 retval = CRL_CACHE_NOTTRUSTED;
1409 /* Okay, the CRL is considered valid by the client and thus
1410 we can return the result as is. */
1414 unlock_db_file (cache, entry);
1420 /* Check whether the certificate identified by ISSUER_HASH and
1421 SERIALNO is valid; i.e. not listed in our cache. With
1422 FORCE_REFRESH set to true, a new CRL will be retrieved even if the
1423 cache has not yet expired. We use a 30 minutes threshold here so
1424 that invoking this function several times won't load the CRL over
1427 crl_cache_isvalid (ctrl_t ctrl, const char *issuer_hash, const char *serialno,
1430 crl_cache_result_t result;
1431 unsigned char snbuf_buffer[50];
1432 unsigned char *snbuf;
1435 n = strlen (serialno)/2+1;
1436 if (n < sizeof snbuf_buffer - 1)
1437 snbuf = snbuf_buffer;
1440 snbuf = xtrymalloc (n);
1442 return CRL_CACHE_DONTKNOW;
1445 n = unhexify (snbuf, serialno);
1447 result = cache_isvalid (ctrl, issuer_hash, snbuf, n, force_refresh);
1449 if (snbuf != snbuf_buffer)
1456 /* Check whether the certificate CERT is valid; i.e. not listed in our
1457 cache. With FORCE_REFRESH set to true, a new CRL will be retrieved
1458 even if the cache has not yet expired. We use a 30 minutes
1459 threshold here so that invoking this function several times won't
1460 load the CRL over and over. */
1462 crl_cache_cert_isvalid (ctrl_t ctrl, ksba_cert_t cert,
1466 crl_cache_result_t result;
1467 unsigned char issuerhash[20];
1468 char issuerhash_hex[41];
1475 /* Compute the hash value of the issuer name. */
1476 tmp = ksba_cert_get_issuer (cert, 0);
1479 log_error ("oops: issuer missing in certificate\n");
1480 return gpg_error (GPG_ERR_INV_CERT_OBJ);
1482 gcry_md_hash_buffer (GCRY_MD_SHA1, issuerhash, tmp, strlen (tmp));
1484 for (i=0,tmp=issuerhash_hex; i < 20; i++, tmp += 2)
1485 sprintf (tmp, "%02X", issuerhash[i]);
1487 /* Get the serial number. */
1488 serial = ksba_cert_get_serial (cert);
1491 log_error ("oops: S/N missing in certificate\n");
1492 return gpg_error (GPG_ERR_INV_CERT_OBJ);
1497 log_error ("oops: invalid S/N\n");
1499 return gpg_error (GPG_ERR_INV_CERT_OBJ);
1502 snlen = strtoul (sn, &endp, 10);
1506 log_error ("oops: invalid S/N\n");
1508 return gpg_error (GPG_ERR_INV_CERT_OBJ);
1512 /* Check the cache. */
1513 result = cache_isvalid (ctrl, issuerhash_hex, sn, snlen, force_refresh);
1516 case CRL_CACHE_VALID:
1519 case CRL_CACHE_INVALID:
1520 err = gpg_error (GPG_ERR_CERT_REVOKED);
1522 case CRL_CACHE_DONTKNOW:
1523 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1525 case CRL_CACHE_NOTTRUSTED:
1526 err = gpg_error (GPG_ERR_NOT_TRUSTED);
1528 case CRL_CACHE_CANTUSE:
1529 err = gpg_error (GPG_ERR_INV_CRL_OBJ);
1532 log_fatal ("cache_isvalid returned invalid status code %d\n", result);
1540 /* Return the hash algorithm's algo id from its name given in the
1541 * non-null termnated string in (buffer,buflen). Returns 0 on failure
1542 * or if the algo is not known. */
1544 hash_algo_from_buffer (const void *buffer, size_t buflen)
1549 string = xtrymalloc (buflen + 1);
1552 log_error (_("out of core\n"));
1555 memcpy (string, buffer, buflen);
1557 algo = gcry_md_map_name (string);
1559 log_error ("unknown digest algorithm '%s' used in certificate\n", string);
1565 /* Return an unsigned integer from the non-null termnated string
1566 * (buffer,buflen). Returns 0 on failure. */
1568 uint_from_buffer (const void *buffer, size_t buflen)
1573 string = xtrymalloc (buflen + 1);
1576 log_error (_("out of core\n"));
1579 memcpy (string, buffer, buflen);
1581 val = strtoul (string, NULL, 10);
1587 /* Prepare a hash context for the signature verification. Input is
1588 the CRL and the output is the hash context MD as well as the uses
1589 algorithm identifier ALGO. */
1591 start_sig_check (ksba_crl_t crl, gcry_md_hd_t *md, int *algo, int *use_pss)
1597 algoid = ksba_crl_get_digest_algo (crl);
1598 if (algoid && !strcmp (algoid, "1.2.840.113549.1.1.10"))
1600 /* Parse rsaPSS parameter. */
1601 gcry_buffer_t ioarray[1] = { {0} };
1602 ksba_sexp_t pssparam;
1604 gcry_sexp_t psssexp;
1606 pssparam = ksba_crl_get_sig_val (crl);
1607 n = gcry_sexp_canon_len (pssparam, 0, NULL, NULL);
1610 ksba_free (pssparam);
1611 log_error (_("got an invalid S-expression from libksba\n"));
1612 return gpg_error (GPG_ERR_INV_SEXP);
1614 err = gcry_sexp_sscan (&psssexp, NULL, pssparam, n);
1615 ksba_free (pssparam);
1618 log_error (_("converting S-expression failed: %s\n"),
1619 gcry_strerror (err));
1623 err = gcry_sexp_extract_param (psssexp, "sig-val",
1624 "&'hash-algo'", ioarray, NULL);
1625 gcry_sexp_release (psssexp);
1628 log_error ("extracting params from PSS failed: %s\n",
1629 gpg_strerror (err));
1632 *algo = hash_algo_from_buffer (ioarray[0].data, ioarray[0].len);
1633 xfree (ioarray[0].data);
1637 *algo = gcry_md_map_name (algoid);
1640 log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?");
1641 return gpg_error (GPG_ERR_DIGEST_ALGO);
1644 err = gcry_md_open (md, *algo, 0);
1647 log_error (_("gcry_md_open for algorithm %d failed: %s\n"),
1648 *algo, gcry_strerror (err));
1652 gcry_md_debug (*md, "hash.cert");
1654 ksba_crl_set_hash_function (crl, HASH_FNC, *md);
1659 /* Finish a hash context and verify the signature. This function
1660 should return 0 on a good signature, GPG_ERR_BAD_SIGNATURE if the
1661 signature does not verify or any other error code. CRL is the CRL
1662 object we are working on, MD the hash context and ISSUER_CERT the
1663 certificate of the CRL issuer. This function takes ownership of MD. */
1665 finish_sig_check (ksba_crl_t crl, gcry_md_hd_t md, int algo,
1666 ksba_cert_t issuer_cert, int use_pss)
1669 ksba_sexp_t sigval = NULL, pubkey = NULL;
1671 gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
1672 unsigned int saltlen = 0; /* (used only with use_pss) */
1675 /* This also stops debugging on the MD. */
1678 /* Get and convert the signature value. */
1679 sigval = ksba_crl_get_sig_val (crl);
1680 n = gcry_sexp_canon_len (sigval, 0, NULL, NULL);
1683 log_error (_("got an invalid S-expression from libksba\n"));
1684 err = gpg_error (GPG_ERR_INV_SEXP);
1687 err = gcry_sexp_sscan (&s_sig, NULL, sigval, n);
1690 log_error (_("converting S-expression failed: %s\n"),
1691 gcry_strerror (err));
1697 /* Parse rsaPSS parameter which we should find in S_SIG. */
1698 gcry_buffer_t ioarray[2] = { {0}, {0} };
1699 ksba_sexp_t pssparam;
1700 gcry_sexp_t psssexp;
1703 pssparam = ksba_crl_get_sig_val (crl);
1704 n = gcry_sexp_canon_len (pssparam, 0, NULL, NULL);
1707 ksba_free (pssparam);
1708 log_error (_("got an invalid S-expression from libksba\n"));
1709 err = gpg_error (GPG_ERR_INV_SEXP);
1712 err = gcry_sexp_sscan (&psssexp, NULL, pssparam, n);
1713 ksba_free (pssparam);
1716 log_error (_("converting S-expression failed: %s\n"),
1717 gcry_strerror (err));
1721 err = gcry_sexp_extract_param (psssexp, "sig-val",
1722 "&'hash-algo''salt-length'",
1723 ioarray+0, ioarray+1, NULL);
1724 gcry_sexp_release (psssexp);
1727 log_error ("extracting params from PSS failed: %s\n",
1728 gpg_strerror (err));
1731 hashalgo = hash_algo_from_buffer (ioarray[0].data, ioarray[0].len);
1732 saltlen = uint_from_buffer (ioarray[1].data, ioarray[1].len);
1733 xfree (ioarray[0].data);
1734 xfree (ioarray[1].data);
1735 if (hashalgo != algo)
1737 log_error ("hash algo mismatch: %d announced but %d used\n",
1739 err = gpg_error (GPG_ERR_INV_CRL);
1742 /* Add some restrictions; see ../sm/certcheck.c for details. */
1746 case GCRY_MD_SHA256:
1747 case GCRY_MD_SHA384:
1748 case GCRY_MD_SHA512:
1749 case GCRY_MD_SHA3_256:
1750 case GCRY_MD_SHA3_384:
1751 case GCRY_MD_SHA3_512:
1754 log_error ("PSS hash algorithm '%s' rejected\n",
1755 gcry_md_algo_name (algo));
1756 err = gpg_error (GPG_ERR_DIGEST_ALGO);
1760 if (gcry_md_get_algo_dlen (algo) != saltlen)
1762 log_error ("PSS hash algorithm '%s' rejected due to salt length %u\n",
1763 gcry_md_algo_name (algo), saltlen);
1764 err = gpg_error (GPG_ERR_DIGEST_ALGO);
1770 /* Get and convert the public key for the issuer certificate. */
1772 dump_cert ("crl_issuer_cert", issuer_cert);
1773 pubkey = ksba_cert_get_public_key (issuer_cert);
1774 n = gcry_sexp_canon_len (pubkey, 0, NULL, NULL);
1777 log_error (_("got an invalid S-expression from libksba\n"));
1778 err = gpg_error (GPG_ERR_INV_SEXP);
1781 err = gcry_sexp_sscan (&s_pkey, NULL, pubkey, n);
1784 log_error (_("converting S-expression failed: %s\n"),
1785 gcry_strerror (err));
1789 /* Create an S-expression with the actual hash value. */
1792 err = gcry_sexp_build (&s_hash, NULL,
1795 "(salt-length %u))",
1796 hash_algo_to_string (algo),
1797 (int)gcry_md_get_algo_dlen (algo),
1798 gcry_md_read (md, algo),
1801 else if ((pkalgo = pk_algo_from_sexp (s_pkey)) == GCRY_PK_ECC)
1803 unsigned int qbits0, qbits;
1805 qbits0 = gcry_pk_get_nbits (s_pkey);
1806 qbits = qbits0 == 521? 512 : qbits0;
1810 log_error ("ECDSA requires the hash length to be a"
1811 " multiple of 8 bits\n");
1812 err = gpg_error (GPG_ERR_INTERNAL);
1816 /* Don't allow any Q smaller than 160 bits. */
1819 log_error (_("%s key uses an unsafe (%u bit) hash\n"),
1820 gcry_pk_algo_name (pkalgo), qbits0);
1821 err = gpg_error (GPG_ERR_INTERNAL);
1825 /* Check if we're too short. */
1826 n = gcry_md_get_algo_dlen (algo);
1829 log_error (_("a %u bit hash is not valid for a %u bit %s key\n"),
1832 gcry_pk_algo_name (pkalgo));
1835 err = gpg_error (GPG_ERR_INTERNAL);
1844 err = gcry_sexp_build (&s_hash, NULL, "(data(flags raw)(value %b))",
1846 gcry_md_read (md, algo));
1851 err = gcry_sexp_build (&s_hash, NULL,
1852 "(data(flags pkcs1)(hash %s %b))",
1853 hash_algo_to_string (algo),
1854 (int)gcry_md_get_algo_dlen (algo),
1855 gcry_md_read (md, algo));
1859 log_error (_("creating S-expression failed: %s\n"), gcry_strerror (err));
1863 /* Pass this on to the signature verification. */
1864 err = gcry_pk_verify (s_sig, s_hash, s_pkey);
1866 log_debug ("%s: gcry_pk_verify: %s\n", __func__, gpg_strerror (err));
1871 gcry_sexp_release (s_sig);
1872 gcry_sexp_release (s_hash);
1873 gcry_sexp_release (s_pkey);
1880 /* Call this to match a start_sig_check that can not be completed
1881 normally. Takes ownership of MD if MD is not NULL. */
1883 abort_sig_check (ksba_crl_t crl, gcry_md_hd_t md)
1891 /* Workhorse of the CRL loading machinery. The CRL is read using the
1892 CRL object and stored in the data base file DB with the name FNAME
1893 (only used for printing error messages). That DB should be a
1894 temporary one and not the actual one. If the function fails the
1895 caller should delete this temporary database file. CTRL is
1896 required to retrieve certificates using the general dirmngr
1897 callback service. R_CRLISSUER returns an allocated string with the
1898 crl-issuer DN, THIS_UPDATE and NEXT_UPDATE are filled with the
1899 corresponding data from the CRL. Note that these values might get
1900 set even if the CRL processing fails at a later step; thus the
1901 caller should free *R_ISSUER even if the function returns with an
1902 error. R_TRUST_ANCHOR is set on exit to NULL or a string with the
1903 hexified fingerprint of the root certificate, if checking this
1904 certificate for trustiness is required.
1907 crl_parse_insert (ctrl_t ctrl, ksba_crl_t crl,
1908 struct cdb_make *cdb, const char *fname,
1910 ksba_isotime_t thisupdate, ksba_isotime_t nextupdate,
1911 char **r_trust_anchor)
1914 ksba_stop_reason_t stopreason;
1915 ksba_cert_t crlissuer_cert = NULL;
1916 gcry_md_hd_t md = NULL;
1923 *r_crlissuer = NULL;
1924 *thisupdate = *nextupdate = 0;
1925 *r_trust_anchor = NULL;
1927 /* Start of the KSBA parser loop. */
1930 err = ksba_crl_parse (crl, &stopreason);
1933 log_error (_("ksba_crl_parse failed: %s\n"), gpg_strerror (err) );
1939 case KSBA_SR_BEGIN_ITEMS:
1941 err = start_sig_check (crl, &md, &algo, &use_pss);
1945 err = ksba_crl_get_update_times (crl, thisupdate, nextupdate);
1948 log_error (_("error getting update times of CRL: %s\n"),
1949 gpg_strerror (err));
1950 err = gpg_error (GPG_ERR_INV_CRL);
1954 if (opt.verbose || !*nextupdate)
1955 log_info (_("update times of this CRL: this=%s next=%s\n"),
1956 thisupdate, nextupdate);
1959 log_info (_("nextUpdate not given; "
1960 "assuming a validity period of one day\n"));
1961 gnupg_copy_time (nextupdate, thisupdate);
1962 add_seconds_to_isotime (nextupdate, 86400);
1967 case KSBA_SR_GOT_ITEM:
1970 const unsigned char *p;
1971 ksba_isotime_t rdate;
1972 ksba_crl_reason_t reason;
1974 unsigned char record[1+15];
1976 err = ksba_crl_get_item (crl, &serial, rdate, &reason);
1979 log_error (_("error getting CRL item: %s\n"),
1980 gpg_strerror (err));
1981 err = gpg_error (GPG_ERR_INV_CRL);
1985 p = serial_to_buffer (serial, &n);
1988 record[0] = (reason & 0xff);
1989 memcpy (record+1, rdate, 15);
1990 rc = cdb_make_add (cdb, p, n, record, 1+15);
1993 err = gpg_error_from_errno (errno);
1994 log_error (_("error inserting item into "
1995 "temporary cache file: %s\n"),
2004 case KSBA_SR_END_ITEMS:
2011 ksba_sexp_t authidsn;
2014 /* We need to look for the issuer only after having read
2015 all items. The issuer itself comes before the items
2016 but the optional authorityKeyIdentifier comes after the
2018 err = ksba_crl_get_issuer (crl, &crlissuer);
2021 log_error (_("no CRL issuer found in CRL: %s\n"),
2022 gpg_strerror (err) );
2023 err = gpg_error (GPG_ERR_INV_CRL);
2026 /* Note: This should be released by ksba_free, not xfree.
2027 May need a memory reallocation dance. */
2028 *r_crlissuer = crlissuer; /* (Do it here so we don't need
2029 to free it later) */
2031 if (!ksba_crl_get_auth_key_id (crl, &keyid, &authid, &authidsn))
2036 log_info (_("locating CRL issuer certificate by "
2037 "authorityKeyIdentifier\n"));
2039 s = ksba_name_enum (authid, 0);
2041 crlissuer_cert = find_cert_bysn (ctrl, s, authidsn);
2042 if (!crlissuer_cert && keyid)
2043 crlissuer_cert = find_cert_bysubject (ctrl,
2046 if (!crlissuer_cert)
2048 log_info ("CRL issuer certificate ");
2052 dump_serial (keyid);
2058 dump_serial (authidsn);
2063 log_printf ("not found\n");
2065 ksba_name_release (authid);
2070 crlissuer_cert = find_cert_bysubject (ctrl, crlissuer, NULL);
2072 if (!crlissuer_cert)
2074 err = gpg_error (GPG_ERR_MISSING_CERT);
2078 err = finish_sig_check (crl, md, algo, crlissuer_cert, use_pss);
2079 md = NULL; /* Closed. */
2082 log_error (_("CRL signature verification failed: %s\n"),
2083 gpg_strerror (err));
2087 err = validate_cert_chain (ctrl, crlissuer_cert, NULL,
2088 (VALIDATE_FLAG_TRUST_CONFIG
2090 | VALIDATE_FLAG_RECURSIVE),
2094 log_error (_("error checking validity of CRL "
2095 "issuer certificate: %s\n"),
2096 gpg_strerror (err));
2104 log_debug ("crl_parse_insert: unknown stop reason\n");
2105 err = gpg_error (GPG_ERR_BUG);
2109 while (stopreason != KSBA_SR_READY);
2114 abort_sig_check (crl, md);
2115 ksba_cert_release (crlissuer_cert);
2121 /* Return the crlNumber extension as an allocated hex string or NULL
2122 if there is none. */
2124 get_crl_number (ksba_crl_t crl)
2130 err = ksba_crl_get_crl_number (crl, &number);
2133 string = serial_hex (number);
2139 /* Return the authorityKeyIdentifier or NULL if it is not available.
2140 The issuer name may consists of several parts - they are delimited by
2143 get_auth_key_id (ksba_crl_t crl, char **serialno)
2154 err = ksba_crl_get_auth_key_id (crl, NULL, &name, &sn);
2157 *serialno = serial_hex (sn);
2161 return xstrdup ("");
2164 for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
2166 char *p = ksba_name_get_uri (name, idx);
2167 length += strlen (p?p:s) + 1;
2170 string = xtrymalloc (length+1);
2174 for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
2176 char *p = ksba_name_get_uri (name, idx);
2178 strcat (string, "\x01");
2179 strcat (string, p?p:s);
2183 ksba_name_release (name);
2189 /* Insert the CRL retrieved using URL into the cache specified by
2190 CACHE. The CRL itself will be read from the stream FP and is
2191 expected in binary format.
2197 crl_cache_reload_crl
2205 crl_cache_insert (ctrl_t ctrl, const char *url, ksba_reader_t reader)
2207 crl_cache_t cache = get_current_cache ();
2208 gpg_error_t err, err2;
2211 char *newfname = NULL;
2212 struct cdb_make cdb;
2214 char *issuer = NULL;
2215 char *issuer_hash = NULL;
2216 ksba_isotime_t thisupdate, nextupdate;
2217 crl_cache_entry_t entry = NULL;
2218 crl_cache_entry_t e;
2219 gnupg_isotime_t current_time;
2220 char *checksum = NULL;
2221 int invalidate_crl = 0;
2225 char *trust_anchor = NULL;
2227 /* FIXME: We should acquire a mutex for the URL, so that we don't
2228 simultaneously enter the same CRL twice. However this needs to be
2229 interweaved with the checking function.*/
2233 err = ksba_crl_new (&crl);
2236 log_error (_("ksba_crl_new failed: %s\n"), gpg_strerror (err));
2240 err = ksba_crl_set_reader (crl, reader);
2243 log_error (_("ksba_crl_set_reader failed: %s\n"), gpg_strerror (err));
2247 /* Create a temporary cache file to load the CRL into. */
2250 const char *nodename;
2251 #ifndef HAVE_W32_SYSTEM
2252 struct utsname utsbuf;
2255 #ifdef HAVE_W32_SYSTEM
2256 nodename = "unknown";
2258 if (uname (&utsbuf))
2259 nodename = "unknown";
2261 nodename = utsbuf.nodename;
2264 gpgrt_asprintf (&tmpfname, "crl-tmp-%s-%u-%p.db.tmp",
2265 nodename, (unsigned int)getpid (), &tmpfname);
2268 err = gpg_error_from_syserror ();
2271 for (p=tmpfname; *p; p++)
2274 fname = make_filename (opt.homedir_cache, DBDIR_D, tmpfname, NULL);
2276 if (!gnupg_remove (fname))
2277 log_info (_("removed stale temporary cache file '%s'\n"), fname);
2278 else if (errno != ENOENT)
2280 err = gpg_error_from_syserror ();
2281 log_error (_("problem removing stale temporary cache file '%s': %s\n"),
2282 fname, gpg_strerror (err));
2287 fd_cdb = gnupg_open (fname, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2290 err = gpg_error_from_errno (errno);
2291 log_error (_("error creating temporary cache file '%s': %s\n"),
2292 fname, strerror (errno));
2295 cdb_make_start(&cdb, fd_cdb);
2297 err = crl_parse_insert (ctrl, crl, &cdb, fname,
2298 &issuer, thisupdate, nextupdate, &trust_anchor);
2301 log_error (_("crl_parse_insert failed: %s\n"), gpg_strerror (err));
2302 /* Error in cleanup ignored. */
2303 cdb_make_finish (&cdb);
2307 /* Finish the database. */
2308 if (cdb_make_finish (&cdb))
2310 err = gpg_error_from_errno (errno);
2311 log_error (_("error finishing temporary cache file '%s': %s\n"),
2312 fname, strerror (errno));
2317 err = gpg_error_from_errno (errno);
2318 log_error (_("error closing temporary cache file '%s': %s\n"),
2319 fname, strerror (errno));
2325 /* Create a checksum. */
2327 unsigned char md5buf[16];
2329 if (hash_dbfile (fname, md5buf))
2331 err = gpg_error (GPG_ERR_CHECKSUM);
2334 checksum = hexify_data (md5buf, 16, 0);
2338 /* Check whether that new CRL is still not expired. */
2339 gnupg_get_isotime (current_time);
2340 if (strcmp (nextupdate, current_time) < 0 )
2343 log_info (_("WARNING: new CRL still too old; it expired on %s "
2344 "- loading anyway\n"), nextupdate);
2347 log_error (_("new CRL still too old; it expired on %s\n"),
2350 err2 = gpg_error (GPG_ERR_CRL_TOO_OLD);
2351 invalidate_crl |= INVCRL_TOO_OLD;
2355 /* Check for unknown critical extensions. */
2356 for (idx=0; !(err=ksba_crl_get_extension (crl, idx, &oid, &critical,
2357 NULL, NULL)); idx++)
2362 || !strcmp (oid, oidstr_authorityKeyIdentifier)
2363 || !strcmp (oid, oidstr_crlNumber) )
2366 for (sl=opt.ignored_crl_extensions;
2367 sl && strcmp (sl->d, oid); sl = sl->next)
2370 continue; /* Is in ignored list. */
2372 log_error (_("unknown critical CRL extension %s\n"), oid);
2373 log_info ("(CRL='%s')\n", url);
2375 err2 = gpg_error (GPG_ERR_INV_CRL);
2376 invalidate_crl |= INVCRL_UNKNOWN_EXTN;
2378 if (gpg_err_code (err) == GPG_ERR_EOF
2379 || gpg_err_code (err) == GPG_ERR_NO_DATA )
2383 log_error (_("error reading CRL extensions: %s\n"), gpg_strerror (err));
2384 err = gpg_error (GPG_ERR_INV_CRL);
2388 /* Create an hex encoded SHA-1 hash of the issuer DN to be
2389 used as the key for the cache. */
2390 issuer_hash = hashify_data (issuer, strlen (issuer));
2392 /* Create an ENTRY. */
2393 entry = xtrycalloc (1, sizeof *entry);
2396 err = gpg_error_from_syserror ();
2399 entry->release_ptr = xtrymalloc (strlen (issuer_hash) + 1
2400 + strlen (issuer) + 1
2402 + strlen (checksum) + 1);
2403 if (!entry->release_ptr)
2405 err = gpg_error_from_syserror ();
2410 entry->issuer_hash = entry->release_ptr;
2411 entry->issuer = stpcpy (entry->issuer_hash, issuer_hash) + 1;
2412 entry->url = stpcpy (entry->issuer, issuer) + 1;
2413 entry->dbfile_hash = stpcpy (entry->url, url) + 1;
2414 strcpy (entry->dbfile_hash, checksum);
2415 gnupg_copy_time (entry->this_update, thisupdate);
2416 gnupg_copy_time (entry->next_update, nextupdate);
2417 gnupg_copy_time (entry->last_refresh, current_time);
2418 entry->crl_number = get_crl_number (crl);
2419 entry->authority_issuer = get_auth_key_id (crl, &entry->authority_serialno);
2420 entry->invalid = invalidate_crl;
2421 entry->user_trust_req = !!trust_anchor;
2422 entry->check_trust_anchor = trust_anchor;
2423 trust_anchor = NULL;
2425 /* Check whether we already have an entry for this issuer and mark
2426 it as deleted. We better use a loop, just in case duplicates got
2427 somehow into the list. */
2428 for (e = cache->entries; (e=find_entry (e, entry->issuer_hash)); e = e->next)
2431 /* Rename the temporary DB to the real name. */
2432 newfname = make_db_file_name (entry->issuer_hash);
2434 log_info (_("creating cache file '%s'\n"), newfname);
2436 /* Just in case close unused matching files. Actually we need this
2437 only under Windows but saving file descriptors is never bad. */
2443 for (e = cache->entries; e; e = e->next)
2444 if (!e->cdb_use_count && e->cdb
2445 && !strcmp (e->issuer_hash, entry->issuer_hash))
2447 int fd = cdb_fileno (e->cdb);
2452 log_error (_("error closing cache file: %s\n"),
2460 #ifdef HAVE_W32_SYSTEM
2461 gnupg_remove (newfname);
2463 if (rename (fname, newfname))
2465 err = gpg_error_from_syserror ();
2466 log_error (_("problem renaming '%s' to '%s': %s\n"),
2467 fname, newfname, gpg_strerror (err));
2470 xfree (fname); fname = NULL; /*(let the cleanup code not try to remove it)*/
2472 /* Link the new entry in. */
2473 entry->next = cache->entries;
2474 cache->entries = entry;
2477 err = update_dir (cache);
2480 log_error (_("updating the DIR file failed - "
2481 "cache entry will get lost with the next program start\n"));
2482 err = 0; /* Keep on running. */
2487 release_one_cache_entry (entry);
2492 gnupg_remove (fname);
2496 ksba_crl_release (crl);
2498 xfree (issuer_hash);
2500 xfree (trust_anchor);
2501 return err ? err : err2;
2505 /* Print one cached entry E in a human readable format to stream
2506 FP. Return 0 on success. */
2508 list_one_crl_entry (crl_cache_t cache, crl_cache_entry_t e, estream_t fp)
2510 struct cdb_find cdbfp;
2514 const unsigned char *s;
2515 unsigned int invalid;
2517 es_fputs ("--------------------------------------------------------\n", fp );
2518 es_fprintf (fp, _("Begin CRL dump (retrieved via %s)\n"), e->url );
2519 es_fprintf (fp, " Issuer:\t%s\n", e->issuer );
2520 es_fprintf (fp, " Issuer Hash:\t%s\n", e->issuer_hash );
2521 es_fprintf (fp, " This Update:\t%s\n", e->this_update );
2522 es_fprintf (fp, " Next Update:\t%s\n", e->next_update );
2523 es_fprintf (fp, " CRL Number :\t%s\n", e->crl_number? e->crl_number: "none");
2524 es_fprintf (fp, " AuthKeyId :\t%s\n",
2525 e->authority_serialno? e->authority_serialno:"none");
2526 if (e->authority_serialno && e->authority_issuer)
2528 es_fputs (" \t", fp);
2529 for (s=e->authority_issuer; *s; s++)
2531 es_fputs ("\n \t", fp);
2536 es_fprintf (fp, " Trust Check:\t%s\n",
2537 !e->user_trust_req? "[system]" :
2538 e->check_trust_anchor? e->check_trust_anchor:"[missing]");
2540 invalid = e->invalid;
2541 if ((invalid & INVCRL_TOO_OLD))
2543 invalid &= ~INVCRL_TOO_OLD;
2544 es_fprintf (fp, _(" ERROR: The CRL will not be used "
2545 "because it was still too old after an update!\n"));
2547 if ((invalid & INVCRL_UNKNOWN_EXTN))
2549 invalid &= ~INVCRL_UNKNOWN_EXTN;
2550 es_fprintf (fp, _(" ERROR: The CRL will not be used "
2551 "due to an unknown critical extension!\n"));
2553 if (invalid) /* INVCRL_GENERAL or some other bits are set. */
2554 es_fprintf (fp, _(" ERROR: The CRL will not be used\n"));
2556 cdb = lock_db_file (cache, e);
2558 return gpg_error (GPG_ERR_GENERAL);
2560 if (!e->dbfile_checked)
2561 es_fprintf (fp, _(" ERROR: This cached CRL may have been tampered with!\n"));
2565 rc = cdb_findinit (&cdbfp, cdb, NULL, 0);
2566 while (!rc && (rc=cdb_findnext (&cdbfp)) > 0 )
2568 unsigned char keyrecord[256];
2569 unsigned char record[16];
2576 n = cdb_datalen (cdb);
2579 log_error (_(" WARNING: invalid cache record length\n"));
2584 if (cdb_read (cdb, record, n, cdb_datapos (cdb)))
2586 log_error (_("problem reading cache record: %s\n"),
2592 n = cdb_keylen (cdb);
2593 if (n > sizeof keyrecord)
2594 n = sizeof keyrecord;
2595 if (cdb_read (cdb, keyrecord, n, cdb_keypos (cdb)))
2597 log_error (_("problem reading cache key: %s\n"), strerror (errno));
2604 for (i = 0; i < n; i++)
2605 es_fprintf (fp, "%02X", keyrecord[i]);
2606 es_fputs (":\t reasons( ", fp);
2608 if (reason & KSBA_CRLREASON_UNSPECIFIED)
2609 es_fputs( "unspecified ", fp ), any = 1;
2610 if (reason & KSBA_CRLREASON_KEY_COMPROMISE )
2611 es_fputs( "key_compromise ", fp ), any = 1;
2612 if (reason & KSBA_CRLREASON_CA_COMPROMISE )
2613 es_fputs( "ca_compromise ", fp ), any = 1;
2614 if (reason & KSBA_CRLREASON_AFFILIATION_CHANGED )
2615 es_fputs( "affiliation_changed ", fp ), any = 1;
2616 if (reason & KSBA_CRLREASON_SUPERSEDED )
2617 es_fputs( "superseded", fp ), any = 1;
2618 if (reason & KSBA_CRLREASON_CESSATION_OF_OPERATION )
2619 es_fputs( "cessation_of_operation", fp ), any = 1;
2620 if (reason & KSBA_CRLREASON_CERTIFICATE_HOLD )
2621 es_fputs( "certificate_hold", fp ), any = 1;
2623 es_fputs( "other", fp );
2625 es_fprintf (fp, ") rdate: %.15s\n", record+1);
2628 log_error (_("error reading cache entry from db: %s\n"), strerror (rc));
2630 unlock_db_file (cache, e);
2631 es_fprintf (fp, _("End CRL dump\n") );
2634 return (rc||warn)? gpg_error (GPG_ERR_GENERAL) : 0;
2638 /* Print the contents of the CRL CACHE in a human readable format to
2641 crl_cache_list (estream_t fp)
2643 crl_cache_t cache = get_current_cache ();
2644 crl_cache_entry_t entry;
2645 gpg_error_t err = 0;
2647 for (entry = cache->entries;
2648 entry && !entry->deleted && !err;
2649 entry = entry->next )
2650 err = list_one_crl_entry (cache, entry, fp);
2656 /* Load the CRL containing the file named FILENAME into our CRL cache. */
2658 crl_cache_load (ctrl_t ctrl, const char *filename)
2662 ksba_reader_t reader;
2664 fp = es_fopen (filename, "rb");
2667 err = gpg_error_from_errno (errno);
2668 log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2672 err = create_estream_ksba_reader (&reader, fp);
2675 err = crl_cache_insert (ctrl, filename, reader);
2676 ksba_reader_release (reader);
2683 /* Locate the corresponding CRL for the certificate CERT, read and
2684 verify the CRL and store it in the cache. */
2686 crl_cache_reload_crl (ctrl_t ctrl, ksba_cert_t cert)
2689 ksba_reader_t reader = NULL;
2690 char *issuer = NULL;
2691 ksba_name_t distpoint = NULL;
2692 ksba_name_t issuername = NULL;
2693 char *distpoint_uri = NULL;
2694 int any_dist_point = 0;
2696 gpg_error_t last_err = 0;
2698 /* Loop over all distribution points, get the CRLs and put them into
2701 log_info ("checking distribution points\n");
2703 while (xfree (distpoint), xfree (issuername),
2704 !(err = ksba_cert_get_crl_dist_point (cert, seq++,
2706 &issuername, NULL )))
2710 if (!distpoint && !issuername)
2713 log_info ("no issuer name and no distribution point\n");
2714 break; /* Not allowed; i.e. an invalid certificate. We give
2715 up here and hope that the default method returns a
2719 /* Get the URIs. We do this in a loop to iterate over all names
2721 for (name_seq=0; ksba_name_enum (distpoint, name_seq); name_seq++)
2723 xfree (distpoint_uri);
2724 distpoint_uri = ksba_name_get_uri (distpoint, name_seq);
2728 if (!strncmp (distpoint_uri, "ldap:", 5)
2729 || !strncmp (distpoint_uri, "ldaps:", 6))
2731 if (opt.ignore_ldap_dp)
2734 else if (!strncmp (distpoint_uri, "http:", 5)
2735 || !strncmp (distpoint_uri, "https:", 6))
2737 if (opt.ignore_http_dp)
2741 continue; /* Skip unknown schemes. */
2745 crl_close_reader (reader);
2746 err = crl_fetch (ctrl, distpoint_uri, &reader);
2749 log_error (_("crl_fetch via DP failed: %s\n"),
2750 gpg_strerror (err));
2752 continue; /* with the next name. */
2756 log_info ("inserting CRL (reader %p)\n", reader);
2757 err = crl_cache_insert (ctrl, distpoint_uri, reader);
2760 log_error (_("crl_cache_insert via DP failed: %s\n"),
2761 gpg_strerror (err));
2763 continue; /* with the next name. */
2765 goto leave; /* Ready - we got the CRL. */
2768 if (gpg_err_code (err) == GPG_ERR_EOF)
2770 if (!err && last_err)
2776 /* If we did not found any distpoint, try something reasonable. */
2777 if (!any_dist_point )
2780 log_info ("no distribution point - trying issuer name\n");
2782 issuer = ksba_cert_get_issuer (cert, 0);
2785 log_error ("oops: issuer missing in certificate\n");
2786 err = gpg_error (GPG_ERR_INV_CERT_OBJ);
2791 log_info ("fetching CRL from default location\n");
2792 crl_close_reader (reader);
2793 err = crl_fetch_default (ctrl, issuer, &reader);
2796 log_error ("crl_fetch via issuer failed: %s\n",
2797 gpg_strerror (err));
2802 log_info ("inserting CRL (reader %p)\n", reader);
2803 err = crl_cache_insert (ctrl, "default location(s)", reader);
2806 log_error (_("crl_cache_insert via issuer failed: %s\n"),
2807 gpg_strerror (err));
2813 crl_close_reader (reader);
2814 xfree (distpoint_uri);
2815 ksba_name_release (distpoint);
2816 ksba_name_release (issuername);