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