Imported Upstream version 2.4.3
[platform/upstream/gpg2.git] / dirmngr / crlcache.c
1 /* crlcache.c - LDAP access
2  * Copyright (C) 2002 Klarälvdalens Datakonsult AB
3  * Copyright (C) 2003, 2004, 2005, 2008 g10 Code GmbH
4  *
5  * This file is part of DirMngr.
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 /*
22
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").
28
29       The first field is a record type identifier, so that the file is
30       useful to keep track of other meta data too.
31
32       The name of the file is "DIR.txt".
33
34
35    1.1. Comment record
36
37         Field 1: Constant beginning with "#".
38
39         Other fields are not defined and such a record is simply
40         skipped during processing.
41
42    1.2. Version record
43
44         Field 1: Constant "v"
45         Field 2: Version number of this file.  Must be 1.
46
47         This record must be the first non-comment record and
48         there shall only exist one record of this type.
49
50    1.3. CRL cache record
51
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
55                  to be done.
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
60                  uppercase letters.
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'.
71
72    2. Layout of the standard CRL Cache DB file:
73
74       We use records of variable length with this structure
75
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.
82
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.
86
87
88 */
89
90 #include <config.h>
91
92 #include <stdio.h>
93 #include <stdlib.h>
94 #include <errno.h>
95 #include <string.h>
96 #include <sys/stat.h>
97 #include <assert.h>
98 #include <dirent.h>
99 #include <fcntl.h>
100 #include <unistd.h>
101 #ifndef HAVE_W32_SYSTEM
102 #include <sys/utsname.h>
103 #endif
104
105 #include "dirmngr.h"
106 #include "validate.h"
107 #include "certcache.h"
108 #include "crlcache.h"
109 #include "crlfetch.h"
110 #include "misc.h"
111 #include "cdb.h"
112
113 /* Change this whenever the format changes */
114 #define DBDIR_D "crls.d"
115 #define DBDIRFILE "DIR.txt"
116 #define DBDIRVERSION 1
117
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
123
124 #ifndef O_BINARY
125 # define O_BINARY 0
126 #endif
127
128
129 /* Reason flags for an invalid CRL.  */
130 #define INVCRL_TOO_OLD       1
131 #define INVCRL_UNKNOWN_EXTN  2
132 #define INVCRL_GENERAL       127
133
134
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";
138
139
140 /* Definition of one cached item. */
141 struct crl_cache_entry_s
142 {
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. */
158   char *crl_number;
159   char *authority_issuer;
160   char *authority_serialno;
161
162   struct cdb *cdb;             /* The cache file handle or NULL if not open. */
163
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. */
168 };
169
170
171 /* Definition of the entire cache object. */
172 struct crl_cache_s
173 {
174   crl_cache_entry_t entries;
175 };
176
177 typedef struct crl_cache_s *crl_cache_t;
178
179
180 /* Prototypes.  */
181 static crl_cache_entry_t find_entry (crl_cache_entry_t first,
182                                      const char *issuer_hash);
183
184
185
186 /* The currently loaded cache object.  This is usually initialized
187    right at startup.  */
188 static crl_cache_t current_cache;
189
190
191
192
193 \f
194 /* Return the current cache object or bail out if it is has not yet
195    been initialized.  */
196 static crl_cache_t
197 get_current_cache (void)
198 {
199   if (!current_cache)
200     log_fatal ("CRL cache has not yet been initialized\n");
201   return current_cache;
202 }
203
204
205 /*
206    Create ae directory if it does not yet exists.  Returns on
207    success, or -1 on error.
208  */
209 static int
210 create_directory_if_needed (const char *name)
211 {
212   gnupg_dir_t dir;
213   char *fname;
214
215   fname = make_filename (opt.homedir_cache, name, NULL);
216   dir = gnupg_opendir (fname);
217   if (!dir)
218     {
219       log_info (_("creating directory '%s'\n"), fname);
220       if (gnupg_mkdir (fname, "-rwx"))
221         {
222           int save_errno = errno;
223           log_error (_("error creating directory '%s': %s\n"),
224                      fname, strerror (errno));
225           xfree (fname);
226           gpg_err_set_errno (save_errno);
227           return -1;
228         }
229     }
230   else
231     gnupg_closedir (dir);
232   xfree (fname);
233   return 0;
234 }
235
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. */
239 static int
240 cleanup_cache_dir (int force)
241 {
242   char *dname = make_filename (opt.homedir_cache, DBDIR_D, NULL);
243   gnupg_dir_t dir;
244   gnupg_dirent_t de;
245   int problem = 0;
246
247   if (!force)
248     { /* Very minor sanity checks. */
249       if (!strcmp (dname, "~/") || !strcmp (dname, "/" ))
250         {
251           log_error (_("ignoring database dir '%s'\n"), dname);
252           xfree (dname);
253           return -1;
254         }
255     }
256
257   dir = gnupg_opendir (dname);
258   if (!dir)
259     {
260       log_error (_("error reading directory '%s': %s\n"),
261                  dname, strerror (errno));
262       xfree (dname);
263       return -1;
264     }
265
266   while ((de = gnupg_readdir (dir)))
267     {
268       if (strcmp (de->d_name, "." ) && strcmp (de->d_name, ".."))
269         {
270           char *cdbname = make_filename (dname, de->d_name, NULL);
271           int okay;
272           struct stat sbuf;
273
274           if (force)
275             okay = 1;
276           else
277             okay = (!gnupg_stat (cdbname, &sbuf) && S_ISREG (sbuf.st_mode));
278
279           if (okay)
280             {
281               log_info (_("removing cache file '%s'\n"), cdbname);
282               if (gnupg_remove (cdbname))
283                 {
284                   log_error ("failed to remove '%s': %s\n",
285                              cdbname, strerror (errno));
286                   problem = -1;
287                 }
288             }
289           else
290             log_info (_("not removing file '%s'\n"), cdbname);
291           xfree (cdbname);
292         }
293     }
294   xfree (dname);
295   gnupg_closedir (dir);
296   return problem;
297 }
298
299
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. */
305 static char *
306 next_line_from_file (estream_t fp, gpg_error_t *r_err)
307 {
308   char buf[300];
309   char *largebuf = NULL;
310   size_t buflen;
311   size_t len = 0;
312   unsigned char *p;
313   int c;
314   char *tmpbuf;
315
316   *r_err = 0;
317   p = buf;
318   buflen = sizeof buf - 1;
319   while ((c=es_getc (fp)) != EOF && c != '\n')
320     {
321       if (len >= buflen)
322         {
323           if (!largebuf)
324             {
325               buflen += 1024;
326               largebuf = xtrymalloc ( buflen + 1 );
327               if (!largebuf)
328                 {
329                   *r_err = gpg_error_from_syserror ();
330                   return NULL;
331                 }
332               memcpy (largebuf, buf, len);
333             }
334           else
335             {
336               buflen += 1024;
337               tmpbuf = xtryrealloc (largebuf, buflen + 1);
338               if (!tmpbuf)
339                 {
340                   *r_err = gpg_error_from_syserror ();
341                   xfree (largebuf);
342                   return NULL;
343                 }
344               largebuf = tmpbuf;
345             }
346           p = largebuf;
347         }
348       p[len++] = c;
349     }
350   if (c == EOF && !len)
351     return NULL;
352   p[len] = 0;
353
354   if (largebuf)
355     tmpbuf = xtryrealloc (largebuf, len+1);
356   else
357     tmpbuf = xtrystrdup (buf);
358   if (!tmpbuf)
359     {
360       *r_err = gpg_error_from_syserror ();
361       xfree (largebuf);
362     }
363   return tmpbuf;
364 }
365
366
367 /* Release one cache entry.  */
368 static void
369 release_one_cache_entry (crl_cache_entry_t entry)
370 {
371   if (entry)
372     {
373       if (entry->cdb)
374         {
375           int fd = cdb_fileno (entry->cdb);
376           cdb_free (entry->cdb);
377           xfree (entry->cdb);
378           if (close (fd))
379             log_error (_("error closing cache file: %s\n"), strerror(errno));
380         }
381       xfree (entry->release_ptr);
382       xfree (entry->check_trust_anchor);
383       xfree (entry);
384     }
385 }
386
387
388 /* Release the CACHE object. */
389 static void
390 release_cache (crl_cache_t cache)
391 {
392   crl_cache_entry_t entry, entry2;
393
394   if (!cache)
395     return;
396
397   for (entry = cache->entries; entry; entry = entry2)
398     {
399       entry2 = entry->next;
400       release_one_cache_entry (entry);
401     }
402   cache->entries = NULL;
403   xfree (cache);
404 }
405
406
407 /* Open the dir file FNAME or create a new one if it does not yet
408    exist. */
409 static estream_t
410 open_dir_file (const char *fname)
411 {
412   estream_t fp;
413
414   fp = es_fopen (fname, "r");
415   if (!fp)
416     {
417       log_error (_("failed to open cache dir file '%s': %s\n"),
418                  fname, strerror (errno));
419
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))
423         return NULL;
424       fp = es_fopen (fname, "w");
425       if (!fp)
426         {
427           log_error (_("error creating new cache dir file '%s': %s\n"),
428                      fname, strerror (errno));
429           return NULL;
430         }
431       es_fprintf (fp, "v:%d:\n", DBDIRVERSION);
432       if (es_ferror (fp))
433         {
434           log_error (_("error writing new cache dir file '%s': %s\n"),
435                      fname, strerror (errno));
436           es_fclose (fp);
437           return NULL;
438         }
439       if (es_fclose (fp))
440         {
441           log_error (_("error closing new cache dir file '%s': %s\n"),
442                      fname, strerror (errno));
443           return NULL;
444         }
445
446       log_info (_("new cache dir file '%s' created\n"), fname);
447
448       fp = es_fopen (fname, "r");
449       if (!fp)
450         {
451           log_error (_("failed to re-open cache dir file '%s': %s\n"),
452                      fname, strerror (errno));
453           return NULL;
454         }
455     }
456
457   return fp;
458 }
459
460 /* Helper for open_dir. */
461 static gpg_error_t
462 check_dir_version (estream_t *fpadr, const char *fname,
463                          unsigned int *lineno,
464                          int cleanup_on_mismatch)
465 {
466   char *line;
467   gpg_error_t lineerr = 0;
468   estream_t fp = *fpadr;
469   int created = 0;
470
471  retry:
472   while ((line = next_line_from_file (fp, &lineerr)))
473     {
474       ++*lineno;
475       if (*line == 'v' && line[1] == ':')
476         break;
477       else if (*line != '#')
478         {
479           log_error (_("first record of '%s' is not the version\n"), fname);
480           xfree (line);
481           return gpg_error (GPG_ERR_CONFIGURATION);
482         }
483       xfree (line);
484     }
485   if (lineerr)
486     return lineerr;
487
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)
491     {
492       if (!created && cleanup_on_mismatch)
493         {
494           log_error (_("old version of cache directory - cleaning up\n"));
495           es_fclose (fp);
496           *fpadr = NULL;
497           if (!cleanup_cache_dir (1))
498             {
499               *lineno = 0;
500               fp = *fpadr = open_dir_file (fname);
501               if (!fp)
502                 {
503                   xfree (line);
504                   return gpg_error (GPG_ERR_CONFIGURATION);
505                 }
506               created = 1;
507               goto retry;
508             }
509         }
510       log_error (_("old version of cache directory - giving up\n"));
511       xfree (line);
512       return gpg_error (GPG_ERR_CONFIGURATION);
513     }
514   xfree (line);
515   return 0;
516 }
517
518
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. */
524 static gpg_error_t
525 open_dir (crl_cache_t *r_cache)
526 {
527   crl_cache_t cache;
528   char *fname;
529   char *line = NULL;
530   gpg_error_t lineerr = 0;
531   estream_t fp;
532   crl_cache_entry_t entry, *entrytail;
533   unsigned int lineno;
534   gpg_error_t err = 0;
535   int anyerr = 0;
536
537   cache = xtrycalloc (1, sizeof *cache);
538   if (!cache)
539     return gpg_error_from_syserror ();
540
541   fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);
542
543   lineno = 0;
544   fp = open_dir_file (fname);
545   if (!fp)
546     {
547       err = gpg_error (GPG_ERR_CONFIGURATION);
548       goto leave;
549     }
550
551   err = check_dir_version (&fp, fname, &lineno, 1);
552   if (err)
553     goto leave;
554
555
556   /* Read in all supported entries from the dir file. */
557   cache->entries = NULL;
558   entrytail = &cache->entries;
559   xfree (line);
560   while ((line = next_line_from_file (fp, &lineerr)))
561     {
562       int fieldno;
563       char *p, *endp;
564
565       lineno++;
566       if ( *line == 'c' || *line == 'u' || *line == 'i' )
567         {
568           entry = xtrycalloc (1, sizeof *entry);
569           if (!entry)
570             {
571               err = gpg_error_from_syserror ();
572               goto leave;
573             }
574           entry->lineno = lineno;
575           entry->release_ptr = line;
576           if (*line == 'i')
577             {
578               entry->invalid = atoi (line+1);
579               if (!entry->invalid)
580                 entry->invalid = INVCRL_GENERAL;
581             }
582           else if (*line == 'u')
583             entry->user_trust_req = 1;
584
585           for (fieldno=1, p = line; p; p = endp, fieldno++)
586             {
587               endp = strchr (p, ':');
588               if (endp)
589                 *endp++ = '\0';
590
591               switch (fieldno)
592                 {
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;
597                 case 5:
598                   strncpy (entry->this_update, p, 15);
599                   entry->this_update[15] = 0;
600                   break;
601                 case 6:
602                   strncpy (entry->next_update, p, 15);
603                   entry->next_update[15] = 0;
604                   break;
605                 case 7: entry->dbfile_hash = p; break;
606                 case 8: if (*p) entry->crl_number = p; break;
607                 case 9:
608                   if (*p)
609                     entry->authority_issuer = unpercent_string (p);
610                   break;
611                 case 10:
612                   if (*p)
613                     entry->authority_serialno = unpercent_string (p);
614                   break;
615                 case 11:
616                   if (*p)
617                     entry->check_trust_anchor = xtrystrdup (p);
618                   break;
619                 default:
620                   if (*p)
621                     log_info (_("extra field detected in crl record of "
622                                 "'%s' line %u\n"), fname, lineno);
623                   break;
624                 }
625             }
626
627           if (!entry->issuer_hash)
628             {
629               log_info (_("invalid line detected in '%s' line %u\n"),
630                         fname, lineno);
631               xfree (entry);
632               entry = NULL;
633             }
634           else if (find_entry (cache->entries, entry->issuer_hash))
635             {
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"),
639                         fname, lineno);
640               xfree (entry);
641               entry = NULL;
642             }
643           else
644             {
645               line = NULL;
646               *entrytail = entry;
647               entrytail = &entry->next;
648             }
649         }
650       else if (*line == '#')
651         ;
652       else
653         log_info (_("unsupported record type in '%s' line %u skipped\n"),
654                   fname, lineno);
655
656       if (line)
657         xfree (line);
658     }
659   if (lineerr)
660     {
661       err = lineerr;
662       log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
663       goto leave;
664     }
665   if (es_ferror (fp))
666     {
667       log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
668       err = gpg_error (GPG_ERR_CONFIGURATION);
669       goto leave;
670     }
671
672   /* Now do some basic checks on the data. */
673   for (entry = cache->entries; entry; entry = entry->next)
674     {
675       assert (entry->lineno);
676       if (strlen (entry->issuer_hash) != 40)
677         {
678           anyerr++;
679           log_error (_("invalid issuer hash in '%s' line %u\n"),
680                      fname, entry->lineno);
681         }
682       else if ( !*entry->issuer )
683         {
684           anyerr++;
685           log_error (_("no issuer DN in '%s' line %u\n"),
686                      fname, entry->lineno);
687         }
688       else if ( check_isotime (entry->this_update)
689                 || check_isotime (entry->next_update))
690         {
691           anyerr++;
692           log_error (_("invalid timestamp in '%s' line %u\n"),
693                      fname, entry->lineno);
694         }
695
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);
700     }
701
702   if (anyerr)
703     {
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);
707     }
708
709
710  leave:
711   es_fclose (fp);
712   xfree (line);
713   xfree (fname);
714   if (err)
715     {
716       release_cache (cache);
717       cache = NULL;
718     }
719   *r_cache = cache;
720   return err;
721 }
722
723 static void
724 write_percented_string (const char *s, estream_t fp)
725 {
726   for (; *s; s++)
727     if (*s == ':')
728       es_fputs ("%3A", fp);
729     else if (*s == '\n')
730       es_fputs ("%0A", fp);
731     else if (*s == '\r')
732       es_fputs ("%0D", fp);
733     else
734       es_putc (*s, fp);
735 }
736
737
738 static void
739 write_dir_line_crl (estream_t fp, crl_cache_entry_t e)
740 {
741   if (e->invalid)
742     es_fprintf (fp, "i%d", e->invalid);
743   else if (e->user_trust_req)
744     es_putc ('u', fp);
745   else
746     es_putc ('c', fp);
747   es_putc (':', fp);
748   es_fputs (e->issuer_hash, fp);
749   es_putc (':', fp);
750   write_percented_string (e->issuer, fp);
751   es_putc (':', fp);
752   write_percented_string (e->url, fp);
753   es_putc (':', fp);
754   es_fwrite (e->this_update, 15, 1, fp);
755   es_putc (':', fp);
756   es_fwrite (e->next_update, 15, 1, fp);
757   es_putc (':', fp);
758   es_fputs (e->dbfile_hash, fp);
759   es_putc (':', fp);
760   if (e->crl_number)
761     es_fputs (e->crl_number, fp);
762   es_putc (':', fp);
763   if (e->authority_issuer)
764     write_percented_string (e->authority_issuer, fp);
765   es_putc (':', fp);
766   if (e->authority_serialno)
767     es_fputs (e->authority_serialno, fp);
768   es_putc (':', fp);
769   if (e->check_trust_anchor && e->user_trust_req)
770     es_fputs (e->check_trust_anchor, fp);
771   es_putc ('\n', fp);
772 }
773
774
775 /* Update the current dir file using the cache. */
776 static gpg_error_t
777 update_dir (crl_cache_t cache)
778 {
779   char *fname = NULL;
780   char *tmpfname = NULL;
781   char *line = NULL;
782   gpg_error_t lineerr = 0;
783   estream_t fp;
784   estream_t fpout = NULL;
785   crl_cache_entry_t e;
786   unsigned int lineno;
787   gpg_error_t err = 0;
788
789   fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);
790
791   /* Fixme: Take an update file lock here. */
792
793   for (e= cache->entries; e; e = e->next)
794     e->mark = 1;
795
796   lineno = 0;
797   fp = es_fopen (fname, "r");
798   if (!fp)
799     {
800       err = gpg_error_from_errno (errno);
801       log_error (_("failed to open cache dir file '%s': %s\n"),
802                  fname, strerror (errno));
803       goto leave;
804     }
805   err = check_dir_version (&fp, fname, &lineno, 0);
806   if (err)
807     goto leave;
808   es_rewind (fp);
809   lineno = 0;
810
811   /* Create a temporary DIR file. */
812   {
813     char *tmpbuf, *p;
814     const char *nodename;
815 #ifndef HAVE_W32_SYSTEM
816     struct utsname utsbuf;
817 #endif
818
819 #ifdef HAVE_W32_SYSTEM
820     nodename = "unknown";
821 #else
822     if (uname (&utsbuf))
823       nodename = "unknown";
824     else
825       nodename = utsbuf.nodename;
826 #endif
827
828     gpgrt_asprintf (&tmpbuf, "DIR-tmp-%s-%u-%p.txt.tmp",
829                     nodename, (unsigned int)getpid (), &tmpbuf);
830     if (!tmpbuf)
831       {
832         err = gpg_error_from_errno (errno);
833         log_error (_("failed to create temporary cache dir file '%s': %s\n"),
834                    tmpfname, strerror (errno));
835         goto leave;
836       }
837     for (p=tmpbuf; *p; p++)
838       if (*p == '/')
839         *p = '.';
840     tmpfname = make_filename (opt.homedir_cache, DBDIR_D, tmpbuf, NULL);
841     xfree (tmpbuf);
842   }
843   fpout = es_fopen (tmpfname, "w");
844   if (!fpout)
845     {
846       err = gpg_error_from_errno (errno);
847       log_error (_("failed to create temporary cache dir file '%s': %s\n"),
848                  tmpfname, strerror (errno));
849       goto leave;
850     }
851
852   while ((line = next_line_from_file (fp, &lineerr)))
853     {
854       lineno++;
855       if (*line == 'c' || *line == 'u' || *line == 'i')
856         {
857           /* Extract the issuer hash field. */
858           char *fieldp, *endp;
859
860           fieldp = strchr (line, ':');
861           endp = fieldp? strchr (++fieldp, ':') : NULL;
862           if (endp)
863             {
864               /* There should be no percent within the issuer hash
865                  field, thus we can compare it pretty easily. */
866               *endp = 0;
867               e = find_entry ( cache->entries, fieldp);
868               *endp = ':'; /* Restore original line. */
869               if (e && e->deleted)
870                 {
871                   /* Marked for deletion, so don't write it. */
872                   e->mark = 0;
873                 }
874               else if (e)
875                 {
876                   /* Yep, this is valid entry we know about; write it out */
877                   write_dir_line_crl (fpout, e);
878                   e->mark = 0;
879                 }
880               else
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);
889                 }
890             }
891           else
892             {
893               es_fputs ("# Invalid line detected: ", fpout);
894               es_fputs (line, fpout);
895               es_putc ('\n', fpout);
896             }
897         }
898       else
899         {
900           /* Write out all non CRL lines as they are. */
901           es_fputs (line, fpout);
902           es_putc ('\n', fpout);
903         }
904
905       xfree (line);
906     }
907   if (!es_ferror (fp) && !es_ferror (fpout) && !lineerr)
908     {
909       /* Write out the remaining entries. */
910       for (e= cache->entries; e; e = e->next)
911         if (e->mark)
912           {
913             if (!e->deleted)
914               write_dir_line_crl (fpout, e);
915             e->mark = 0;
916           }
917     }
918   if (lineerr)
919     {
920       err = lineerr;
921       log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
922       goto leave;
923     }
924   if (es_ferror (fp))
925     {
926       err = gpg_error_from_errno (errno);
927       log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
928     }
929   if (es_ferror (fpout))
930     {
931       err = gpg_error_from_errno (errno);
932       log_error (_("error writing '%s': %s\n"), tmpfname, strerror (errno));
933     }
934   if (err)
935     goto leave;
936
937   /* Rename the files. */
938   es_fclose (fp);
939   fp = NULL;
940   if (es_fclose (fpout))
941     {
942       err = gpg_error_from_errno (errno);
943       log_error (_("error closing '%s': %s\n"), tmpfname, strerror (errno));
944       goto leave;
945     }
946   fpout = NULL;
947
948 #ifdef HAVE_W32_SYSTEM
949   /* No atomic mv on W32 systems.  */
950   gnupg_remove (fname);
951 #endif
952   if (rename (tmpfname, fname))
953     {
954       err = gpg_error_from_errno (errno);
955       log_error (_("error renaming '%s' to '%s': %s\n"),
956                  tmpfname, fname, strerror (errno));
957       goto leave;
958     }
959
960  leave:
961   /* Fixme: Relinquish update lock. */
962   xfree (line);
963   es_fclose (fp);
964   xfree (fname);
965   if (fpout)
966     {
967       es_fclose (fpout);
968       if (err && tmpfname)
969         gnupg_remove (tmpfname);
970     }
971   xfree (tmpfname);
972   return err;
973 }
974
975
976
977
978 /* Create the filename for the cache file from the 40 byte ISSUER_HASH
979    string. Caller must release the return string. */
980 static char *
981 make_db_file_name (const char *issuer_hash)
982 {
983   char bname[50];
984
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);
990 }
991
992
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
995  * on success. */
996 static int
997 hash_dbfile (const char *fname, unsigned char *md5buffer)
998 {
999   estream_t fp;
1000   char *buffer;
1001   size_t n;
1002   gcry_md_hd_t md5;
1003   gpg_error_t err;
1004
1005   buffer = xtrymalloc (65536);
1006   fp = buffer? es_fopen (fname, "rb") : NULL;
1007   if (!fp)
1008     {
1009       log_error (_("can't hash '%s': %s\n"), fname, strerror (errno));
1010       xfree (buffer);
1011       return -1;
1012     }
1013
1014   err = gcry_md_open (&md5, GCRY_MD_MD5, 0);
1015   if (err)
1016     {
1017       log_error (_("error setting up MD5 hash context: %s\n"),
1018                  gpg_strerror (err));
1019       xfree (buffer);
1020       es_fclose (fp);
1021       return -1;
1022     }
1023
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));
1027
1028   for (;;)
1029     {
1030       n = es_fread (buffer, 1, 65536, fp);
1031       if (n < 65536 && es_ferror (fp))
1032         {
1033           log_error (_("error hashing '%s': %s\n"), fname, strerror (errno));
1034           xfree (buffer);
1035           es_fclose (fp);
1036           gcry_md_close (md5);
1037           return -1;
1038         }
1039       if (!n)
1040         break;
1041       gcry_md_write (md5, buffer, n);
1042     }
1043   es_fclose (fp);
1044   xfree (buffer);
1045   gcry_md_final (md5);
1046
1047   memcpy (md5buffer, gcry_md_read (md5, GCRY_MD_MD5), 16);
1048   gcry_md_close (md5);
1049   return 0;
1050 }
1051
1052 /* Compare the file FNAME against the dexified MD5 hash MD5HASH and
1053    return 0 if they match. */
1054 static int
1055 check_dbfile (const char *fname, const char *md5hexvalue)
1056 {
1057   unsigned char buffer1[16], buffer2[16];
1058
1059   if (strlen (md5hexvalue) != 32)
1060     {
1061       log_error (_("invalid formatted checksum for '%s'\n"), fname);
1062       return -1;
1063     }
1064   unhexify (buffer1, md5hexvalue);
1065
1066   if (hash_dbfile (fname, buffer2))
1067     return -1;
1068
1069   return memcmp (buffer1, buffer2, 16);
1070 }
1071
1072
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. */
1076 static struct cdb *
1077 lock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
1078 {
1079   char *fname;
1080   int fd;
1081   int open_count;
1082   crl_cache_entry_t e;
1083
1084   if (entry->cdb)
1085     {
1086       entry->cdb_use_count++;
1087       return entry->cdb;
1088     }
1089
1090   for (open_count = 0, e = cache->entries; e; e = e->next)
1091     {
1092       if (e->cdb)
1093         open_count++;
1094 /*       log_debug ("CACHE: cdb=%p use_count=%u lru_count=%u\n", */
1095 /*                  e->cdb,e->cdb_use_count,e->cdb_lru_count); */
1096     }
1097
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
1100      use a loop here. */
1101   while (open_count >= MAX_OPEN_DB_FILES )
1102     {
1103       crl_cache_entry_t last_e = NULL;
1104       unsigned int last_lru = (unsigned int)(-1);
1105
1106       for (e = cache->entries; e; e = e->next)
1107         if (e->cdb && !e->cdb_use_count && e->cdb_lru_count < last_lru)
1108           {
1109             last_lru = e->cdb_lru_count;
1110             last_e = e;
1111           }
1112       if (!last_e)
1113         {
1114           log_error (_("too many open cache files; can't open anymore\n"));
1115           return NULL;
1116         }
1117
1118 /*       log_debug ("CACHE: closing file at cdb=%p\n", last_e->cdb); */
1119
1120       fd = cdb_fileno (last_e->cdb);
1121       cdb_free (last_e->cdb);
1122       xfree (last_e->cdb);
1123       last_e->cdb = NULL;
1124       if (close (fd))
1125         log_error (_("error closing cache file: %s\n"), strerror(errno));
1126       open_count--;
1127     }
1128
1129
1130   fname = make_db_file_name (entry->issuer_hash);
1131   if (opt.verbose)
1132     log_info (_("opening cache file '%s'\n"), fname );
1133
1134   if (!entry->dbfile_checked)
1135     {
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. */
1140     }
1141
1142   entry->cdb = xtrycalloc (1, sizeof *entry->cdb);
1143   if (!entry->cdb)
1144     {
1145       xfree (fname);
1146       return NULL;
1147     }
1148   fd = gnupg_open (fname, O_RDONLY | O_BINARY, 0);
1149   if (fd == -1)
1150     {
1151       log_error (_("error opening cache file '%s': %s\n"),
1152                  fname, strerror (errno));
1153       xfree (entry->cdb);
1154       entry->cdb = NULL;
1155       xfree (fname);
1156       return NULL;
1157     }
1158   if (cdb_init (entry->cdb, fd))
1159     {
1160       log_error (_("error initializing cache file '%s' for reading: %s\n"),
1161                  fname, strerror (errno));
1162       xfree (entry->cdb);
1163       entry->cdb = NULL;
1164       close (fd);
1165       xfree (fname);
1166       return NULL;
1167     }
1168   xfree (fname);
1169
1170   entry->cdb_use_count = 1;
1171   entry->cdb_lru_count = 0;
1172
1173   return entry->cdb;
1174 }
1175
1176 /* Unlock a cache file, so that it can be reused. */
1177 static void
1178 unlock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
1179 {
1180   if (!entry->cdb)
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"));
1184   else
1185     {
1186       entry->cdb_use_count--;
1187       entry->cdb_lru_count++;
1188     }
1189
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)
1193     {
1194       crl_cache_entry_t eprev, enext;
1195
1196       enext = entry->next;
1197       for (eprev = cache->entries;
1198            eprev && eprev->next != entry; eprev = eprev->next)
1199         ;
1200       assert (eprev);
1201       if (eprev == cache->entries)
1202         cache->entries = enext;
1203       else
1204         eprev->next = enext;
1205       /* FIXME: Do we leak ENTRY? */
1206     }
1207 }
1208
1209
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)
1214 {
1215   while (first && (first->deleted || strcmp (issuer_hash, first->issuer_hash)))
1216     first = first->next;
1217   return first;
1218 }
1219
1220
1221 /* Create a new CRL cache. This function is usually called only once.
1222    never fail. */
1223 void
1224 crl_cache_init(void)
1225 {
1226   crl_cache_t cache = NULL;
1227   gpg_error_t err;
1228
1229   if (current_cache)
1230     {
1231       log_error ("crl cache has already been initialized - not doing twice\n");
1232       return;
1233     }
1234
1235   err = open_dir (&cache);
1236   if (err)
1237     log_fatal (_("failed to create a new cache object: %s\n"),
1238                gpg_strerror (err));
1239   current_cache = cache;
1240 }
1241
1242
1243 /* Remove the cache information and all its resources.  Note that we
1244    still keep the cache on disk. */
1245 void
1246 crl_cache_deinit (void)
1247 {
1248   if (current_cache)
1249     {
1250       release_cache (current_cache);
1251       current_cache = NULL;
1252     }
1253 }
1254
1255
1256 /* Delete the cache from disk and memory. Return 0 on success.*/
1257 int
1258 crl_cache_flush (void)
1259 {
1260   int rc;
1261
1262   crl_cache_deinit ();
1263   rc = cleanup_cache_dir (0)? -1 : 0;
1264   crl_cache_init ();
1265
1266   return rc;
1267 }
1268
1269
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
1275    and 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,
1279                int force_refresh)
1280 {
1281   crl_cache_t cache = get_current_cache ();
1282   crl_cache_result_t retval;
1283   struct cdb *cdb;
1284   int rc;
1285   crl_cache_entry_t entry;
1286   gnupg_isotime_t current_time;
1287   size_t n;
1288
1289   (void)ctrl;
1290
1291   entry = find_entry (cache->entries, issuer_hash);
1292   if (!entry)
1293     {
1294       log_info (_("no CRL available for issuer id %s\n"), issuer_hash );
1295       return CRL_CACHE_DONTKNOW;
1296     }
1297
1298   gnupg_get_isotime (current_time);
1299   if (strcmp (entry->next_update, current_time) < 0 )
1300     {
1301       log_info (_("cached CRL for issuer id %s too old; update required\n"),
1302                 issuer_hash);
1303       return CRL_CACHE_DONTKNOW;
1304     }
1305   if (force_refresh)
1306     {
1307       gnupg_isotime_t tmptime;
1308
1309       if (*entry->last_refresh)
1310         {
1311           gnupg_copy_time (tmptime, entry->last_refresh);
1312           add_seconds_to_isotime (tmptime, 30 * 60);
1313           if (strcmp (tmptime, current_time) < 0 )
1314             {
1315               log_info (_("force-crl-refresh active and %d minutes passed for"
1316                           " issuer id %s; update required\n"),
1317                         30, issuer_hash);
1318               return CRL_CACHE_DONTKNOW;
1319             }
1320         }
1321       else
1322         {
1323           log_info (_("force-crl-refresh active for"
1324                       " issuer id %s; update required\n"),
1325                     issuer_hash);
1326           return CRL_CACHE_DONTKNOW;
1327         }
1328     }
1329
1330   if (entry->invalid)
1331     {
1332       log_info (_("available CRL for issuer ID %s can't be used\n"),
1333                 issuer_hash);
1334       return CRL_CACHE_CANTUSE;
1335     }
1336
1337   cdb = lock_db_file (cache, entry);
1338   if (!cdb)
1339     return CRL_CACHE_DONTKNOW; /* Hmmm, not the best error code. */
1340
1341   if (!entry->dbfile_checked)
1342     {
1343       log_error (_("cached CRL for issuer id %s tampered; we need to update\n")
1344                  , issuer_hash);
1345       unlock_db_file (cache, entry);
1346       return CRL_CACHE_DONTKNOW;
1347     }
1348
1349   rc = cdb_find (cdb, sn, snlen);
1350   if (rc == 1)
1351     {
1352       n = cdb_datalen (cdb);
1353       if (n != 16)
1354         {
1355           log_error (_("WARNING: invalid cache record length for S/N "));
1356           log_printf ("0x");
1357           log_printhex (sn, snlen, "");
1358         }
1359       else if (opt.verbose)
1360         {
1361           unsigned char record[16];
1362           char *tmp = hexify_data (sn, snlen, 1);
1363
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));
1367           else
1368             log_info (_("S/N %s is not valid; reason=%02X  date=%.15s\n"),
1369                       tmp, *record, record+1);
1370           xfree (tmp);
1371         }
1372       retval = CRL_CACHE_INVALID;
1373     }
1374   else if (!rc)
1375     {
1376       if (opt.verbose)
1377         {
1378           char *serialno = hexify_data (sn, snlen, 1);
1379           log_info (_("S/N %s is valid, it is not listed in the CRL\n"),
1380                     serialno );
1381           xfree (serialno);
1382         }
1383       retval = CRL_CACHE_VALID;
1384     }
1385   else
1386     {
1387       log_error (_("error getting data from cache file: %s\n"),
1388                  strerror (errno));
1389       retval = CRL_CACHE_DONTKNOW;
1390     }
1391
1392
1393   if (entry->user_trust_req
1394       && (retval == CRL_CACHE_VALID || retval == CRL_CACHE_INVALID))
1395     {
1396       if (!entry->check_trust_anchor)
1397         {
1398           log_error ("inconsistent data on user trust check\n");
1399           retval = CRL_CACHE_CANTUSE;
1400         }
1401       else if (get_istrusted_from_client (ctrl, entry->check_trust_anchor))
1402         {
1403           if (opt.verbose)
1404             log_info ("no system trust and client does not trust either\n");
1405           retval = CRL_CACHE_NOTTRUSTED;
1406         }
1407       else
1408         {
1409           /* Okay, the CRL is considered valid by the client and thus
1410              we can return the result as is.  */
1411         }
1412     }
1413
1414   unlock_db_file (cache, entry);
1415
1416   return retval;
1417 }
1418
1419
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
1425    and over.  */
1426 crl_cache_result_t
1427 crl_cache_isvalid (ctrl_t ctrl, const char *issuer_hash, const char *serialno,
1428                    int force_refresh)
1429 {
1430   crl_cache_result_t result;
1431   unsigned char snbuf_buffer[50];
1432   unsigned char *snbuf;
1433   size_t n;
1434
1435   n = strlen (serialno)/2+1;
1436   if (n < sizeof snbuf_buffer - 1)
1437     snbuf = snbuf_buffer;
1438   else
1439     {
1440       snbuf = xtrymalloc (n);
1441       if (!snbuf)
1442         return CRL_CACHE_DONTKNOW;
1443     }
1444
1445   n = unhexify (snbuf, serialno);
1446
1447   result = cache_isvalid (ctrl, issuer_hash, snbuf, n, force_refresh);
1448
1449   if (snbuf != snbuf_buffer)
1450     xfree (snbuf);
1451
1452   return result;
1453 }
1454
1455
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.  */
1461 gpg_error_t
1462 crl_cache_cert_isvalid (ctrl_t ctrl, ksba_cert_t cert,
1463                         int force_refresh)
1464 {
1465   gpg_error_t err;
1466   crl_cache_result_t result;
1467   unsigned char issuerhash[20];
1468   char issuerhash_hex[41];
1469   ksba_sexp_t serial;
1470   unsigned char *sn;
1471   size_t snlen;
1472   char *endp, *tmp;
1473   int i;
1474
1475   /* Compute the hash value of the issuer name.  */
1476   tmp = ksba_cert_get_issuer (cert, 0);
1477   if (!tmp)
1478     {
1479       log_error ("oops: issuer missing in certificate\n");
1480       return gpg_error (GPG_ERR_INV_CERT_OBJ);
1481     }
1482   gcry_md_hash_buffer (GCRY_MD_SHA1, issuerhash, tmp, strlen (tmp));
1483   xfree (tmp);
1484   for (i=0,tmp=issuerhash_hex; i < 20; i++, tmp += 2)
1485     sprintf (tmp, "%02X", issuerhash[i]);
1486
1487   /* Get the serial number.  */
1488   serial = ksba_cert_get_serial (cert);
1489   if (!serial)
1490     {
1491       log_error ("oops: S/N missing in certificate\n");
1492       return gpg_error (GPG_ERR_INV_CERT_OBJ);
1493     }
1494   sn = serial;
1495   if (*sn != '(')
1496     {
1497       log_error ("oops: invalid S/N\n");
1498       xfree (serial);
1499       return gpg_error (GPG_ERR_INV_CERT_OBJ);
1500     }
1501   sn++;
1502   snlen = strtoul (sn, &endp, 10);
1503   sn = endp;
1504   if (*sn != ':')
1505     {
1506       log_error ("oops: invalid S/N\n");
1507       xfree (serial);
1508       return gpg_error (GPG_ERR_INV_CERT_OBJ);
1509     }
1510   sn++;
1511
1512   /* Check the cache.  */
1513   result = cache_isvalid (ctrl, issuerhash_hex, sn, snlen, force_refresh);
1514   switch (result)
1515     {
1516     case CRL_CACHE_VALID:
1517       err = 0;
1518       break;
1519     case CRL_CACHE_INVALID:
1520       err = gpg_error (GPG_ERR_CERT_REVOKED);
1521       break;
1522     case CRL_CACHE_DONTKNOW:
1523       err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1524       break;
1525     case CRL_CACHE_NOTTRUSTED:
1526       err = gpg_error (GPG_ERR_NOT_TRUSTED);
1527       break;
1528     case CRL_CACHE_CANTUSE:
1529       err = gpg_error (GPG_ERR_INV_CRL_OBJ);
1530       break;
1531     default:
1532       log_fatal ("cache_isvalid returned invalid status code %d\n", result);
1533     }
1534
1535   xfree (serial);
1536   return err;
1537 }
1538
1539
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.  */
1543 static int
1544 hash_algo_from_buffer (const void *buffer, size_t buflen)
1545 {
1546   char *string;
1547   int algo;
1548
1549   string = xtrymalloc (buflen + 1);
1550   if (!string)
1551     {
1552       log_error (_("out of core\n"));
1553       return 0;
1554     }
1555   memcpy (string, buffer, buflen);
1556   string[buflen] = 0;
1557   algo = gcry_md_map_name (string);
1558   if (!algo)
1559     log_error ("unknown digest algorithm '%s' used in certificate\n", string);
1560   xfree (string);
1561   return algo;
1562 }
1563
1564
1565 /* Return an unsigned integer from the non-null termnated string
1566  * (buffer,buflen).  Returns 0 on failure.  */
1567 static unsigned int
1568 uint_from_buffer (const void *buffer, size_t buflen)
1569 {
1570   char *string;
1571   unsigned int val;
1572
1573   string = xtrymalloc (buflen + 1);
1574   if (!string)
1575     {
1576       log_error (_("out of core\n"));
1577       return 0;
1578     }
1579   memcpy (string, buffer, buflen);
1580   string[buflen] = 0;
1581   val = strtoul (string, NULL, 10);
1582   xfree (string);
1583   return val;
1584 }
1585
1586
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. */
1590 static gpg_error_t
1591 start_sig_check (ksba_crl_t crl, gcry_md_hd_t *md, int *algo, int *use_pss)
1592 {
1593   gpg_error_t err;
1594   const char *algoid;
1595
1596   *use_pss = 0;
1597   algoid = ksba_crl_get_digest_algo (crl);
1598   if (algoid && !strcmp (algoid, "1.2.840.113549.1.1.10"))
1599     {
1600       /* Parse rsaPSS parameter.  */
1601       gcry_buffer_t ioarray[1] = { {0} };
1602       ksba_sexp_t pssparam;
1603       size_t n;
1604       gcry_sexp_t psssexp;
1605
1606       pssparam = ksba_crl_get_sig_val (crl);
1607       n = gcry_sexp_canon_len (pssparam, 0, NULL, NULL);
1608       if (!n)
1609         {
1610           ksba_free (pssparam);
1611           log_error (_("got an invalid S-expression from libksba\n"));
1612           return gpg_error (GPG_ERR_INV_SEXP);
1613         }
1614       err = gcry_sexp_sscan (&psssexp, NULL, pssparam, n);
1615       ksba_free (pssparam);
1616       if (err)
1617         {
1618           log_error (_("converting S-expression failed: %s\n"),
1619                      gcry_strerror (err));
1620           return err;
1621         }
1622
1623       err = gcry_sexp_extract_param (psssexp, "sig-val",
1624                                     "&'hash-algo'", ioarray, NULL);
1625       gcry_sexp_release (psssexp);
1626       if (err)
1627         {
1628           log_error ("extracting params from PSS failed: %s\n",
1629                      gpg_strerror (err));
1630           return err;
1631         }
1632       *algo = hash_algo_from_buffer (ioarray[0].data, ioarray[0].len);
1633       xfree (ioarray[0].data);
1634       *use_pss = 1;
1635     }
1636   else
1637     *algo = gcry_md_map_name (algoid);
1638   if (!*algo)
1639     {
1640       log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?");
1641       return gpg_error (GPG_ERR_DIGEST_ALGO);
1642     }
1643
1644   err = gcry_md_open (md, *algo, 0);
1645   if (err)
1646     {
1647       log_error (_("gcry_md_open for algorithm %d failed: %s\n"),
1648                  *algo, gcry_strerror (err));
1649       return err;
1650     }
1651   if (DBG_HASHING)
1652     gcry_md_debug (*md, "hash.cert");
1653
1654   ksba_crl_set_hash_function (crl, HASH_FNC, *md);
1655   return 0;
1656 }
1657
1658
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.  */
1664 static gpg_error_t
1665 finish_sig_check (ksba_crl_t crl, gcry_md_hd_t md, int algo,
1666                   ksba_cert_t issuer_cert, int use_pss)
1667 {
1668   gpg_error_t err;
1669   ksba_sexp_t sigval = NULL, pubkey = NULL;
1670   size_t n;
1671   gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
1672   unsigned int saltlen = 0;  /* (used only with use_pss)  */
1673   int pkalgo;
1674
1675   /* This also stops debugging on the MD.  */
1676   gcry_md_final (md);
1677
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);
1681   if (!n)
1682     {
1683       log_error (_("got an invalid S-expression from libksba\n"));
1684       err = gpg_error (GPG_ERR_INV_SEXP);
1685       goto leave;
1686     }
1687   err = gcry_sexp_sscan (&s_sig, NULL, sigval, n);
1688   if (err)
1689     {
1690       log_error (_("converting S-expression failed: %s\n"),
1691                  gcry_strerror (err));
1692       goto leave;
1693     }
1694
1695   if (use_pss)
1696     {
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;
1701       int hashalgo;
1702
1703       pssparam = ksba_crl_get_sig_val (crl);
1704       n = gcry_sexp_canon_len (pssparam, 0, NULL, NULL);
1705       if (!n)
1706         {
1707           ksba_free (pssparam);
1708           log_error (_("got an invalid S-expression from libksba\n"));
1709           err = gpg_error (GPG_ERR_INV_SEXP);
1710           goto leave;
1711         }
1712       err = gcry_sexp_sscan (&psssexp, NULL, pssparam, n);
1713       ksba_free (pssparam);
1714       if (err)
1715         {
1716           log_error (_("converting S-expression failed: %s\n"),
1717                      gcry_strerror (err));
1718           goto leave;
1719         }
1720
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);
1725       if (err)
1726         {
1727           log_error ("extracting params from PSS failed: %s\n",
1728                      gpg_strerror (err));
1729           goto leave;
1730         }
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)
1736         {
1737           log_error ("hash algo mismatch: %d announced but %d used\n",
1738                      algo, hashalgo);
1739           err = gpg_error (GPG_ERR_INV_CRL);
1740           goto leave;
1741         }
1742       /* Add some restrictions; see ../sm/certcheck.c for details.  */
1743       switch (algo)
1744         {
1745         case GCRY_MD_SHA1:
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:
1752           break;
1753         default:
1754           log_error ("PSS hash algorithm '%s' rejected\n",
1755                      gcry_md_algo_name (algo));
1756           err = gpg_error (GPG_ERR_DIGEST_ALGO);
1757           goto leave;
1758         }
1759
1760       if (gcry_md_get_algo_dlen (algo) != saltlen)
1761         {
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);
1765           goto leave;
1766         }
1767     }
1768
1769
1770   /* Get and convert the public key for the issuer certificate. */
1771   if (DBG_X509)
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);
1775   if (!n)
1776     {
1777       log_error (_("got an invalid S-expression from libksba\n"));
1778       err = gpg_error (GPG_ERR_INV_SEXP);
1779       goto leave;
1780     }
1781   err = gcry_sexp_sscan (&s_pkey, NULL, pubkey, n);
1782   if (err)
1783     {
1784       log_error (_("converting S-expression failed: %s\n"),
1785                  gcry_strerror (err));
1786       goto leave;
1787     }
1788
1789   /* Create an S-expression with the actual hash value. */
1790   if (use_pss)
1791     {
1792       err = gcry_sexp_build (&s_hash, NULL,
1793                              "(data (flags pss)"
1794                              "(hash %s %b)"
1795                              "(salt-length %u))",
1796                              hash_algo_to_string (algo),
1797                              (int)gcry_md_get_algo_dlen (algo),
1798                              gcry_md_read (md, algo),
1799                              saltlen);
1800     }
1801   else if ((pkalgo = pk_algo_from_sexp (s_pkey)) == GCRY_PK_ECC)
1802     {
1803       unsigned int qbits0, qbits;
1804
1805       qbits0 = gcry_pk_get_nbits (s_pkey);
1806       qbits = qbits0 == 521? 512 : qbits0;
1807
1808       if ((qbits%8))
1809         {
1810           log_error ("ECDSA requires the hash length to be a"
1811                      " multiple of 8 bits\n");
1812           err = gpg_error (GPG_ERR_INTERNAL);
1813           goto leave;
1814         }
1815
1816       /* Don't allow any Q smaller than 160 bits.  */
1817       if (qbits < 160)
1818         {
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);
1822           goto leave;
1823         }
1824
1825       /* Check if we're too short.  */
1826       n = gcry_md_get_algo_dlen (algo);
1827       if (n < qbits/8)
1828         {
1829           log_error (_("a %u bit hash is not valid for a %u bit %s key\n"),
1830                      (unsigned int)n*8,
1831                      qbits0,
1832                      gcry_pk_algo_name (pkalgo));
1833           if (n < 20)
1834             {
1835               err = gpg_error (GPG_ERR_INTERNAL);
1836               goto leave;
1837             }
1838         }
1839
1840       /* Truncate.  */
1841       if (n > qbits/8)
1842         n = qbits/8;
1843
1844       err = gcry_sexp_build (&s_hash, NULL, "(data(flags raw)(value %b))",
1845                              (int)n,
1846                              gcry_md_read (md, algo));
1847
1848     }
1849   else
1850     {
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));
1856     }
1857   if (err)
1858     {
1859       log_error (_("creating S-expression failed: %s\n"), gcry_strerror (err));
1860       goto leave;
1861     }
1862
1863   /* Pass this on to the signature verification. */
1864   err = gcry_pk_verify (s_sig, s_hash, s_pkey);
1865   if (DBG_X509)
1866     log_debug ("%s: gcry_pk_verify: %s\n", __func__, gpg_strerror (err));
1867
1868  leave:
1869   xfree (sigval);
1870   xfree (pubkey);
1871   gcry_sexp_release (s_sig);
1872   gcry_sexp_release (s_hash);
1873   gcry_sexp_release (s_pkey);
1874   gcry_md_close (md);
1875
1876   return err;
1877 }
1878
1879
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.  */
1882 static void
1883 abort_sig_check (ksba_crl_t crl, gcry_md_hd_t md)
1884 {
1885   (void)crl;
1886   if (md)
1887     gcry_md_close (md);
1888 }
1889
1890
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.
1905 */
1906 static int
1907 crl_parse_insert (ctrl_t ctrl, ksba_crl_t crl,
1908                   struct cdb_make *cdb, const char *fname,
1909                   char **r_crlissuer,
1910                   ksba_isotime_t thisupdate, ksba_isotime_t nextupdate,
1911                   char **r_trust_anchor)
1912 {
1913   gpg_error_t err;
1914   ksba_stop_reason_t stopreason;
1915   ksba_cert_t crlissuer_cert = NULL;
1916   gcry_md_hd_t md = NULL;
1917   int algo = 0;
1918   int use_pss = 0;
1919   size_t n;
1920
1921   (void)fname;
1922
1923   *r_crlissuer = NULL;
1924   *thisupdate = *nextupdate = 0;
1925   *r_trust_anchor = NULL;
1926
1927   /* Start of the KSBA parser loop. */
1928   do
1929     {
1930       err = ksba_crl_parse (crl, &stopreason);
1931       if (err)
1932         {
1933           log_error (_("ksba_crl_parse failed: %s\n"), gpg_strerror (err) );
1934           goto failure;
1935         }
1936
1937       switch (stopreason)
1938         {
1939         case KSBA_SR_BEGIN_ITEMS:
1940           {
1941             err = start_sig_check (crl, &md, &algo, &use_pss);
1942             if (err)
1943               goto failure;
1944
1945             err = ksba_crl_get_update_times (crl, thisupdate, nextupdate);
1946             if (err)
1947               {
1948                 log_error (_("error getting update times of CRL: %s\n"),
1949                            gpg_strerror (err));
1950                 err = gpg_error (GPG_ERR_INV_CRL);
1951                 goto failure;
1952               }
1953
1954             if (opt.verbose || !*nextupdate)
1955               log_info (_("update times of this CRL: this=%s next=%s\n"),
1956                         thisupdate, nextupdate);
1957             if (!*nextupdate)
1958               {
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);
1963               }
1964           }
1965           break;
1966
1967         case KSBA_SR_GOT_ITEM:
1968           {
1969             ksba_sexp_t serial;
1970             const unsigned char *p;
1971             ksba_isotime_t rdate;
1972             ksba_crl_reason_t reason;
1973             int rc;
1974             unsigned char record[1+15];
1975
1976             err = ksba_crl_get_item (crl, &serial, rdate, &reason);
1977             if (err)
1978               {
1979                 log_error (_("error getting CRL item: %s\n"),
1980                            gpg_strerror (err));
1981                 err = gpg_error (GPG_ERR_INV_CRL);
1982                 ksba_free (serial);
1983                 goto failure;
1984               }
1985             p = serial_to_buffer (serial, &n);
1986             if (!p)
1987               BUG ();
1988             record[0] = (reason & 0xff);
1989             memcpy (record+1, rdate, 15);
1990             rc = cdb_make_add (cdb, p, n, record, 1+15);
1991             if (rc)
1992               {
1993                 err = gpg_error_from_errno (errno);
1994                 log_error (_("error inserting item into "
1995                              "temporary cache file: %s\n"),
1996                            strerror (errno));
1997                 goto failure;
1998               }
1999
2000             ksba_free (serial);
2001           }
2002           break;
2003
2004         case KSBA_SR_END_ITEMS:
2005           break;
2006
2007         case KSBA_SR_READY:
2008           {
2009             char *crlissuer;
2010             ksba_name_t authid;
2011             ksba_sexp_t authidsn;
2012             ksba_sexp_t keyid;
2013
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
2017                items. */
2018             err = ksba_crl_get_issuer (crl, &crlissuer);
2019             if( err )
2020               {
2021                 log_error (_("no CRL issuer found in CRL: %s\n"),
2022                            gpg_strerror (err) );
2023                 err = gpg_error (GPG_ERR_INV_CRL);
2024                 goto failure;
2025               }
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) */
2030
2031             if (!ksba_crl_get_auth_key_id (crl, &keyid, &authid, &authidsn))
2032               {
2033                 const char *s;
2034
2035                 if (opt.verbose)
2036                   log_info (_("locating CRL issuer certificate by "
2037                               "authorityKeyIdentifier\n"));
2038
2039                 s = ksba_name_enum (authid, 0);
2040                 if (s && *authidsn)
2041                   crlissuer_cert = find_cert_bysn (ctrl, s, authidsn);
2042                 if (!crlissuer_cert && keyid)
2043                   crlissuer_cert = find_cert_bysubject (ctrl,
2044                                                         crlissuer, keyid);
2045
2046                 if (!crlissuer_cert)
2047                   {
2048                     log_info ("CRL issuer certificate ");
2049                     if (keyid)
2050                       {
2051                         log_printf ("{");
2052                         dump_serial (keyid);
2053                         log_printf ("} ");
2054                       }
2055                     if (authidsn)
2056                       {
2057                         log_printf ("(#");
2058                         dump_serial (authidsn);
2059                         log_printf ("/");
2060                         dump_string (s);
2061                         log_printf (") ");
2062                       }
2063                     log_printf ("not found\n");
2064                   }
2065                 ksba_name_release (authid);
2066                 xfree (authidsn);
2067                 xfree (keyid);
2068               }
2069             else
2070               crlissuer_cert = find_cert_bysubject (ctrl, crlissuer, NULL);
2071             err = 0;
2072             if (!crlissuer_cert)
2073               {
2074                 err = gpg_error (GPG_ERR_MISSING_CERT);
2075                 goto failure;
2076               }
2077
2078             err = finish_sig_check (crl, md, algo, crlissuer_cert, use_pss);
2079             md = NULL; /* Closed.  */
2080             if (err)
2081               {
2082                 log_error (_("CRL signature verification failed: %s\n"),
2083                            gpg_strerror (err));
2084                 goto failure;
2085               }
2086
2087             err = validate_cert_chain (ctrl, crlissuer_cert, NULL,
2088                                        (VALIDATE_FLAG_TRUST_CONFIG
2089                                         | VALIDATE_FLAG_CRL
2090                                         | VALIDATE_FLAG_RECURSIVE),
2091                                        r_trust_anchor);
2092             if (err)
2093               {
2094                 log_error (_("error checking validity of CRL "
2095                              "issuer certificate: %s\n"),
2096                            gpg_strerror (err));
2097                 goto failure;
2098               }
2099
2100           }
2101           break;
2102
2103         default:
2104           log_debug ("crl_parse_insert: unknown stop reason\n");
2105           err = gpg_error (GPG_ERR_BUG);
2106           goto failure;
2107         }
2108     }
2109   while (stopreason != KSBA_SR_READY);
2110   log_assert (!err);
2111
2112
2113  failure:
2114   abort_sig_check (crl, md);
2115   ksba_cert_release (crlissuer_cert);
2116   return err;
2117 }
2118
2119
2120
2121 /* Return the crlNumber extension as an allocated hex string or NULL
2122    if there is none. */
2123 static char *
2124 get_crl_number (ksba_crl_t crl)
2125 {
2126   gpg_error_t err;
2127   ksba_sexp_t number;
2128   char *string;
2129
2130   err = ksba_crl_get_crl_number (crl, &number);
2131   if (err)
2132     return NULL;
2133   string = serial_hex (number);
2134   ksba_free (number);
2135   return string;
2136 }
2137
2138
2139 /* Return the authorityKeyIdentifier or NULL if it is not available.
2140    The issuer name may consists of several parts - they are delimited by
2141    0x01. */
2142 static char *
2143 get_auth_key_id (ksba_crl_t crl, char **serialno)
2144 {
2145   gpg_error_t err;
2146   ksba_name_t name;
2147   ksba_sexp_t sn;
2148   int idx;
2149   const char *s;
2150   char *string;
2151   size_t length;
2152
2153   *serialno = NULL;
2154   err = ksba_crl_get_auth_key_id (crl, NULL, &name, &sn);
2155   if (err)
2156     return NULL;
2157   *serialno = serial_hex (sn);
2158   ksba_free (sn);
2159
2160   if (!name)
2161     return xstrdup ("");
2162
2163   length = 0;
2164   for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
2165     {
2166       char *p = ksba_name_get_uri (name, idx);
2167       length += strlen (p?p:s) + 1;
2168       xfree (p);
2169     }
2170   string = xtrymalloc (length+1);
2171   if (string)
2172     {
2173       *string = 0;
2174       for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
2175         {
2176           char *p = ksba_name_get_uri (name, idx);
2177           if (*string)
2178             strcat (string, "\x01");
2179           strcat (string, p?p:s);
2180           xfree (p);
2181         }
2182     }
2183   ksba_name_release (name);
2184   return string;
2185 }
2186
2187
2188
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.
2192
2193    Called by:
2194       crl_cache_load
2195          cmd_loadcrl
2196          --load-crl
2197       crl_cache_reload_crl
2198          cmd_isvalid
2199          cmd_checkcrl
2200       cmd_loadcrl
2201       --fetch-crl
2202
2203  */
2204 gpg_error_t
2205 crl_cache_insert (ctrl_t ctrl, const char *url, ksba_reader_t reader)
2206 {
2207   crl_cache_t cache = get_current_cache ();
2208   gpg_error_t err, err2;
2209   ksba_crl_t crl;
2210   char *fname = NULL;
2211   char *newfname = NULL;
2212   struct cdb_make cdb;
2213   int fd_cdb = -1;
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;
2222   int idx;
2223   const char *oid;
2224   int critical;
2225   char *trust_anchor = NULL;
2226
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.*/
2230
2231   err2 = 0;
2232
2233   err = ksba_crl_new (&crl);
2234   if (err)
2235     {
2236       log_error (_("ksba_crl_new failed: %s\n"), gpg_strerror (err));
2237       goto leave;
2238     }
2239
2240   err = ksba_crl_set_reader (crl, reader);
2241   if ( err )
2242     {
2243       log_error (_("ksba_crl_set_reader failed: %s\n"), gpg_strerror (err));
2244       goto leave;
2245     }
2246
2247   /* Create a temporary cache file to load the CRL into. */
2248   {
2249     char *tmpfname, *p;
2250     const char *nodename;
2251 #ifndef HAVE_W32_SYSTEM
2252     struct utsname utsbuf;
2253 #endif
2254
2255 #ifdef HAVE_W32_SYSTEM
2256     nodename = "unknown";
2257 #else
2258     if (uname (&utsbuf))
2259       nodename = "unknown";
2260     else
2261       nodename = utsbuf.nodename;
2262 #endif
2263
2264     gpgrt_asprintf (&tmpfname, "crl-tmp-%s-%u-%p.db.tmp",
2265                     nodename, (unsigned int)getpid (), &tmpfname);
2266     if (!tmpfname)
2267       {
2268         err = gpg_error_from_syserror ();
2269         goto leave;
2270       }
2271     for (p=tmpfname; *p; p++)
2272       if (*p == '/')
2273         *p = '.';
2274     fname = make_filename (opt.homedir_cache, DBDIR_D, tmpfname, NULL);
2275     xfree (tmpfname);
2276     if (!gnupg_remove (fname))
2277       log_info (_("removed stale temporary cache file '%s'\n"), fname);
2278     else if (errno != ENOENT)
2279       {
2280         err = gpg_error_from_syserror ();
2281         log_error (_("problem removing stale temporary cache file '%s': %s\n"),
2282                    fname, gpg_strerror (err));
2283         goto leave;
2284       }
2285   }
2286
2287   fd_cdb = gnupg_open (fname, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2288   if (fd_cdb == -1)
2289     {
2290       err = gpg_error_from_errno (errno);
2291       log_error (_("error creating temporary cache file '%s': %s\n"),
2292                  fname, strerror (errno));
2293       goto leave;
2294     }
2295   cdb_make_start(&cdb, fd_cdb);
2296
2297   err = crl_parse_insert (ctrl, crl, &cdb, fname,
2298                           &issuer, thisupdate, nextupdate, &trust_anchor);
2299   if (err)
2300     {
2301       log_error (_("crl_parse_insert failed: %s\n"), gpg_strerror (err));
2302       /* Error in cleanup ignored.  */
2303       cdb_make_finish (&cdb);
2304       goto leave;
2305     }
2306
2307   /* Finish the database. */
2308   if (cdb_make_finish (&cdb))
2309     {
2310       err = gpg_error_from_errno (errno);
2311       log_error (_("error finishing temporary cache file '%s': %s\n"),
2312                  fname, strerror (errno));
2313       goto leave;
2314     }
2315   if (close (fd_cdb))
2316     {
2317       err = gpg_error_from_errno (errno);
2318       log_error (_("error closing temporary cache file '%s': %s\n"),
2319                  fname, strerror (errno));
2320       goto leave;
2321     }
2322   fd_cdb = -1;
2323
2324
2325   /* Create a checksum. */
2326   {
2327     unsigned char md5buf[16];
2328
2329     if (hash_dbfile (fname, md5buf))
2330       {
2331         err = gpg_error (GPG_ERR_CHECKSUM);
2332         goto leave;
2333       }
2334     checksum = hexify_data (md5buf, 16, 0);
2335   }
2336
2337
2338   /* Check whether that new CRL is still not expired. */
2339   gnupg_get_isotime (current_time);
2340   if (strcmp (nextupdate, current_time) < 0 )
2341     {
2342       if (opt.force)
2343         log_info (_("WARNING: new CRL still too old; it expired on %s "
2344                     "- loading anyway\n"),  nextupdate);
2345       else
2346         {
2347           log_error (_("new CRL still too old; it expired on %s\n"),
2348                      nextupdate);
2349           if (!err2)
2350             err2 = gpg_error (GPG_ERR_CRL_TOO_OLD);
2351           invalidate_crl |= INVCRL_TOO_OLD;
2352         }
2353     }
2354
2355   /* Check for unknown critical extensions. */
2356   for (idx=0; !(err=ksba_crl_get_extension (crl, idx, &oid, &critical,
2357                                               NULL, NULL)); idx++)
2358     {
2359       strlist_t sl;
2360
2361       if (!critical
2362           || !strcmp (oid, oidstr_authorityKeyIdentifier)
2363           || !strcmp (oid, oidstr_crlNumber) )
2364         continue;
2365
2366       for (sl=opt.ignored_crl_extensions;
2367            sl && strcmp (sl->d, oid); sl = sl->next)
2368         ;
2369       if (sl)
2370         continue;  /* Is in ignored list.  */
2371
2372       log_error (_("unknown critical CRL extension %s\n"), oid);
2373       log_info ("(CRL='%s')\n", url);
2374       if (!err2)
2375         err2 = gpg_error (GPG_ERR_INV_CRL);
2376       invalidate_crl |= INVCRL_UNKNOWN_EXTN;
2377     }
2378   if (gpg_err_code (err) == GPG_ERR_EOF
2379       || gpg_err_code (err) == GPG_ERR_NO_DATA )
2380     err = 0;
2381   if (err)
2382     {
2383       log_error (_("error reading CRL extensions: %s\n"), gpg_strerror (err));
2384       err = gpg_error (GPG_ERR_INV_CRL);
2385     }
2386
2387
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));
2391
2392   /* Create an ENTRY. */
2393   entry = xtrycalloc (1, sizeof *entry);
2394   if (!entry)
2395     {
2396       err = gpg_error_from_syserror ();
2397       goto leave;
2398     }
2399   entry->release_ptr = xtrymalloc (strlen (issuer_hash) + 1
2400                                    + strlen (issuer) + 1
2401                                    + strlen (url) + 1
2402                                    + strlen (checksum) + 1);
2403   if (!entry->release_ptr)
2404     {
2405       err = gpg_error_from_syserror ();
2406       xfree (entry);
2407       entry = NULL;
2408       goto leave;
2409     }
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;
2424
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)
2429     e->deleted = 1;
2430
2431   /* Rename the temporary DB to the real name. */
2432   newfname = make_db_file_name (entry->issuer_hash);
2433   if (opt.verbose)
2434     log_info (_("creating cache file '%s'\n"), newfname);
2435
2436   /* Just in case close unused matching files.  Actually we need this
2437      only under Windows but saving file descriptors is never bad.  */
2438   {
2439     int any;
2440     do
2441       {
2442         any = 0;
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))
2446             {
2447               int fd = cdb_fileno (e->cdb);
2448               cdb_free (e->cdb);
2449               xfree (e->cdb);
2450               e->cdb = NULL;
2451               if (close (fd))
2452                 log_error (_("error closing cache file: %s\n"),
2453                            strerror(errno));
2454               any = 1;
2455               break;
2456             }
2457       }
2458     while (any);
2459   }
2460 #ifdef HAVE_W32_SYSTEM
2461   gnupg_remove (newfname);
2462 #endif
2463   if (rename (fname, newfname))
2464     {
2465       err = gpg_error_from_syserror ();
2466       log_error (_("problem renaming '%s' to '%s': %s\n"),
2467                  fname, newfname, gpg_strerror (err));
2468       goto leave;
2469     }
2470   xfree (fname); fname = NULL; /*(let the cleanup code not try to remove it)*/
2471
2472   /* Link the new entry in. */
2473   entry->next = cache->entries;
2474   cache->entries = entry;
2475   entry = NULL;
2476
2477   err = update_dir (cache);
2478   if (err)
2479     {
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. */
2483     }
2484
2485
2486  leave:
2487   release_one_cache_entry (entry);
2488   if (fd_cdb != -1)
2489     close (fd_cdb);
2490   if (fname)
2491     {
2492       gnupg_remove (fname);
2493       xfree (fname);
2494     }
2495   xfree (newfname);
2496   ksba_crl_release (crl);
2497   xfree (issuer);
2498   xfree (issuer_hash);
2499   xfree (checksum);
2500   xfree (trust_anchor);
2501   return err ? err : err2;
2502 }
2503
2504
2505 /* Print one cached entry E in a human readable format to stream
2506    FP. Return 0 on success. */
2507 static gpg_error_t
2508 list_one_crl_entry (crl_cache_t cache, crl_cache_entry_t e, estream_t fp)
2509 {
2510   struct cdb_find cdbfp;
2511   struct cdb *cdb;
2512   int rc;
2513   int warn = 0;
2514   const unsigned char *s;
2515   unsigned int invalid;
2516
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)
2527     {
2528       es_fputs ("             \t", fp);
2529       for (s=e->authority_issuer; *s; s++)
2530         if (*s == '\x01')
2531           es_fputs ("\n             \t", fp);
2532         else
2533           es_putc (*s, fp);
2534       es_putc ('\n', fp);
2535     }
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]");
2539
2540   invalid = e->invalid;
2541   if ((invalid & INVCRL_TOO_OLD))
2542     {
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"));
2546     }
2547   if ((invalid & INVCRL_UNKNOWN_EXTN))
2548     {
2549       invalid &= ~INVCRL_UNKNOWN_EXTN;
2550       es_fprintf (fp, _(" ERROR: The CRL will not be used "
2551                       "due to an unknown critical extension!\n"));
2552     }
2553   if (invalid)  /* INVCRL_GENERAL or some other bits are set.  */
2554     es_fprintf (fp, _(" ERROR: The CRL will not be used\n"));
2555
2556   cdb = lock_db_file (cache, e);
2557   if (!cdb)
2558     return gpg_error (GPG_ERR_GENERAL);
2559
2560   if (!e->dbfile_checked)
2561     es_fprintf (fp, _(" ERROR: This cached CRL may have been tampered with!\n"));
2562
2563   es_putc ('\n', fp);
2564
2565   rc = cdb_findinit (&cdbfp, cdb, NULL, 0);
2566   while (!rc && (rc=cdb_findnext (&cdbfp)) > 0 )
2567     {
2568       unsigned char keyrecord[256];
2569       unsigned char record[16];
2570       int reason;
2571       int any = 0;
2572       cdbi_t n;
2573       cdbi_t i;
2574
2575       rc = 0;
2576       n = cdb_datalen (cdb);
2577       if (n != 16)
2578         {
2579           log_error (_(" WARNING: invalid cache record length\n"));
2580           warn = 1;
2581           continue;
2582         }
2583
2584       if (cdb_read (cdb, record, n, cdb_datapos (cdb)))
2585         {
2586           log_error (_("problem reading cache record: %s\n"),
2587                      strerror (errno));
2588           warn = 1;
2589           continue;
2590         }
2591
2592       n = cdb_keylen (cdb);
2593       if (n > sizeof keyrecord)
2594         n = sizeof keyrecord;
2595       if (cdb_read (cdb, keyrecord, n, cdb_keypos (cdb)))
2596         {
2597           log_error (_("problem reading cache key: %s\n"), strerror (errno));
2598           warn = 1;
2599           continue;
2600         }
2601
2602       reason = *record;
2603       es_fputs ("  ", fp);
2604       for (i = 0; i < n; i++)
2605         es_fprintf (fp, "%02X", keyrecord[i]);
2606       es_fputs (":\t reasons( ", fp);
2607
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;
2622       if (reason && !any)
2623         es_fputs( "other", fp );
2624
2625       es_fprintf (fp, ") rdate: %.15s\n", record+1);
2626     }
2627   if (rc)
2628     log_error (_("error reading cache entry from db: %s\n"), strerror (rc));
2629
2630   unlock_db_file (cache, e);
2631   es_fprintf (fp, _("End CRL dump\n") );
2632   es_putc ('\n', fp);
2633
2634   return (rc||warn)? gpg_error (GPG_ERR_GENERAL) : 0;
2635 }
2636
2637
2638 /* Print the contents of the CRL CACHE in a human readable format to
2639    stream FP. */
2640 gpg_error_t
2641 crl_cache_list (estream_t fp)
2642 {
2643   crl_cache_t cache = get_current_cache ();
2644   crl_cache_entry_t entry;
2645   gpg_error_t err = 0;
2646
2647   for (entry = cache->entries;
2648        entry && !entry->deleted && !err;
2649        entry = entry->next )
2650     err = list_one_crl_entry (cache, entry, fp);
2651
2652   return err;
2653 }
2654
2655
2656 /* Load the CRL containing the file named FILENAME into our CRL cache. */
2657 gpg_error_t
2658 crl_cache_load (ctrl_t ctrl, const char *filename)
2659 {
2660   gpg_error_t err;
2661   estream_t fp;
2662   ksba_reader_t reader;
2663
2664   fp = es_fopen (filename, "rb");
2665   if (!fp)
2666     {
2667       err = gpg_error_from_errno (errno);
2668       log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2669       return err;
2670     }
2671
2672   err = create_estream_ksba_reader (&reader, fp);
2673   if (!err)
2674     {
2675       err = crl_cache_insert (ctrl, filename, reader);
2676       ksba_reader_release (reader);
2677     }
2678   es_fclose (fp);
2679   return err;
2680 }
2681
2682
2683 /* Locate the corresponding CRL for the certificate CERT, read and
2684    verify the CRL and store it in the cache.  */
2685 gpg_error_t
2686 crl_cache_reload_crl (ctrl_t ctrl, ksba_cert_t cert)
2687 {
2688   gpg_error_t err;
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;
2695   int seq;
2696   gpg_error_t last_err = 0;
2697
2698   /* Loop over all distribution points, get the CRLs and put them into
2699      the cache. */
2700   if (opt.verbose)
2701     log_info ("checking distribution points\n");
2702   seq = 0;
2703   while (xfree (distpoint), xfree (issuername),
2704          !(err = ksba_cert_get_crl_dist_point (cert, seq++,
2705                                                 &distpoint,
2706                                                 &issuername, NULL )))
2707     {
2708       int name_seq;
2709
2710       if (!distpoint && !issuername)
2711         {
2712           if (opt.verbose)
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
2716                     suitable CRL. */
2717         }
2718
2719       /* Get the URIs.  We do this in a loop to iterate over all names
2720          in the crlDP. */
2721       for (name_seq=0; ksba_name_enum (distpoint, name_seq); name_seq++)
2722         {
2723           xfree (distpoint_uri);
2724           distpoint_uri = ksba_name_get_uri (distpoint, name_seq);
2725           if (!distpoint_uri)
2726             continue;
2727
2728           if (!strncmp (distpoint_uri, "ldap:", 5)
2729               || !strncmp (distpoint_uri, "ldaps:", 6))
2730             {
2731               if (opt.ignore_ldap_dp)
2732                 continue;
2733             }
2734           else if (!strncmp (distpoint_uri, "http:", 5)
2735                    || !strncmp (distpoint_uri, "https:", 6))
2736             {
2737               if (opt.ignore_http_dp)
2738                 continue;
2739             }
2740           else
2741             continue; /* Skip unknown schemes. */
2742
2743           any_dist_point = 1;
2744
2745           crl_close_reader (reader);
2746           err = crl_fetch (ctrl, distpoint_uri, &reader);
2747           if (err)
2748             {
2749               log_error (_("crl_fetch via DP failed: %s\n"),
2750                          gpg_strerror (err));
2751               last_err = err;
2752               continue; /* with the next name. */
2753             }
2754
2755           if (opt.verbose)
2756             log_info ("inserting CRL (reader %p)\n", reader);
2757           err = crl_cache_insert (ctrl, distpoint_uri, reader);
2758           if (err)
2759             {
2760               log_error (_("crl_cache_insert via DP failed: %s\n"),
2761                          gpg_strerror (err));
2762               last_err = err;
2763               continue; /* with the next name. */
2764             }
2765           goto leave; /* Ready - we got the CRL. */
2766         }
2767     }
2768   if (gpg_err_code (err) == GPG_ERR_EOF)
2769     err = 0;
2770   if (!err && last_err)
2771     {
2772       err = last_err;
2773       goto leave;
2774     }
2775
2776   /* If we did not found any distpoint, try something reasonable. */
2777   if (!any_dist_point )
2778     {
2779       if (opt.verbose)
2780         log_info ("no distribution point - trying issuer name\n");
2781
2782       issuer = ksba_cert_get_issuer (cert, 0);
2783       if (!issuer)
2784         {
2785           log_error ("oops: issuer missing in certificate\n");
2786           err = gpg_error (GPG_ERR_INV_CERT_OBJ);
2787           goto leave;
2788         }
2789
2790       if (opt.verbose)
2791         log_info ("fetching CRL from default location\n");
2792       crl_close_reader (reader);
2793       err = crl_fetch_default (ctrl, issuer, &reader);
2794       if (err)
2795           {
2796             log_error ("crl_fetch via issuer failed: %s\n",
2797                        gpg_strerror (err));
2798             goto leave;
2799           }
2800
2801       if (opt.verbose)
2802         log_info ("inserting CRL (reader %p)\n", reader);
2803       err = crl_cache_insert (ctrl, "default location(s)", reader);
2804       if (err)
2805         {
2806           log_error (_("crl_cache_insert via issuer failed: %s\n"),
2807                      gpg_strerror (err));
2808           goto leave;
2809         }
2810     }
2811
2812  leave:
2813   crl_close_reader (reader);
2814   xfree (distpoint_uri);
2815   ksba_name_release (distpoint);
2816   ksba_name_release (issuername);
2817   ksba_free (issuer);
2818   return err;
2819 }