Bump to 2.4.3
[platform/upstream/gpg2.git] / dirmngr / certcache.c
1 /* certcache.c - Certificate caching
2  * Copyright (C) 2004, 2005, 2007, 2008, 2017 g10 Code GmbH
3  *
4  * This file is part of DirMngr.
5  *
6  * DirMngr is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * DirMngr is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <https://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include <assert.h>
26 #include <sys/types.h>
27 #include <dirent.h>
28 #include <npth.h>
29
30 #include "dirmngr.h"
31 #include "misc.h"
32 #include "../common/ksba-io-support.h"
33 #include "crlfetch.h"
34 #include "certcache.h"
35
36 #define MAX_NONPERM_CACHED_CERTS 1000
37
38 /* Constants used to classify search patterns.  */
39 enum pattern_class
40   {
41     PATTERN_UNKNOWN = 0,
42     PATTERN_EMAIL,
43     PATTERN_EMAIL_SUBSTR,
44     PATTERN_FINGERPRINT16,
45     PATTERN_FINGERPRINT20,
46     PATTERN_SHORT_KEYID,
47     PATTERN_LONG_KEYID,
48     PATTERN_SUBJECT,
49     PATTERN_SERIALNO,
50     PATTERN_SERIALNO_ISSUER,
51     PATTERN_ISSUER,
52     PATTERN_SUBSTR
53   };
54
55
56 /* A certificate cache item.  This consists of a the KSBA cert object
57    and some meta data for easier lookup.  We use a hash table to keep
58    track of all items and use the (randomly distributed) first byte of
59    the fingerprint directly as the hash which makes it pretty easy. */
60 struct cert_item_s
61 {
62   struct cert_item_s *next; /* Next item with the same hash value. */
63   ksba_cert_t cert;         /* The KSBA cert object or NULL is this is
64                                not a valid item.  */
65   unsigned char fpr[20];    /* The fingerprint of this object. */
66   char *issuer_dn;          /* The malloced issuer DN.  */
67   ksba_sexp_t sn;           /* The malloced serial number  */
68   char *subject_dn;         /* The malloced subject DN - maybe NULL.  */
69
70   /* If this field is set the certificate has been taken from some
71    * configuration and shall not be flushed from the cache.  */
72   unsigned int permanent:1;
73
74   /* If this field is set the certificate is trusted.  The actual
75    * value is a (possible) combination of CERTTRUST_CLASS values.  */
76   unsigned int trustclasses:4;
77 };
78 typedef struct cert_item_s *cert_item_t;
79
80 /* The actual cert cache consisting of 256 slots for items indexed by
81    the first byte of the fingerprint.  */
82 static cert_item_t cert_cache[256];
83
84 /* This is the global cache_lock variable. In general locking is not
85    needed but it would take extra efforts to make sure that no
86    indirect use of npth functions is done, so we simply lock it
87    always.  Note: We can't use static initialization, as that is not
88    available through w32-pth.  */
89 static npth_rwlock_t cert_cache_lock;
90
91 /* Flag to track whether the cache has been initialized.  */
92 static int initialization_done;
93
94 /* Total number of non-permanent certificates.  */
95 static unsigned int total_nonperm_certificates;
96
97 /* For each cert class the corresponding bit is set if at least one
98  * certificate of that class is loaded permanetly.  */
99 static unsigned int any_cert_of_class;
100
101
102 #ifdef HAVE_W32_SYSTEM
103 /* We load some functions dynamically.  Provide typedefs for tehse
104  * functions.  */
105 typedef HCERTSTORE (WINAPI *CERTOPENSYSTEMSTORE)
106   (HCRYPTPROV hProv, LPCSTR szSubsystemProtocol);
107 typedef PCCERT_CONTEXT (WINAPI *CERTENUMCERTIFICATESINSTORE)
108   (HCERTSTORE hCertStore, PCCERT_CONTEXT pPrevCertContext);
109 typedef WINBOOL (WINAPI *CERTCLOSESTORE)
110   (HCERTSTORE hCertStore,DWORD dwFlags);
111 #endif /*HAVE_W32_SYSTEM*/
112
113
114
115 \f
116 /* Helper to do the cache locking.  */
117 static void
118 init_cache_lock (void)
119 {
120   int err;
121
122   err = npth_rwlock_init (&cert_cache_lock, NULL);
123   if (err)
124     log_fatal (_("can't initialize certificate cache lock: %s\n"),
125                strerror (err));
126 }
127
128 static void
129 acquire_cache_read_lock (void)
130 {
131   int err;
132
133   err = npth_rwlock_rdlock (&cert_cache_lock);
134   if (err)
135     log_fatal (_("can't acquire read lock on the certificate cache: %s\n"),
136                strerror (err));
137 }
138
139 static void
140 acquire_cache_write_lock (void)
141 {
142   int err;
143
144   err = npth_rwlock_wrlock (&cert_cache_lock);
145   if (err)
146     log_fatal (_("can't acquire write lock on the certificate cache: %s\n"),
147                strerror (err));
148 }
149
150 static void
151 release_cache_lock (void)
152 {
153   int err;
154
155   err = npth_rwlock_unlock (&cert_cache_lock);
156   if (err)
157     log_fatal (_("can't release lock on the certificate cache: %s\n"),
158                strerror (err));
159 }
160
161
162 /* Return false if both serial numbers match.  Can't be used for
163    sorting. */
164 static int
165 compare_serialno (ksba_sexp_t serial1, ksba_sexp_t serial2 )
166 {
167   unsigned char *a = serial1;
168   unsigned char *b = serial2;
169   return cmp_simple_canon_sexp (a, b);
170 }
171
172
173
174 /* Return a malloced canonical S-Expression with the serial number
175  * converted from the hex string HEXSN.  Return NULL on memory
176  * error.  */
177 ksba_sexp_t
178 hexsn_to_sexp (const char *hexsn)
179 {
180   char *buffer, *p;
181   size_t len;
182   char numbuf[40];
183
184   len = unhexify (NULL, hexsn);
185   snprintf (numbuf, sizeof numbuf, "(%u:", (unsigned int)len);
186   buffer = xtrymalloc (strlen (numbuf) + len + 2 );
187   if (!buffer)
188     return NULL;
189   p = stpcpy (buffer, numbuf);
190   len = unhexify (p, hexsn);
191   p[len] = ')';
192   p[len+1] = 0;
193
194   return buffer;
195 }
196
197
198 /* Compute the fingerprint of the certificate CERT and put it into
199    the 20 bytes large buffer DIGEST.  Return address of this buffer.  */
200 unsigned char *
201 cert_compute_fpr (ksba_cert_t cert, unsigned char *digest)
202 {
203   gpg_error_t err;
204   gcry_md_hd_t md;
205
206   err = gcry_md_open (&md, GCRY_MD_SHA1, 0);
207   if (err)
208     log_fatal ("gcry_md_open failed: %s\n", gpg_strerror (err));
209
210   err = ksba_cert_hash (cert, 0, HASH_FNC, md);
211   if (err)
212     {
213       log_error ("oops: ksba_cert_hash failed: %s\n", gpg_strerror (err));
214       memset (digest, 0xff, 20); /* Use a dummy value. */
215     }
216   else
217     {
218       gcry_md_final (md);
219       memcpy (digest, gcry_md_read (md, GCRY_MD_SHA1), 20);
220     }
221   gcry_md_close (md);
222   return digest;
223 }
224
225
226 \f
227 /* Cleanup one slot.  This releases all resourses but keeps the actual
228    slot in the cache marked for reuse. */
229 static void
230 clean_cache_slot (cert_item_t ci)
231 {
232   ksba_cert_t cert;
233
234   if (!ci->cert)
235     return; /* Already cleaned.  */
236
237   ksba_free (ci->sn);
238   ci->sn = NULL;
239   ksba_free (ci->issuer_dn);
240   ci->issuer_dn = NULL;
241   ksba_free (ci->subject_dn);
242   ci->subject_dn = NULL;
243   cert = ci->cert;
244   ci->cert = NULL;
245
246   ci->permanent = 0;
247   ci->trustclasses = 0;
248
249   ksba_cert_release (cert);
250 }
251
252
253 /* Put the certificate CERT into the cache.  It is assumed that the
254  * cache is locked while this function is called.
255  *
256  * FROM_CONFIG indicates that CERT is a permanent certificate and
257  * should stay in the cache.  IS_TRUSTED requests that the trusted
258  * flag is set for the certificate; a value of 1 indicates the
259  * cert is trusted due to GnuPG mechanisms, a value of 2 indicates
260  * that it is trusted because it has been taken from the system's
261  * store of trusted certificates.  If FPR_BUFFER is not NULL the
262  * fingerprint of the certificate will be stored there.  FPR_BUFFER
263  * needs to point to a buffer of at least 20 bytes.  The fingerprint
264  * will be stored on success or when the function returns
265  * GPG_ERR_DUP_VALUE or GPG_ERR_NOT_ENABLED.  */
266 static gpg_error_t
267 put_cert (ksba_cert_t cert, int permanent, unsigned int trustclass,
268           void *fpr_buffer)
269 {
270   unsigned char help_fpr_buffer[20], *fpr;
271   cert_item_t ci;
272   fingerprint_list_t ignored;
273
274   /* Do not keep expired certificates in the permanent cache.  */
275   if (permanent && !opt.debug_cache_expired_certs)
276     {
277       ksba_isotime_t not_after;
278       ksba_isotime_t current_time;
279
280       if (ksba_cert_get_validity (cert, 1, not_after))
281         return gpg_error (GPG_ERR_BAD_CERT);
282
283       gnupg_get_isotime (current_time);
284
285       if (*not_after && strcmp (current_time, not_after) > 0)
286         return gpg_error (GPG_ERR_CERT_EXPIRED);
287     }
288
289   fpr = fpr_buffer? fpr_buffer : &help_fpr_buffer;
290
291   /* If we already reached the caching limit, drop a couple of certs
292    * from the cache.  Our dropping strategy is simple: We keep a
293    * static index counter and use this to start looking for
294    * certificates, then we drop 5 percent of the oldest certificates
295    * starting at that index.  For a large cache this is a fair way of
296    * removing items.  An LRU strategy would be better of course.
297    * Because we append new entries to the head of the list and we want
298    * to remove old ones first, we need to do this from the tail.  The
299    * implementation is not very efficient but compared to the long
300    * time it takes to retrieve a certificate from an external resource
301    * it seems to be reasonable.  */
302   if (!permanent && total_nonperm_certificates >= MAX_NONPERM_CACHED_CERTS)
303     {
304       static int idx;
305       cert_item_t ci_mark;
306       int i;
307       unsigned int drop_count;
308
309       drop_count = MAX_NONPERM_CACHED_CERTS / 20;
310       if (drop_count < 2)
311         drop_count = 2;
312
313       log_info (_("dropping %u certificates from the cache\n"), drop_count);
314       assert (idx < 256);
315       for (i=idx; drop_count; i = ((i+1)%256))
316         {
317           ci_mark = NULL;
318           for (ci = cert_cache[i]; ci; ci = ci->next)
319             if (ci->cert && !ci->permanent)
320               ci_mark = ci;
321           if (ci_mark)
322             {
323               clean_cache_slot (ci_mark);
324               drop_count--;
325               total_nonperm_certificates--;
326             }
327         }
328       if (i==idx)
329         idx++;
330       else
331         idx = i;
332       idx %= 256;
333     }
334
335   cert_compute_fpr (cert, fpr);
336   /* Compare against the list of to be ignored certificates.  */
337   for (ignored = opt.ignored_certs; ignored; ignored = ignored->next)
338     if (ignored->binlen == 20 && !memcmp (fpr, ignored->hexfpr, 20))
339       {
340         /* We are configured not to use this certificate.  */
341         return gpg_error (GPG_ERR_NOT_ENABLED);
342       }
343
344   for (ci=cert_cache[*fpr]; ci; ci = ci->next)
345     if (ci->cert && !memcmp (ci->fpr, fpr, 20))
346       return gpg_error (GPG_ERR_DUP_VALUE);
347   /* Try to reuse an existing entry.  */
348   for (ci=cert_cache[*fpr]; ci; ci = ci->next)
349     if (!ci->cert)
350       break;
351   if (!ci)
352     { /* No: Create a new entry.  */
353       ci = xtrycalloc (1, sizeof *ci);
354       if (!ci)
355         return gpg_error_from_errno (errno);
356       ci->next = cert_cache[*fpr];
357       cert_cache[*fpr] = ci;
358     }
359
360   ksba_cert_ref (cert);
361   ci->cert = cert;
362   memcpy (ci->fpr, fpr, 20);
363   ci->sn = ksba_cert_get_serial (cert);
364   ci->issuer_dn = ksba_cert_get_issuer (cert, 0);
365   if (!ci->issuer_dn || !ci->sn)
366     {
367       clean_cache_slot (ci);
368       return gpg_error (GPG_ERR_INV_CERT_OBJ);
369     }
370   ci->subject_dn = ksba_cert_get_subject (cert, 0);
371   ci->permanent = !!permanent;
372   ci->trustclasses = trustclass;
373
374   if (permanent)
375     any_cert_of_class |= trustclass;
376   else
377     total_nonperm_certificates++;
378
379   return 0;
380 }
381
382
383 /* Load certificates from the directory DIRNAME.  All certificates
384    matching the pattern "*.crt" or "*.der"  are loaded.  We assume that
385    certificates are DER encoded and not PEM encapsulated.  The cache
386    should be in a locked state when calling this function.  */
387 static gpg_error_t
388 load_certs_from_dir (const char *dirname, unsigned int trustclass)
389 {
390   gpg_error_t err;
391   gnupg_dir_t dir;
392   gnupg_dirent_t ep;
393   char *p;
394   size_t n;
395   estream_t fp;
396   ksba_reader_t reader;
397   ksba_cert_t cert;
398   char *fname = NULL;
399
400   dir = gnupg_opendir (dirname);
401   if (!dir)
402     {
403       return 0; /* We do not consider this a severe error.  */
404     }
405
406   while ( (ep = gnupg_readdir (dir)) )
407     {
408       p = ep->d_name;
409       if (*p == '.' || !*p)
410         continue; /* Skip any hidden files and invalid entries.  */
411       n = strlen (p);
412       if ( n < 5 || (strcmp (p+n-4,".crt") && strcmp (p+n-4,".der")))
413         continue; /* Not the desired "*.crt" or "*.der" pattern.  */
414
415       xfree (fname);
416       fname = make_filename (dirname, p, NULL);
417       fp = es_fopen (fname, "rb");
418       if (!fp)
419         {
420           log_error (_("can't open '%s': %s\n"),
421                      fname, strerror (errno));
422           continue;
423         }
424
425       err = create_estream_ksba_reader (&reader, fp);
426       if (err)
427         {
428           es_fclose (fp);
429           continue;
430         }
431
432       err = ksba_cert_new (&cert);
433       if (!err)
434         err = ksba_cert_read_der (cert, reader);
435       ksba_reader_release (reader);
436       es_fclose (fp);
437       if (err)
438         {
439           log_error (_("can't parse certificate '%s': %s\n"),
440                      fname, gpg_strerror (err));
441           ksba_cert_release (cert);
442           continue;
443         }
444
445       err = put_cert (cert, 1, trustclass, NULL);
446       if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
447         log_info (_("certificate '%s' already cached\n"), fname);
448       else if (!err)
449         {
450           if ((trustclass & CERTTRUST_CLASS_CONFIG))
451             http_register_cfg_ca (fname);
452
453           if (trustclass)
454             log_info (_("trusted certificate '%s' loaded\n"), fname);
455           else
456             log_info (_("certificate '%s' loaded\n"), fname);
457           if (opt.verbose)
458             {
459               p = get_fingerprint_hexstring_colon (cert);
460               log_info (_("  SHA1 fingerprint = %s\n"), p);
461               xfree (p);
462
463               cert_log_name (_("   issuer ="), cert);
464               cert_log_subject (_("  subject ="), cert);
465             }
466         }
467       else if (gpg_err_code (err) == GPG_ERR_NOT_ENABLED)
468         log_info ("certificate '%s' skipped due to configuration\n", fname);
469       else
470         log_error (_("error loading certificate '%s': %s\n"),
471                      fname, gpg_strerror (err));
472       ksba_cert_release (cert);
473     }
474
475   xfree (fname);
476   gnupg_closedir (dir);
477   return 0;
478 }
479
480
481 /* Load certificates from FILE.  The certificates are expected to be
482  * PEM encoded so that it is possible to load several certificates.
483  * TRUSTCLASSES is used to mark the certificates as trusted.  The
484  * cache should be in a locked state when calling this function.
485  * NO_ERROR repalces an error message when FNAME was not found by an
486  * information message.  */
487 static gpg_error_t
488 load_certs_from_file (const char *fname, unsigned int trustclasses,
489                       int no_error)
490 {
491   gpg_error_t err;
492   estream_t fp = NULL;
493   gnupg_ksba_io_t ioctx = NULL;
494   ksba_reader_t reader;
495   ksba_cert_t cert = NULL;
496
497   fp = es_fopen (fname, "rb");
498   if (!fp)
499     {
500       err = gpg_error_from_syserror ();
501       if (gpg_err_code (err) == GPG_ERR_ENONET && no_error)
502         log_info (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
503       else
504         log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
505       goto leave;
506     }
507
508   err = gnupg_ksba_create_reader (&ioctx,
509                                   (GNUPG_KSBA_IO_AUTODETECT
510                                    | GNUPG_KSBA_IO_MULTIPEM),
511                                   fp, &reader);
512   if (err)
513     {
514       log_error ("can't create reader: %s\n", gpg_strerror (err));
515       goto leave;
516     }
517
518   /* Loop to read all certificates from the file.  */
519   do
520     {
521       ksba_cert_release (cert);
522       cert = NULL;
523       err = ksba_cert_new (&cert);
524       if (!err)
525         err = ksba_cert_read_der (cert, reader);
526       if (err)
527         {
528           if (gpg_err_code (err) == GPG_ERR_EOF)
529             err = 0;
530           else
531             log_error (_("can't parse certificate '%s': %s\n"),
532                        fname, gpg_strerror (err));
533           goto leave;
534         }
535
536       err = put_cert (cert, 1, trustclasses, NULL);
537       if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
538         log_info (_("certificate '%s' already cached\n"), fname);
539       else if (gpg_err_code (err) == GPG_ERR_NOT_ENABLED)
540         log_info ("certificate '%s' skipped due to configuration\n", fname);
541       else if (err)
542         log_error (_("error loading certificate '%s': %s\n"),
543                    fname, gpg_strerror (err));
544       else if (opt.verbose > 1)
545         {
546           char *p;
547
548           log_info (_("trusted certificate '%s' loaded\n"), fname);
549           p = get_fingerprint_hexstring_colon (cert);
550           log_info (_("  SHA1 fingerprint = %s\n"), p);
551           xfree (p);
552
553           cert_log_name    (_("   issuer ="), cert);
554           cert_log_subject (_("  subject ="), cert);
555         }
556
557       ksba_reader_clear (reader, NULL, NULL);
558     }
559   while (!gnupg_ksba_reader_eof_seen (ioctx));
560
561  leave:
562   ksba_cert_release (cert);
563   gnupg_ksba_destroy_reader (ioctx);
564   es_fclose (fp);
565
566   return err;
567 }
568
569
570 #ifdef HAVE_W32_SYSTEM
571 /* Load all certificates from the Windows store named STORENAME.  All
572  * certificates are considered to be system provided trusted
573  * certificates.  The cache should be in a locked state when calling
574  * this function.  */
575 static void
576 load_certs_from_w32_store (const char *storename)
577 {
578   static int init_done;
579   static CERTOPENSYSTEMSTORE pCertOpenSystemStore;
580   static CERTENUMCERTIFICATESINSTORE pCertEnumCertificatesInStore;
581   static CERTCLOSESTORE pCertCloseStore;
582   gpg_error_t err;
583   HCERTSTORE w32store;
584   const CERT_CONTEXT *w32cert;
585   ksba_cert_t cert = NULL;
586   unsigned int count = 0;
587
588   /* Initialize on the first use.  */
589   if (!init_done)
590     {
591       static HANDLE hCrypt32;
592
593       init_done = 1;
594
595       hCrypt32 = LoadLibrary ("Crypt32.dll");
596       if (!hCrypt32)
597         {
598           log_error ("can't load Crypt32.dll: %s\n",  w32_strerror (-1));
599           return;
600         }
601
602       pCertOpenSystemStore = (CERTOPENSYSTEMSTORE)
603         (void*)GetProcAddress (hCrypt32, "CertOpenSystemStoreA");
604       pCertEnumCertificatesInStore = (CERTENUMCERTIFICATESINSTORE)
605         (void*)GetProcAddress (hCrypt32, "CertEnumCertificatesInStore");
606       pCertCloseStore = (CERTCLOSESTORE)
607         (void*)GetProcAddress (hCrypt32, "CertCloseStore");
608       if (   !pCertOpenSystemStore
609           || !pCertEnumCertificatesInStore
610           || !pCertCloseStore)
611         {
612           log_error ("can't load crypt32.dll: %s\n", "missing function");
613           pCertOpenSystemStore = NULL;
614         }
615     }
616
617   if (!pCertOpenSystemStore)
618     return;  /* Not initialized.  */
619
620
621   w32store = pCertOpenSystemStore (0, storename);
622   if (!w32store)
623     {
624       log_error ("can't open certificate store '%s': %s\n",
625                  storename, w32_strerror (-1));
626       return;
627     }
628
629   w32cert = NULL;
630   while ((w32cert = pCertEnumCertificatesInStore (w32store, w32cert)))
631     {
632       if (w32cert->dwCertEncodingType == X509_ASN_ENCODING)
633         {
634           ksba_cert_release (cert);
635           cert = NULL;
636           err = ksba_cert_new (&cert);
637           if (!err)
638             err = ksba_cert_init_from_mem (cert,
639                                            w32cert->pbCertEncoded,
640                                            w32cert->cbCertEncoded);
641           if (err)
642             {
643               log_error (_("can't parse certificate '%s': %s\n"),
644                          storename, gpg_strerror (err));
645               break;
646             }
647
648           err = put_cert (cert, 1, CERTTRUST_CLASS_SYSTEM, NULL);
649           if (!err)
650             count++;
651           if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
652             {
653               if (DBG_X509)
654                 log_debug (_("certificate '%s' already cached\n"), storename);
655             }
656           else if (gpg_err_code (err) == GPG_ERR_NOT_ENABLED)
657             log_info ("certificate '%s' skipped due to configuration\n",
658                       storename);
659           else if (err)
660             log_error (_("error loading certificate '%s': %s\n"),
661                        storename, gpg_strerror (err));
662           else if (opt.verbose > 1)
663             {
664               char *p;
665
666               log_info (_("trusted certificate '%s' loaded\n"), storename);
667               p = get_fingerprint_hexstring_colon (cert);
668               log_info (_("  SHA1 fingerprint = %s\n"), p);
669               xfree (p);
670
671               cert_log_name    (_("   issuer ="), cert);
672               cert_log_subject (_("  subject ="), cert);
673             }
674         }
675     }
676
677   ksba_cert_release (cert);
678   pCertCloseStore (w32store, 0);
679
680   if (DBG_X509)
681     log_debug ("number of certs loaded from store '%s': %u\n",
682                storename, count);
683
684 }
685 #endif /*HAVE_W32_SYSTEM*/
686
687
688 /* Load the trusted certificates provided by the system.  */
689 static gpg_error_t
690 load_certs_from_system (void)
691 {
692 #ifdef HAVE_W32_SYSTEM
693
694   load_certs_from_w32_store ("ROOT");
695   load_certs_from_w32_store ("CA");
696
697   return 0;
698
699 #else /*!HAVE_W32_SYSTEM*/
700
701   /* A list of certificate bundles to try.  */
702   static struct {
703     const char *name;
704   } table[] = {
705 #ifdef DEFAULT_TRUST_STORE_FILE
706     { DEFAULT_TRUST_STORE_FILE }
707 #else
708     { "/etc/ssl/ca-bundle.pem" },
709     { "/etc/ssl/certs/ca-certificates.crt" },
710     { "/etc/pki/tls/cert.pem" },
711     { "/usr/local/share/certs/ca-root-nss.crt" },
712     { "/etc/ssl/cert.pem" }
713 #endif /*!DEFAULT_TRUST_STORE_FILE*/
714   };
715   int idx;
716   gpg_error_t err = 0;
717
718   for (idx=0; idx < DIM (table); idx++)
719     if (!gnupg_access (table[idx].name, F_OK))
720       {
721         /* Take the first available bundle.  */
722         err = load_certs_from_file (table[idx].name, CERTTRUST_CLASS_SYSTEM, 0);
723         break;
724       }
725
726   return err;
727 #endif /*!HAVE_W32_SYSTEM*/
728 }
729
730
731 /* Initialize the certificate cache if not yet done.  */
732 void
733 cert_cache_init (strlist_t hkp_cacerts)
734 {
735   char *fname;
736   strlist_t sl;
737
738   if (initialization_done)
739     return;
740   init_cache_lock ();
741   acquire_cache_write_lock ();
742
743   load_certs_from_system ();
744
745   fname = make_filename_try (gnupg_sysconfdir (), "trusted-certs", NULL);
746   if (fname)
747     load_certs_from_dir (fname, CERTTRUST_CLASS_CONFIG);
748   xfree (fname);
749
750   fname = make_filename_try (gnupg_sysconfdir (), "extra-certs", NULL);
751   if (fname)
752     load_certs_from_dir (fname, 0);
753   xfree (fname);
754
755   /* Put the special pool certificate into our store.  This is
756    * currently only used with ntbtls.  For GnuTLS http_session_new
757    * unfortunately loads that certificate directly from the file.  */
758   /* Disabled for 2.3.2 because the service had to be shutdown.  */
759   /* fname = make_filename_try (gnupg_datadir (), */
760   /*                            "sks-keyservers.netCA.pem", NULL); */
761   /* if (fname) */
762   /*   load_certs_from_file (fname, CERTTRUST_CLASS_HKPSPOOL, 1); */
763   /* xfree (fname); */
764
765   for (sl = hkp_cacerts; sl; sl = sl->next)
766     load_certs_from_file (sl->d, CERTTRUST_CLASS_HKP, 0);
767
768   initialization_done = 1;
769   release_cache_lock ();
770
771   cert_cache_print_stats (NULL);
772 }
773
774 /* Deinitialize the certificate cache.  With FULL set to true even the
775    unused certificate slots are released. */
776 void
777 cert_cache_deinit (int full)
778 {
779   cert_item_t ci, ci2;
780   int i;
781
782   if (!initialization_done)
783     return;
784
785   acquire_cache_write_lock ();
786
787   for (i=0; i < 256; i++)
788     for (ci=cert_cache[i]; ci; ci = ci->next)
789       clean_cache_slot (ci);
790
791   if (full)
792     {
793       for (i=0; i < 256; i++)
794         {
795           for (ci=cert_cache[i]; ci; ci = ci2)
796             {
797               ci2 = ci->next;
798               xfree (ci);
799             }
800           cert_cache[i] = NULL;
801         }
802     }
803
804   http_register_cfg_ca (NULL);
805
806   total_nonperm_certificates = 0;
807   any_cert_of_class = 0;
808   initialization_done = 0;
809   release_cache_lock ();
810 }
811
812 /* Print some statistics to the log file.  */
813 void
814 cert_cache_print_stats (ctrl_t ctrl)
815 {
816   cert_item_t ci;
817   int idx;
818   unsigned int n_nonperm = 0;
819   unsigned int n_permanent = 0;
820   unsigned int n_trusted = 0;
821   unsigned int n_trustclass_system = 0;
822   unsigned int n_trustclass_config = 0;
823   unsigned int n_trustclass_hkp = 0;
824   unsigned int n_trustclass_hkpspool = 0;
825
826   acquire_cache_read_lock ();
827   for (idx = 0; idx < 256; idx++)
828     for (ci=cert_cache[idx]; ci; ci = ci->next)
829       if (ci->cert)
830         {
831           if (ci->permanent)
832             n_permanent++;
833           else
834             n_nonperm++;
835           if (ci->trustclasses)
836             {
837               n_trusted++;
838               if ((ci->trustclasses & CERTTRUST_CLASS_SYSTEM))
839                 n_trustclass_system++;
840               if ((ci->trustclasses & CERTTRUST_CLASS_CONFIG))
841                 n_trustclass_config++;
842               if ((ci->trustclasses & CERTTRUST_CLASS_HKP))
843                 n_trustclass_hkp++;
844               if ((ci->trustclasses & CERTTRUST_CLASS_HKPSPOOL))
845                 n_trustclass_hkpspool++;
846             }
847         }
848
849   release_cache_lock ();
850
851   dirmngr_status_helpf (ctrl,
852                  _("permanently loaded certificates: %u\n"),
853                         n_permanent);
854   dirmngr_status_helpf (ctrl,
855                  _("    runtime cached certificates: %u\n"),
856                         n_nonperm);
857   dirmngr_status_helpf (ctrl,
858                  _("           trusted certificates: %u (%u,%u,%u,%u)\n"),
859                         n_trusted,
860                         n_trustclass_system,
861                         n_trustclass_config,
862                         n_trustclass_hkp,
863                         n_trustclass_hkpspool);
864 }
865
866
867 /* Return true if any cert of a class in MASK is permanently
868  * loaded.  */
869 int
870 cert_cache_any_in_class (unsigned int mask)
871 {
872   return !!(any_cert_of_class & mask);
873 }
874
875
876 /* Put CERT into the certificate cache.  */
877 gpg_error_t
878 cache_cert (ksba_cert_t cert)
879 {
880   gpg_error_t err;
881
882   acquire_cache_write_lock ();
883   err = put_cert (cert, 0, 0, NULL);
884   release_cache_lock ();
885   if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
886     log_info (_("certificate already cached\n"));
887   else if (!err)
888     log_info (_("certificate cached\n"));
889   else if (gpg_err_code (err) == GPG_ERR_NOT_ENABLED)
890     log_info ("certificate skipped due to configuration\n");
891   else
892     log_error (_("error caching certificate: %s\n"), gpg_strerror (err));
893   return err;
894 }
895
896
897 /* Put CERT into the certificate cache and store the fingerprint of
898    the certificate into FPR_BUFFER.  If the certificate is already in
899    the cache do not print a warning; just store the
900    fingerprint. FPR_BUFFER needs to be at least 20 bytes. */
901 gpg_error_t
902 cache_cert_silent (ksba_cert_t cert, void *fpr_buffer)
903 {
904   gpg_error_t err;
905
906   acquire_cache_write_lock ();
907   err = put_cert (cert, 0, 0, fpr_buffer);
908   release_cache_lock ();
909   if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
910     err = 0;
911
912   if (gpg_err_code (err) == GPG_ERR_NOT_ENABLED)
913     log_info ("certificate skipped due to configuration\n");
914   else if (err)
915     log_error (_("error caching certificate: %s\n"), gpg_strerror (err));
916   return err;
917 }
918
919
920 \f
921 /* Return a certificate object for the given fingerprint.  FPR is
922    expected to be a 20 byte binary SHA-1 fingerprint.  If no matching
923    certificate is available in the cache NULL is returned.  The caller
924    must release a returned certificate.  Note that although we are
925    using reference counting the caller should not just compare the
926    pointers to check for identical certificates. */
927 ksba_cert_t
928 get_cert_byfpr (const unsigned char *fpr)
929 {
930   cert_item_t ci;
931
932   acquire_cache_read_lock ();
933   for (ci=cert_cache[*fpr]; ci; ci = ci->next)
934     if (ci->cert && !memcmp (ci->fpr, fpr, 20))
935       {
936         ksba_cert_ref (ci->cert);
937         release_cache_lock ();
938         return ci->cert;
939       }
940
941   release_cache_lock ();
942   return NULL;
943 }
944
945 /* Return a certificate object for the given fingerprint.  STRING is
946    expected to be a SHA-1 fingerprint in standard hex notation with or
947    without colons.  If no matching certificate is available in the
948    cache NULL is returned.  The caller must release a returned
949    certificate.  Note that although we are using reference counting
950    the caller should not just compare the pointers to check for
951    identical certificates. */
952 ksba_cert_t
953 get_cert_byhexfpr (const char *string)
954 {
955   unsigned char fpr[20];
956   const char *s;
957   int i;
958
959   if (strchr (string, ':'))
960     {
961       for (s=string,i=0; i < 20 && hexdigitp (s) && hexdigitp(s+1);)
962         {
963           if (s[2] && s[2] != ':')
964             break; /* Invalid string. */
965           fpr[i++] = xtoi_2 (s);
966           s += 2;
967           if (i!= 20 && *s == ':')
968             s++;
969         }
970     }
971   else
972     {
973       for (s=string,i=0; i < 20 && hexdigitp (s) && hexdigitp(s+1); s+=2 )
974         fpr[i++] = xtoi_2 (s);
975     }
976   if (i!=20 || *s)
977     {
978       log_error (_("invalid SHA1 fingerprint string '%s'\n"), string);
979       return NULL;
980     }
981
982   return get_cert_byfpr (fpr);
983 }
984
985
986
987 /* Return the certificate matching ISSUER_DN and SERIALNO.  */
988 ksba_cert_t
989 get_cert_bysn (const char *issuer_dn, ksba_sexp_t serialno)
990 {
991   /* Simple and inefficient implementation.   fixme! */
992   cert_item_t ci;
993   int i;
994
995   acquire_cache_read_lock ();
996   for (i=0; i < 256; i++)
997     {
998       for (ci=cert_cache[i]; ci; ci = ci->next)
999         if (ci->cert && !strcmp (ci->issuer_dn, issuer_dn)
1000             && !compare_serialno (ci->sn, serialno))
1001           {
1002             ksba_cert_ref (ci->cert);
1003             release_cache_lock ();
1004             return ci->cert;
1005           }
1006     }
1007
1008   release_cache_lock ();
1009   return NULL;
1010 }
1011
1012
1013 /* Return the certificate matching ISSUER_DN.  SEQ should initially be
1014    set to 0 and bumped up to get the next issuer with that DN. */
1015 ksba_cert_t
1016 get_cert_byissuer (const char *issuer_dn, unsigned int seq)
1017 {
1018   /* Simple and very inefficient implementation and API.  fixme! */
1019   cert_item_t ci;
1020   int i;
1021
1022   acquire_cache_read_lock ();
1023   for (i=0; i < 256; i++)
1024     {
1025       for (ci=cert_cache[i]; ci; ci = ci->next)
1026         if (ci->cert && !strcmp (ci->issuer_dn, issuer_dn))
1027           if (!seq--)
1028             {
1029               ksba_cert_ref (ci->cert);
1030               release_cache_lock ();
1031               return ci->cert;
1032             }
1033     }
1034
1035   release_cache_lock ();
1036   return NULL;
1037 }
1038
1039
1040 /* Return the certificate matching SUBJECT_DN.  SEQ should initially be
1041    set to 0 and bumped up to get the next subject with that DN. */
1042 ksba_cert_t
1043 get_cert_bysubject (const char *subject_dn, unsigned int seq)
1044 {
1045   /* Simple and very inefficient implementation and API.  fixme! */
1046   cert_item_t ci;
1047   int i;
1048
1049   if (!subject_dn)
1050     return NULL;
1051
1052   acquire_cache_read_lock ();
1053   for (i=0; i < 256; i++)
1054     {
1055       for (ci=cert_cache[i]; ci; ci = ci->next)
1056         if (ci->cert && ci->subject_dn
1057             && !strcmp (ci->subject_dn, subject_dn))
1058           if (!seq--)
1059             {
1060               ksba_cert_ref (ci->cert);
1061               release_cache_lock ();
1062               return ci->cert;
1063             }
1064     }
1065
1066   release_cache_lock ();
1067   return NULL;
1068 }
1069
1070
1071
1072 /* Return a value describing the class of PATTERN.  The offset of
1073    the actual string to be used for the comparison is stored at
1074    R_OFFSET.  The offset of the serialnumer is stored at R_SN_OFFSET. */
1075 static enum pattern_class
1076 classify_pattern (const char *pattern, size_t *r_offset, size_t *r_sn_offset)
1077 {
1078   enum pattern_class result;
1079   const char *s;
1080   int hexprefix = 0;
1081   int hexlength;
1082
1083   *r_offset = *r_sn_offset = 0;
1084
1085   /* Skip leading spaces. */
1086   for(s = pattern; *s && spacep (s); s++ )
1087     ;
1088
1089   switch (*s)
1090     {
1091     case 0:  /* Empty string is an error. */
1092       result = PATTERN_UNKNOWN;
1093       break;
1094
1095     case '.': /* An email address, compare from end.  */
1096       result = PATTERN_UNKNOWN;  /* Not implemented.  */
1097       break;
1098
1099     case '<': /* An email address.  */
1100       result = PATTERN_EMAIL;
1101       s++;
1102       break;
1103
1104     case '@': /* Part of an email address.  */
1105       result = PATTERN_EMAIL_SUBSTR;
1106       s++;
1107       break;
1108
1109     case '=':  /* Exact compare. */
1110       result = PATTERN_UNKNOWN; /* Does not make sense for X.509.  */
1111       break;
1112
1113     case '*':  /* Case insensitive substring search.  */
1114       result = PATTERN_SUBSTR;
1115       s++;
1116       break;
1117
1118     case '+':  /* Compare individual words. */
1119       result = PATTERN_UNKNOWN;  /* Not implemented.  */
1120       break;
1121
1122     case '/': /* Subject's DN. */
1123       s++;
1124       if (!*s || spacep (s))
1125         result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */
1126       else
1127         result = PATTERN_SUBJECT;
1128       break;
1129
1130     case '#': /* Serial number or issuer DN. */
1131       {
1132         const char *si;
1133
1134         s++;
1135         if ( *s == '/')
1136           {
1137             /* An issuer's DN is indicated by "#/" */
1138             s++;
1139             if (!*s || spacep (s))
1140               result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */
1141             else
1142               result = PATTERN_ISSUER;
1143           }
1144         else
1145           { /* Serialnumber + optional issuer ID. */
1146             for (si=s; *si && *si != '/'; si++)
1147               if (!strchr("01234567890abcdefABCDEF", *si))
1148                 break;
1149             if (*si && *si != '/')
1150               result = PATTERN_UNKNOWN; /* Invalid digit in serial number. */
1151             else
1152               {
1153                 *r_sn_offset = s - pattern;
1154                 if (!*si)
1155                   result = PATTERN_SERIALNO;
1156                 else
1157                   {
1158                     s = si+1;
1159                     if (!*s || spacep (s))
1160                       result = PATTERN_UNKNOWN; /* No DN or prefixed
1161                                                    with a space. */
1162                     else
1163                       result = PATTERN_SERIALNO_ISSUER;
1164                   }
1165               }
1166           }
1167       }
1168       break;
1169
1170     case ':': /* Unified fingerprint. */
1171       {
1172         const char *se, *si;
1173         int i;
1174
1175         se = strchr (++s, ':');
1176         if (!se)
1177           result = PATTERN_UNKNOWN;
1178         else
1179           {
1180             for (i=0, si=s; si < se; si++, i++ )
1181               if (!strchr("01234567890abcdefABCDEF", *si))
1182                 break;
1183             if ( si < se )
1184               result = PATTERN_UNKNOWN; /* Invalid digit. */
1185             else if (i == 32)
1186               result = PATTERN_FINGERPRINT16;
1187             else if (i == 40)
1188               result = PATTERN_FINGERPRINT20;
1189             else
1190               result = PATTERN_UNKNOWN; /* Invalid length for a fingerprint. */
1191           }
1192       }
1193       break;
1194
1195     case '&': /* Keygrip. */
1196       result = PATTERN_UNKNOWN;  /* Not implemented.  */
1197       break;
1198
1199     default:
1200       if (s[0] == '0' && s[1] == 'x')
1201         {
1202           hexprefix = 1;
1203           s += 2;
1204         }
1205
1206       hexlength = strspn(s, "0123456789abcdefABCDEF");
1207
1208       /* Check if a hexadecimal number is terminated by EOS or blank. */
1209       if (hexlength && s[hexlength] && !spacep (s+hexlength))
1210         {
1211           /* If the "0x" prefix is used a correct termination is required. */
1212           if (hexprefix)
1213             {
1214               result = PATTERN_UNKNOWN;
1215               break; /* switch */
1216             }
1217           hexlength = 0;  /* Not a hex number.  */
1218         }
1219
1220       if (hexlength == 8 || (!hexprefix && hexlength == 9 && *s == '0'))
1221         {
1222           if (hexlength == 9)
1223             s++;
1224           result = PATTERN_SHORT_KEYID;
1225         }
1226       else if (hexlength == 16 || (!hexprefix && hexlength == 17 && *s == '0'))
1227         {
1228           if (hexlength == 17)
1229             s++;
1230           result = PATTERN_LONG_KEYID;
1231         }
1232       else if (hexlength == 32 || (!hexprefix && hexlength == 33 && *s == '0'))
1233         {
1234           if (hexlength == 33)
1235             s++;
1236           result = PATTERN_FINGERPRINT16;
1237         }
1238       else if (hexlength == 40 || (!hexprefix && hexlength == 41 && *s == '0'))
1239         {
1240           if (hexlength == 41)
1241             s++;
1242           result = PATTERN_FINGERPRINT20;
1243         }
1244       else if (!hexprefix)
1245         {
1246           /* The fingerprints used with X.509 are often delimited by
1247              colons, so we try to single this case out. */
1248           result = PATTERN_UNKNOWN;
1249           hexlength = strspn (s, ":0123456789abcdefABCDEF");
1250           if (hexlength == 59 && (!s[hexlength] || spacep (s+hexlength)))
1251             {
1252               int i, c;
1253
1254               for (i=0; i < 20; i++, s += 3)
1255                 {
1256                   c = hextobyte(s);
1257                   if (c == -1 || (i < 19 && s[2] != ':'))
1258                     break;
1259                 }
1260               if (i == 20)
1261                 result = PATTERN_FINGERPRINT20;
1262             }
1263           if (result == PATTERN_UNKNOWN) /* Default to substring match. */
1264             {
1265               result = PATTERN_SUBSTR;
1266             }
1267         }
1268       else /* A hex number with a prefix but with a wrong length.  */
1269         result = PATTERN_UNKNOWN;
1270     }
1271
1272   if (result != PATTERN_UNKNOWN)
1273     *r_offset = s - pattern;
1274   return result;
1275 }
1276
1277
1278
1279 /* Given PATTERN, which is a string as used by GnuPG to specify a
1280    certificate, return all matching certificates by calling the
1281    supplied function RETFNC.  */
1282 gpg_error_t
1283 get_certs_bypattern (const char *pattern,
1284                      gpg_error_t (*retfnc)(void*,ksba_cert_t),
1285                      void *retfnc_data)
1286 {
1287   gpg_error_t err = GPG_ERR_BUG;
1288   enum pattern_class class;
1289   size_t offset, sn_offset;
1290   const char *hexserialno;
1291   ksba_sexp_t serialno = NULL;
1292   ksba_cert_t cert = NULL;
1293   unsigned int seq;
1294
1295   if (!pattern || !retfnc)
1296     return gpg_error (GPG_ERR_INV_ARG);
1297
1298   class = classify_pattern (pattern, &offset, &sn_offset);
1299   hexserialno = pattern + sn_offset;
1300   pattern += offset;
1301   switch (class)
1302     {
1303     case PATTERN_UNKNOWN:
1304       err = gpg_error (GPG_ERR_INV_NAME);
1305       break;
1306
1307     case PATTERN_FINGERPRINT20:
1308       cert = get_cert_byhexfpr (pattern);
1309       err = cert? 0 : gpg_error (GPG_ERR_NOT_FOUND);
1310       break;
1311
1312     case PATTERN_SERIALNO_ISSUER:
1313       serialno = hexsn_to_sexp (hexserialno);
1314       if (!serialno)
1315         err = gpg_error_from_syserror ();
1316       else
1317         {
1318           cert = get_cert_bysn (pattern, serialno);
1319           err = cert? 0 : gpg_error (GPG_ERR_NOT_FOUND);
1320         }
1321       break;
1322
1323     case PATTERN_ISSUER:
1324       for (seq=0,err=0; !err && (cert = get_cert_byissuer (pattern, seq)); seq++)
1325         {
1326           err = retfnc (retfnc_data, cert);
1327           ksba_cert_release (cert);
1328           cert = NULL;
1329         }
1330       if (!err && !seq)
1331         err = gpg_error (GPG_ERR_NOT_FOUND);
1332       break;
1333
1334     case PATTERN_SUBJECT:
1335       for (seq=0,err=0; !err && (cert = get_cert_bysubject (pattern, seq));seq++)
1336         {
1337           err = retfnc (retfnc_data, cert);
1338           ksba_cert_release (cert);
1339           cert = NULL;
1340         }
1341       if (!err && !seq)
1342         err = gpg_error (GPG_ERR_NOT_FOUND);
1343       break;
1344
1345     case PATTERN_EMAIL:
1346     case PATTERN_EMAIL_SUBSTR:
1347     case PATTERN_FINGERPRINT16:
1348     case PATTERN_SHORT_KEYID:
1349     case PATTERN_LONG_KEYID:
1350     case PATTERN_SUBSTR:
1351     case PATTERN_SERIALNO:
1352       /* Not supported.  */
1353       err = gpg_error (GPG_ERR_INV_NAME);
1354     }
1355
1356
1357   if (!err && cert)
1358     err = retfnc (retfnc_data, cert);
1359   ksba_cert_release (cert);
1360   xfree (serialno);
1361   return err;
1362 }
1363
1364
1365
1366
1367 \f
1368 /* Return the certificate matching ISSUER_DN and SERIALNO; if it is
1369  * not already in the cache, try to find it from other resources.  */
1370 ksba_cert_t
1371 find_cert_bysn (ctrl_t ctrl, const char *issuer_dn, ksba_sexp_t serialno)
1372 {
1373   gpg_error_t err;
1374   ksba_cert_t cert;
1375   cert_fetch_context_t context = NULL;
1376   char *hexsn, *buf;
1377
1378   /* First check whether it has already been cached.  */
1379   cert = get_cert_bysn (issuer_dn, serialno);
1380   if (cert)
1381     return cert;
1382
1383   /* Ask back to the service requester to return the certificate.
1384    * This is because we can assume that he already used the
1385    * certificate while checking for the CRL.  */
1386   hexsn = serial_hex (serialno);
1387   if (!hexsn)
1388     {
1389       log_error ("serial_hex() failed\n");
1390       return NULL;
1391     }
1392   buf = strconcat ("#", hexsn, "/", issuer_dn, NULL);
1393   if (!buf)
1394     {
1395       log_error ("can't allocate enough memory: %s\n", strerror (errno));
1396       xfree (hexsn);
1397       return NULL;
1398     }
1399   xfree (hexsn);
1400
1401   cert = get_cert_local (ctrl, buf);
1402   xfree (buf);
1403   if (cert)
1404     {
1405       cache_cert (cert);
1406       return cert; /* Done. */
1407     }
1408
1409   if (DBG_LOOKUP)
1410     log_debug ("find_cert_bysn: certificate not returned by caller"
1411                " - doing lookup\n");
1412
1413   /* Retrieve the certificate from external resources. */
1414   while (!cert)
1415     {
1416       ksba_sexp_t sn;
1417       char *issdn;
1418
1419       if (!context)
1420         {
1421           err = ca_cert_fetch (ctrl, &context, issuer_dn);
1422           if (err)
1423             {
1424               log_error (_("error fetching certificate by S/N: %s\n"),
1425                          gpg_strerror (err));
1426               break;
1427             }
1428         }
1429
1430       err = fetch_next_ksba_cert (context, &cert);
1431       if (err)
1432         {
1433           log_error (_("error fetching certificate by S/N: %s\n"),
1434                      gpg_strerror (err) );
1435           break;
1436         }
1437
1438       issdn = ksba_cert_get_issuer (cert, 0);
1439       if (strcmp (issuer_dn, issdn))
1440         {
1441           log_debug ("find_cert_bysn: Ooops: issuer DN does not match\n");
1442           ksba_cert_release (cert);
1443           cert = NULL;
1444           ksba_free (issdn);
1445           break;
1446         }
1447
1448       sn = ksba_cert_get_serial (cert);
1449
1450       if (DBG_LOOKUP)
1451         {
1452           log_debug ("   considering certificate (#");
1453           dump_serial (sn);
1454           log_printf ("/");
1455           dump_string (issdn);
1456           log_printf (")\n");
1457         }
1458
1459       if (!compare_serialno (serialno, sn))
1460         {
1461           ksba_free (sn);
1462           ksba_free (issdn);
1463           cache_cert (cert);
1464           if (DBG_LOOKUP)
1465             log_debug ("   found\n");
1466           break; /* Ready.  */
1467         }
1468
1469       ksba_free (sn);
1470       ksba_free (issdn);
1471       ksba_cert_release (cert);
1472       cert = NULL;
1473     }
1474
1475   end_cert_fetch (context);
1476   return cert;
1477 }
1478
1479
1480 /* Return the certificate matching SUBJECT_DN and (if not NULL)
1481  * KEYID. If it is not already in the cache, try to find it from other
1482  * resources.  Note, that the external search does not work for user
1483  * certificates because the LDAP lookup is on the caCertificate
1484  * attribute. For our purposes this is just fine.  */
1485 ksba_cert_t
1486 find_cert_bysubject (ctrl_t ctrl, const char *subject_dn, ksba_sexp_t keyid)
1487 {
1488   gpg_error_t err;
1489   int seq;
1490   ksba_cert_t cert = NULL;
1491   ksba_cert_t first;         /* The first certificate found.  */
1492   cert_fetch_context_t context = NULL;
1493   ksba_sexp_t subj;
1494
1495   /* If we have certificates from an OCSP request we first try to use
1496    * them.  This is because these certificates will really be the
1497    * required ones and thus even in the case that they can't be
1498    * uniquely located by the following code we can use them.  This is
1499    * for example required by Telesec certificates where a keyId is
1500    * used but the issuer certificate comes without a subject keyId! */
1501   if (ctrl->ocsp_certs && subject_dn)
1502     {
1503       cert_item_t ci;
1504       cert_ref_t cr;
1505       int i;
1506
1507       /* For efficiency reasons we won't use get_cert_bysubject here. */
1508       acquire_cache_read_lock ();
1509       for (i=0; i < 256; i++)
1510         for (ci=cert_cache[i]; ci; ci = ci->next)
1511           if (ci->cert && ci->subject_dn
1512               && !strcmp (ci->subject_dn, subject_dn))
1513             for (cr=ctrl->ocsp_certs; cr; cr = cr->next)
1514               if (!memcmp (ci->fpr, cr->fpr, 20))
1515                 {
1516                   ksba_cert_ref (ci->cert);
1517                   release_cache_lock ();
1518                   if (DBG_LOOKUP)
1519                     log_debug ("%s: certificate found in the cache"
1520                                " via ocsp_certs\n", __func__);
1521                   return ci->cert; /* We use this certificate. */
1522                 }
1523       release_cache_lock ();
1524       if (DBG_LOOKUP)
1525         log_debug ("find_cert_bysubject: certificate not in ocsp_certs\n");
1526     }
1527
1528   /* Now check whether the certificate is cached.  */
1529   first = NULL;
1530   subj = NULL;
1531   for (seq=0; (cert = get_cert_bysubject (subject_dn, seq)); seq++)
1532     {
1533       if (!keyid
1534           || (!ksba_cert_get_subj_key_id (cert, NULL, &subj)
1535               && !cmp_simple_canon_sexp (keyid, subj)))
1536         {
1537           xfree (subj);
1538           subj = NULL;
1539           if (DBG_LOOKUP)
1540             log_debug ("%s: certificate found in the cache"
1541                        " %sby subject DN\n", __func__, !keyid?"only ":"");
1542
1543           /* If this a trusted cert - then prefer it.  */
1544           if (!is_trusted_cert (cert, (CERTTRUST_CLASS_SYSTEM
1545                                        | CERTTRUST_CLASS_CONFIG)))
1546             {
1547               ksba_cert_release (first);
1548               first = cert;
1549               cert = NULL;
1550               /* We stop at the first trusted certificate and ignore
1551                * any yet found non-trusted certificates.   */
1552               break;
1553             }
1554           else if (!first)
1555             {
1556               /* Not trusted.  Save only the first one but continue
1557                * the loop in case there is also a trusted one.  */
1558               ksba_cert_release (first);
1559               first = cert;
1560               cert = NULL;
1561             }
1562         }
1563       xfree (subj);
1564       subj = NULL;
1565       ksba_cert_release (cert);
1566     }
1567   if (first)
1568     return first; /* Return the first found certificate.  */
1569
1570   /* If we do not have a subject DN but have a keyid, try to locate it
1571    * by keyid.  */
1572   if (!subject_dn && keyid)
1573     {
1574       int i;
1575       cert_item_t ci;
1576       ksba_sexp_t ski;
1577
1578       acquire_cache_read_lock ();
1579       for (i=0; i < 256; i++)
1580         for (ci=cert_cache[i]; ci; ci = ci->next)
1581           if (ci->cert && !ksba_cert_get_subj_key_id (ci->cert, NULL, &ski))
1582             {
1583               if (!cmp_simple_canon_sexp (keyid, ski))
1584                 {
1585                   ksba_free (ski);
1586                   ksba_cert_ref (ci->cert);
1587                   release_cache_lock ();
1588                   if (DBG_LOOKUP)
1589                     log_debug ("%s: certificate found in the cache"
1590                                " via ski\n", __func__);
1591                   return ci->cert;
1592                 }
1593               ksba_free (ski);
1594             }
1595       release_cache_lock ();
1596     }
1597
1598   if (DBG_LOOKUP)
1599     log_debug ("find_cert_bysubject: certificate not in cache\n");
1600
1601   /* Ask back to the service requester to return the certificate.
1602    * This is because we can assume that he already used the
1603    * certificate while checking for the CRL. */
1604   if (keyid)
1605     cert = get_cert_local_ski (ctrl, subject_dn, keyid);
1606   else
1607     {
1608       /* In contrast to get_cert_local_ski, get_cert_local uses any
1609        * passed pattern, so we need to make sure that an exact subject
1610        * search is done.  */
1611       char *buf;
1612
1613       buf = strconcat ("/", subject_dn, NULL);
1614       if (!buf)
1615         {
1616           log_error ("can't allocate enough memory: %s\n", strerror (errno));
1617           return NULL;
1618         }
1619       cert = get_cert_local (ctrl, buf);
1620       xfree (buf);
1621     }
1622   if (cert)
1623     {
1624       cache_cert (cert);
1625       return cert; /* Done. */
1626     }
1627
1628   if (DBG_LOOKUP)
1629     log_debug ("find_cert_bysubject: certificate not returned by caller"
1630                " - doing lookup\n");
1631
1632   /* Locate the certificate using external resources. */
1633   while (!cert)
1634     {
1635       char *subjdn;
1636
1637       if (!context)
1638         {
1639           err = ca_cert_fetch (ctrl, &context, subject_dn);
1640           if (err)
1641             {
1642               log_error (_("error fetching certificate by subject: %s\n"),
1643                          gpg_strerror (err));
1644               break;
1645             }
1646         }
1647
1648       err = fetch_next_ksba_cert (context, &cert);
1649       if (err)
1650         {
1651           log_error (_("error fetching certificate by subject: %s\n"),
1652                      gpg_strerror (err) );
1653           break;
1654         }
1655
1656       subjdn = ksba_cert_get_subject (cert, 0);
1657       if (strcmp (subject_dn, subjdn))
1658         {
1659           log_info ("find_cert_bysubject: subject DN does not match\n");
1660           ksba_cert_release (cert);
1661           cert = NULL;
1662           ksba_free (subjdn);
1663           continue;
1664         }
1665
1666
1667       if (DBG_LOOKUP)
1668         {
1669           log_debug ("   considering certificate (/");
1670           dump_string (subjdn);
1671           log_printf (")\n");
1672         }
1673       ksba_free (subjdn);
1674
1675       /* If no key ID has been provided, we return the first match.  */
1676       if (!keyid)
1677         {
1678           cache_cert (cert);
1679           if (DBG_LOOKUP)
1680             log_debug ("   found\n");
1681           break; /* Ready.  */
1682         }
1683
1684       /* With the key ID given we need to compare it.  */
1685       if (!ksba_cert_get_subj_key_id (cert, NULL, &subj))
1686         {
1687           if (!cmp_simple_canon_sexp (keyid, subj))
1688             {
1689               ksba_free (subj);
1690               cache_cert (cert);
1691               if (DBG_LOOKUP)
1692                 log_debug ("   found\n");
1693               break; /* Ready.  */
1694             }
1695         }
1696
1697       ksba_free (subj);
1698       ksba_cert_release (cert);
1699       cert = NULL;
1700     }
1701
1702   end_cert_fetch (context);
1703   return cert;
1704 }
1705
1706
1707 /* Return 0 if the certificate is a trusted certificate. Returns
1708  * GPG_ERR_NOT_TRUSTED if it is not trusted or other error codes in
1709  * case of systems errors.  TRUSTCLASSES are the bitwise ORed
1710  * CERTTRUST_CLASS values to use for the check.  */
1711 gpg_error_t
1712 is_trusted_cert (ksba_cert_t cert, unsigned int trustclasses)
1713 {
1714   unsigned char fpr[20];
1715   cert_item_t ci;
1716
1717   cert_compute_fpr (cert, fpr);
1718
1719   acquire_cache_read_lock ();
1720   for (ci=cert_cache[*fpr]; ci; ci = ci->next)
1721     if (ci->cert && !memcmp (ci->fpr, fpr, 20))
1722       {
1723         if ((ci->trustclasses & trustclasses))
1724           {
1725             /* The certificate is trusted in one of the given
1726              * TRUSTCLASSES.  */
1727             release_cache_lock ();
1728             return 0; /* Yes, it is trusted. */
1729           }
1730         break;
1731       }
1732
1733   release_cache_lock ();
1734   return gpg_error (GPG_ERR_NOT_TRUSTED);
1735 }
1736
1737
1738 \f
1739 /* Given the certificate CERT locate the issuer for this certificate
1740  * and return it at R_CERT.  Returns 0 on success or
1741  * GPG_ERR_NOT_FOUND.  */
1742 gpg_error_t
1743 find_issuing_cert (ctrl_t ctrl, ksba_cert_t cert, ksba_cert_t *r_cert)
1744 {
1745   gpg_error_t err;
1746   char *issuer_dn;
1747   ksba_cert_t issuer_cert = NULL;
1748   ksba_name_t authid;
1749   ksba_sexp_t authidno;
1750   ksba_sexp_t keyid;
1751
1752   *r_cert = NULL;
1753
1754   issuer_dn = ksba_cert_get_issuer (cert, 0);
1755   if (!issuer_dn)
1756     {
1757       log_error (_("no issuer found in certificate\n"));
1758       err = gpg_error (GPG_ERR_BAD_CERT);
1759       goto leave;
1760     }
1761
1762   /* First we need to check whether we can return that certificate
1763      using the authorithyKeyIdentifier.  */
1764   err = ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno);
1765   if (err)
1766     {
1767       log_info (_("error getting authorityKeyIdentifier: %s\n"),
1768                 gpg_strerror (err));
1769     }
1770   else
1771     {
1772       const char *s = ksba_name_enum (authid, 0);
1773       if (s && *authidno)
1774         {
1775           issuer_cert = find_cert_bysn (ctrl, s, authidno);
1776         }
1777
1778       if (!issuer_cert && keyid)
1779         {
1780           /* Not found by issuer+s/n.  Now that we have an AKI
1781            * keyIdentifier look for a certificate with a matching
1782            * SKI. */
1783           issuer_cert = find_cert_bysubject (ctrl, issuer_dn, keyid);
1784         }
1785
1786       /* Print a note so that the user does not feel too helpless when
1787        * an issuer certificate was found and gpgsm prints BAD
1788        * signature because it is not the correct one.  */
1789       if (!issuer_cert)
1790         {
1791           log_info ("issuer certificate ");
1792           if (keyid)
1793             {
1794               log_printf ("{");
1795               dump_serial (keyid);
1796               log_printf ("} ");
1797             }
1798           if (authidno)
1799             {
1800               log_printf ("(#");
1801               dump_serial (authidno);
1802               log_printf ("/");
1803               dump_string (s);
1804               log_printf (") ");
1805             }
1806           log_printf ("not found using authorityKeyIdentifier\n");
1807         }
1808       ksba_name_release (authid);
1809       xfree (authidno);
1810       xfree (keyid);
1811     }
1812
1813   /* If this did not work, try just with the issuer's name and assume
1814    * that there is only one such certificate.  We only look into our
1815    * cache then.  */
1816   if (err || !issuer_cert)
1817     {
1818       issuer_cert = get_cert_bysubject (issuer_dn, 0);
1819       if (issuer_cert)
1820         err = 0;
1821     }
1822
1823  leave:
1824   if (!err && !issuer_cert)
1825     err = gpg_error (GPG_ERR_NOT_FOUND);
1826
1827   xfree (issuer_dn);
1828
1829   if (err)
1830     ksba_cert_release (issuer_cert);
1831   else
1832     *r_cert = issuer_cert;
1833
1834   return err;
1835 }
1836
1837
1838 \f
1839 /* Read a list of certificates in PEM format from stream FP and store
1840  * them on success at R_CERTLIST.  On error NULL is stored at R_CERT
1841  * list and an error code returned.  Note that even on success an
1842  * empty list of certificates can be returned (i.e. NULL stored at
1843  * R_CERTLIST) iff the input stream has no certificates.  */
1844 gpg_error_t
1845 read_certlist_from_stream (certlist_t *r_certlist, estream_t fp)
1846 {
1847   gpg_error_t err;
1848   gnupg_ksba_io_t ioctx = NULL;
1849   ksba_reader_t reader;
1850   ksba_cert_t cert = NULL;
1851   certlist_t certlist = NULL;
1852   certlist_t cl, *cltail;
1853
1854   *r_certlist = NULL;
1855
1856   err = gnupg_ksba_create_reader (&ioctx,
1857                                   (GNUPG_KSBA_IO_PEM | GNUPG_KSBA_IO_MULTIPEM),
1858                                   fp, &reader);
1859   if (err)
1860     goto leave;
1861
1862   /* Loop to read all certificates from the stream.  */
1863   cltail = &certlist;
1864   do
1865     {
1866       ksba_cert_release (cert);
1867       cert = NULL;
1868       err = ksba_cert_new (&cert);
1869       if (!err)
1870         err = ksba_cert_read_der (cert, reader);
1871       if (err)
1872         {
1873           if (gpg_err_code (err) == GPG_ERR_EOF)
1874             err = 0;
1875           goto leave;
1876         }
1877
1878       /* Append the certificate to the list.  We also store the
1879        * fingerprint and check whether we have a cached certificate;
1880        * in that case the cached certificate is put into the list to
1881        * take advantage of a validation result which might be stored
1882        * in the cached certificate.  */
1883       cl = xtrycalloc (1, sizeof *cl);
1884       if (!cl)
1885         {
1886           err = gpg_error_from_syserror ();
1887           goto leave;
1888         }
1889       cert_compute_fpr (cert, cl->fpr);
1890       cl->cert = get_cert_byfpr (cl->fpr);
1891       if (!cl->cert)
1892         {
1893           cl->cert = cert;
1894           cert = NULL;
1895         }
1896       *cltail = cl;
1897       cltail = &cl->next;
1898       ksba_reader_clear (reader, NULL, NULL);
1899     }
1900   while (!gnupg_ksba_reader_eof_seen (ioctx));
1901
1902  leave:
1903   ksba_cert_release (cert);
1904   gnupg_ksba_destroy_reader (ioctx);
1905   if (err)
1906     release_certlist (certlist);
1907   else
1908     *r_certlist = certlist;
1909
1910   return err;
1911 }
1912
1913
1914 /* Release the certificate list CL.  */
1915 void
1916 release_certlist (certlist_t cl)
1917 {
1918   while (cl)
1919     {
1920       certlist_t next = cl->next;
1921       ksba_cert_release (cl->cert);
1922       cl = next;
1923     }
1924 }