1 /* certcache.c - Certificate caching
2 * Copyright (C) 2004, 2005, 2007, 2008, 2017 g10 Code GmbH
4 * This file is part of DirMngr.
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.
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.
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/>.
26 #include <sys/types.h>
32 #include "../common/ksba-io-support.h"
34 #include "certcache.h"
36 #define MAX_NONPERM_CACHED_CERTS 1000
38 /* Constants used to classify search patterns. */
44 PATTERN_FINGERPRINT16,
45 PATTERN_FINGERPRINT20,
50 PATTERN_SERIALNO_ISSUER,
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. */
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
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. */
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;
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;
78 typedef struct cert_item_s *cert_item_t;
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];
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;
91 /* Flag to track whether the cache has been initialized. */
92 static int initialization_done;
94 /* Total number of non-permanent certificates. */
95 static unsigned int total_nonperm_certificates;
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;
102 #ifdef HAVE_W32_SYSTEM
103 /* We load some functions dynamically. Provide typedefs for tehse
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*/
116 /* Helper to do the cache locking. */
118 init_cache_lock (void)
122 err = npth_rwlock_init (&cert_cache_lock, NULL);
124 log_fatal (_("can't initialize certificate cache lock: %s\n"),
129 acquire_cache_read_lock (void)
133 err = npth_rwlock_rdlock (&cert_cache_lock);
135 log_fatal (_("can't acquire read lock on the certificate cache: %s\n"),
140 acquire_cache_write_lock (void)
144 err = npth_rwlock_wrlock (&cert_cache_lock);
146 log_fatal (_("can't acquire write lock on the certificate cache: %s\n"),
151 release_cache_lock (void)
155 err = npth_rwlock_unlock (&cert_cache_lock);
157 log_fatal (_("can't release lock on the certificate cache: %s\n"),
162 /* Return false if both serial numbers match. Can't be used for
165 compare_serialno (ksba_sexp_t serial1, ksba_sexp_t serial2 )
167 unsigned char *a = serial1;
168 unsigned char *b = serial2;
169 return cmp_simple_canon_sexp (a, b);
174 /* Return a malloced canonical S-Expression with the serial number
175 * converted from the hex string HEXSN. Return NULL on memory
178 hexsn_to_sexp (const char *hexsn)
184 len = unhexify (NULL, hexsn);
185 snprintf (numbuf, sizeof numbuf, "(%u:", (unsigned int)len);
186 buffer = xtrymalloc (strlen (numbuf) + len + 2 );
189 p = stpcpy (buffer, numbuf);
190 len = unhexify (p, hexsn);
198 /* Compute the fingerprint of the certificate CERT and put it into
199 the 20 bytes large buffer DIGEST. Return address of this buffer. */
201 cert_compute_fpr (ksba_cert_t cert, unsigned char *digest)
206 err = gcry_md_open (&md, GCRY_MD_SHA1, 0);
208 log_fatal ("gcry_md_open failed: %s\n", gpg_strerror (err));
210 err = ksba_cert_hash (cert, 0, HASH_FNC, md);
213 log_error ("oops: ksba_cert_hash failed: %s\n", gpg_strerror (err));
214 memset (digest, 0xff, 20); /* Use a dummy value. */
219 memcpy (digest, gcry_md_read (md, GCRY_MD_SHA1), 20);
227 /* Cleanup one slot. This releases all resourses but keeps the actual
228 slot in the cache marked for reuse. */
230 clean_cache_slot (cert_item_t ci)
235 return; /* Already cleaned. */
239 ksba_free (ci->issuer_dn);
240 ci->issuer_dn = NULL;
241 ksba_free (ci->subject_dn);
242 ci->subject_dn = NULL;
247 ci->trustclasses = 0;
249 ksba_cert_release (cert);
253 /* Put the certificate CERT into the cache. It is assumed that the
254 * cache is locked while this function is called.
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. */
267 put_cert (ksba_cert_t cert, int permanent, unsigned int trustclass,
270 unsigned char help_fpr_buffer[20], *fpr;
272 fingerprint_list_t ignored;
274 /* Do not keep expired certificates in the permanent cache. */
275 if (permanent && !opt.debug_cache_expired_certs)
277 ksba_isotime_t not_after;
278 ksba_isotime_t current_time;
280 if (ksba_cert_get_validity (cert, 1, not_after))
281 return gpg_error (GPG_ERR_BAD_CERT);
283 gnupg_get_isotime (current_time);
285 if (*not_after && strcmp (current_time, not_after) > 0)
286 return gpg_error (GPG_ERR_CERT_EXPIRED);
289 fpr = fpr_buffer? fpr_buffer : &help_fpr_buffer;
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)
307 unsigned int drop_count;
309 drop_count = MAX_NONPERM_CACHED_CERTS / 20;
313 log_info (_("dropping %u certificates from the cache\n"), drop_count);
315 for (i=idx; drop_count; i = ((i+1)%256))
318 for (ci = cert_cache[i]; ci; ci = ci->next)
319 if (ci->cert && !ci->permanent)
323 clean_cache_slot (ci_mark);
325 total_nonperm_certificates--;
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))
340 /* We are configured not to use this certificate. */
341 return gpg_error (GPG_ERR_NOT_ENABLED);
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)
352 { /* No: Create a new entry. */
353 ci = xtrycalloc (1, sizeof *ci);
355 return gpg_error_from_errno (errno);
356 ci->next = cert_cache[*fpr];
357 cert_cache[*fpr] = ci;
360 ksba_cert_ref (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)
367 clean_cache_slot (ci);
368 return gpg_error (GPG_ERR_INV_CERT_OBJ);
370 ci->subject_dn = ksba_cert_get_subject (cert, 0);
371 ci->permanent = !!permanent;
372 ci->trustclasses = trustclass;
375 any_cert_of_class |= trustclass;
377 total_nonperm_certificates++;
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. */
388 load_certs_from_dir (const char *dirname, unsigned int trustclass)
396 ksba_reader_t reader;
400 dir = gnupg_opendir (dirname);
403 return 0; /* We do not consider this a severe error. */
406 while ( (ep = gnupg_readdir (dir)) )
409 if (*p == '.' || !*p)
410 continue; /* Skip any hidden files and invalid entries. */
412 if ( n < 5 || (strcmp (p+n-4,".crt") && strcmp (p+n-4,".der")))
413 continue; /* Not the desired "*.crt" or "*.der" pattern. */
416 fname = make_filename (dirname, p, NULL);
417 fp = es_fopen (fname, "rb");
420 log_error (_("can't open '%s': %s\n"),
421 fname, strerror (errno));
425 err = create_estream_ksba_reader (&reader, fp);
432 err = ksba_cert_new (&cert);
434 err = ksba_cert_read_der (cert, reader);
435 ksba_reader_release (reader);
439 log_error (_("can't parse certificate '%s': %s\n"),
440 fname, gpg_strerror (err));
441 ksba_cert_release (cert);
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);
450 if ((trustclass & CERTTRUST_CLASS_CONFIG))
451 http_register_cfg_ca (fname);
454 log_info (_("trusted certificate '%s' loaded\n"), fname);
456 log_info (_("certificate '%s' loaded\n"), fname);
459 p = get_fingerprint_hexstring_colon (cert);
460 log_info (_(" SHA1 fingerprint = %s\n"), p);
463 cert_log_name (_(" issuer ="), cert);
464 cert_log_subject (_(" subject ="), cert);
467 else if (gpg_err_code (err) == GPG_ERR_NOT_ENABLED)
468 log_info ("certificate '%s' skipped due to configuration\n", fname);
470 log_error (_("error loading certificate '%s': %s\n"),
471 fname, gpg_strerror (err));
472 ksba_cert_release (cert);
476 gnupg_closedir (dir);
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. */
488 load_certs_from_file (const char *fname, unsigned int trustclasses,
493 gnupg_ksba_io_t ioctx = NULL;
494 ksba_reader_t reader;
495 ksba_cert_t cert = NULL;
497 fp = es_fopen (fname, "rb");
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));
504 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
508 err = gnupg_ksba_create_reader (&ioctx,
509 (GNUPG_KSBA_IO_AUTODETECT
510 | GNUPG_KSBA_IO_MULTIPEM),
514 log_error ("can't create reader: %s\n", gpg_strerror (err));
518 /* Loop to read all certificates from the file. */
521 ksba_cert_release (cert);
523 err = ksba_cert_new (&cert);
525 err = ksba_cert_read_der (cert, reader);
528 if (gpg_err_code (err) == GPG_ERR_EOF)
531 log_error (_("can't parse certificate '%s': %s\n"),
532 fname, gpg_strerror (err));
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);
542 log_error (_("error loading certificate '%s': %s\n"),
543 fname, gpg_strerror (err));
544 else if (opt.verbose > 1)
548 log_info (_("trusted certificate '%s' loaded\n"), fname);
549 p = get_fingerprint_hexstring_colon (cert);
550 log_info (_(" SHA1 fingerprint = %s\n"), p);
553 cert_log_name (_(" issuer ="), cert);
554 cert_log_subject (_(" subject ="), cert);
557 ksba_reader_clear (reader, NULL, NULL);
559 while (!gnupg_ksba_reader_eof_seen (ioctx));
562 ksba_cert_release (cert);
563 gnupg_ksba_destroy_reader (ioctx);
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
576 load_certs_from_w32_store (const char *storename)
578 static int init_done;
579 static CERTOPENSYSTEMSTORE pCertOpenSystemStore;
580 static CERTENUMCERTIFICATESINSTORE pCertEnumCertificatesInStore;
581 static CERTCLOSESTORE pCertCloseStore;
584 const CERT_CONTEXT *w32cert;
585 ksba_cert_t cert = NULL;
586 unsigned int count = 0;
588 /* Initialize on the first use. */
591 static HANDLE hCrypt32;
595 hCrypt32 = LoadLibrary ("Crypt32.dll");
598 log_error ("can't load Crypt32.dll: %s\n", w32_strerror (-1));
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
612 log_error ("can't load crypt32.dll: %s\n", "missing function");
613 pCertOpenSystemStore = NULL;
617 if (!pCertOpenSystemStore)
618 return; /* Not initialized. */
621 w32store = pCertOpenSystemStore (0, storename);
624 log_error ("can't open certificate store '%s': %s\n",
625 storename, w32_strerror (-1));
630 while ((w32cert = pCertEnumCertificatesInStore (w32store, w32cert)))
632 if (w32cert->dwCertEncodingType == X509_ASN_ENCODING)
634 ksba_cert_release (cert);
636 err = ksba_cert_new (&cert);
638 err = ksba_cert_init_from_mem (cert,
639 w32cert->pbCertEncoded,
640 w32cert->cbCertEncoded);
643 log_error (_("can't parse certificate '%s': %s\n"),
644 storename, gpg_strerror (err));
648 err = put_cert (cert, 1, CERTTRUST_CLASS_SYSTEM, NULL);
651 if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
654 log_debug (_("certificate '%s' already cached\n"), storename);
656 else if (gpg_err_code (err) == GPG_ERR_NOT_ENABLED)
657 log_info ("certificate '%s' skipped due to configuration\n",
660 log_error (_("error loading certificate '%s': %s\n"),
661 storename, gpg_strerror (err));
662 else if (opt.verbose > 1)
666 log_info (_("trusted certificate '%s' loaded\n"), storename);
667 p = get_fingerprint_hexstring_colon (cert);
668 log_info (_(" SHA1 fingerprint = %s\n"), p);
671 cert_log_name (_(" issuer ="), cert);
672 cert_log_subject (_(" subject ="), cert);
677 ksba_cert_release (cert);
678 pCertCloseStore (w32store, 0);
681 log_debug ("number of certs loaded from store '%s': %u\n",
685 #endif /*HAVE_W32_SYSTEM*/
688 /* Load the trusted certificates provided by the system. */
690 load_certs_from_system (void)
692 #ifdef HAVE_W32_SYSTEM
694 load_certs_from_w32_store ("ROOT");
695 load_certs_from_w32_store ("CA");
699 #else /*!HAVE_W32_SYSTEM*/
701 /* A list of certificate bundles to try. */
705 #ifdef DEFAULT_TRUST_STORE_FILE
706 { DEFAULT_TRUST_STORE_FILE }
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*/
718 for (idx=0; idx < DIM (table); idx++)
719 if (!gnupg_access (table[idx].name, F_OK))
721 /* Take the first available bundle. */
722 err = load_certs_from_file (table[idx].name, CERTTRUST_CLASS_SYSTEM, 0);
727 #endif /*!HAVE_W32_SYSTEM*/
731 /* Initialize the certificate cache if not yet done. */
733 cert_cache_init (strlist_t hkp_cacerts)
738 if (initialization_done)
741 acquire_cache_write_lock ();
743 load_certs_from_system ();
745 fname = make_filename_try (gnupg_sysconfdir (), "trusted-certs", NULL);
747 load_certs_from_dir (fname, CERTTRUST_CLASS_CONFIG);
750 fname = make_filename_try (gnupg_sysconfdir (), "extra-certs", NULL);
752 load_certs_from_dir (fname, 0);
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); */
762 /* load_certs_from_file (fname, CERTTRUST_CLASS_HKPSPOOL, 1); */
765 for (sl = hkp_cacerts; sl; sl = sl->next)
766 load_certs_from_file (sl->d, CERTTRUST_CLASS_HKP, 0);
768 initialization_done = 1;
769 release_cache_lock ();
771 cert_cache_print_stats (NULL);
774 /* Deinitialize the certificate cache. With FULL set to true even the
775 unused certificate slots are released. */
777 cert_cache_deinit (int full)
782 if (!initialization_done)
785 acquire_cache_write_lock ();
787 for (i=0; i < 256; i++)
788 for (ci=cert_cache[i]; ci; ci = ci->next)
789 clean_cache_slot (ci);
793 for (i=0; i < 256; i++)
795 for (ci=cert_cache[i]; ci; ci = ci2)
800 cert_cache[i] = NULL;
804 http_register_cfg_ca (NULL);
806 total_nonperm_certificates = 0;
807 any_cert_of_class = 0;
808 initialization_done = 0;
809 release_cache_lock ();
812 /* Print some statistics to the log file. */
814 cert_cache_print_stats (ctrl_t ctrl)
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;
826 acquire_cache_read_lock ();
827 for (idx = 0; idx < 256; idx++)
828 for (ci=cert_cache[idx]; ci; ci = ci->next)
835 if (ci->trustclasses)
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))
844 if ((ci->trustclasses & CERTTRUST_CLASS_HKPSPOOL))
845 n_trustclass_hkpspool++;
849 release_cache_lock ();
851 dirmngr_status_helpf (ctrl,
852 _("permanently loaded certificates: %u\n"),
854 dirmngr_status_helpf (ctrl,
855 _(" runtime cached certificates: %u\n"),
857 dirmngr_status_helpf (ctrl,
858 _(" trusted certificates: %u (%u,%u,%u,%u)\n"),
863 n_trustclass_hkpspool);
867 /* Return true if any cert of a class in MASK is permanently
870 cert_cache_any_in_class (unsigned int mask)
872 return !!(any_cert_of_class & mask);
876 /* Put CERT into the certificate cache. */
878 cache_cert (ksba_cert_t cert)
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"));
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");
892 log_error (_("error caching certificate: %s\n"), gpg_strerror (err));
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. */
902 cache_cert_silent (ksba_cert_t cert, void *fpr_buffer)
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)
912 if (gpg_err_code (err) == GPG_ERR_NOT_ENABLED)
913 log_info ("certificate skipped due to configuration\n");
915 log_error (_("error caching certificate: %s\n"), gpg_strerror (err));
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. */
928 get_cert_byfpr (const unsigned char *fpr)
932 acquire_cache_read_lock ();
933 for (ci=cert_cache[*fpr]; ci; ci = ci->next)
934 if (ci->cert && !memcmp (ci->fpr, fpr, 20))
936 ksba_cert_ref (ci->cert);
937 release_cache_lock ();
941 release_cache_lock ();
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. */
953 get_cert_byhexfpr (const char *string)
955 unsigned char fpr[20];
959 if (strchr (string, ':'))
961 for (s=string,i=0; i < 20 && hexdigitp (s) && hexdigitp(s+1);)
963 if (s[2] && s[2] != ':')
964 break; /* Invalid string. */
965 fpr[i++] = xtoi_2 (s);
967 if (i!= 20 && *s == ':')
973 for (s=string,i=0; i < 20 && hexdigitp (s) && hexdigitp(s+1); s+=2 )
974 fpr[i++] = xtoi_2 (s);
978 log_error (_("invalid SHA1 fingerprint string '%s'\n"), string);
982 return get_cert_byfpr (fpr);
987 /* Return the certificate matching ISSUER_DN and SERIALNO. */
989 get_cert_bysn (const char *issuer_dn, ksba_sexp_t serialno)
991 /* Simple and inefficient implementation. fixme! */
995 acquire_cache_read_lock ();
996 for (i=0; i < 256; i++)
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))
1002 ksba_cert_ref (ci->cert);
1003 release_cache_lock ();
1008 release_cache_lock ();
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. */
1016 get_cert_byissuer (const char *issuer_dn, unsigned int seq)
1018 /* Simple and very inefficient implementation and API. fixme! */
1022 acquire_cache_read_lock ();
1023 for (i=0; i < 256; i++)
1025 for (ci=cert_cache[i]; ci; ci = ci->next)
1026 if (ci->cert && !strcmp (ci->issuer_dn, issuer_dn))
1029 ksba_cert_ref (ci->cert);
1030 release_cache_lock ();
1035 release_cache_lock ();
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. */
1043 get_cert_bysubject (const char *subject_dn, unsigned int seq)
1045 /* Simple and very inefficient implementation and API. fixme! */
1052 acquire_cache_read_lock ();
1053 for (i=0; i < 256; i++)
1055 for (ci=cert_cache[i]; ci; ci = ci->next)
1056 if (ci->cert && ci->subject_dn
1057 && !strcmp (ci->subject_dn, subject_dn))
1060 ksba_cert_ref (ci->cert);
1061 release_cache_lock ();
1066 release_cache_lock ();
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)
1078 enum pattern_class result;
1083 *r_offset = *r_sn_offset = 0;
1085 /* Skip leading spaces. */
1086 for(s = pattern; *s && spacep (s); s++ )
1091 case 0: /* Empty string is an error. */
1092 result = PATTERN_UNKNOWN;
1095 case '.': /* An email address, compare from end. */
1096 result = PATTERN_UNKNOWN; /* Not implemented. */
1099 case '<': /* An email address. */
1100 result = PATTERN_EMAIL;
1104 case '@': /* Part of an email address. */
1105 result = PATTERN_EMAIL_SUBSTR;
1109 case '=': /* Exact compare. */
1110 result = PATTERN_UNKNOWN; /* Does not make sense for X.509. */
1113 case '*': /* Case insensitive substring search. */
1114 result = PATTERN_SUBSTR;
1118 case '+': /* Compare individual words. */
1119 result = PATTERN_UNKNOWN; /* Not implemented. */
1122 case '/': /* Subject's DN. */
1124 if (!*s || spacep (s))
1125 result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */
1127 result = PATTERN_SUBJECT;
1130 case '#': /* Serial number or issuer DN. */
1137 /* An issuer's DN is indicated by "#/" */
1139 if (!*s || spacep (s))
1140 result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */
1142 result = PATTERN_ISSUER;
1145 { /* Serialnumber + optional issuer ID. */
1146 for (si=s; *si && *si != '/'; si++)
1147 if (!strchr("01234567890abcdefABCDEF", *si))
1149 if (*si && *si != '/')
1150 result = PATTERN_UNKNOWN; /* Invalid digit in serial number. */
1153 *r_sn_offset = s - pattern;
1155 result = PATTERN_SERIALNO;
1159 if (!*s || spacep (s))
1160 result = PATTERN_UNKNOWN; /* No DN or prefixed
1163 result = PATTERN_SERIALNO_ISSUER;
1170 case ':': /* Unified fingerprint. */
1172 const char *se, *si;
1175 se = strchr (++s, ':');
1177 result = PATTERN_UNKNOWN;
1180 for (i=0, si=s; si < se; si++, i++ )
1181 if (!strchr("01234567890abcdefABCDEF", *si))
1184 result = PATTERN_UNKNOWN; /* Invalid digit. */
1186 result = PATTERN_FINGERPRINT16;
1188 result = PATTERN_FINGERPRINT20;
1190 result = PATTERN_UNKNOWN; /* Invalid length for a fingerprint. */
1195 case '&': /* Keygrip. */
1196 result = PATTERN_UNKNOWN; /* Not implemented. */
1200 if (s[0] == '0' && s[1] == 'x')
1206 hexlength = strspn(s, "0123456789abcdefABCDEF");
1208 /* Check if a hexadecimal number is terminated by EOS or blank. */
1209 if (hexlength && s[hexlength] && !spacep (s+hexlength))
1211 /* If the "0x" prefix is used a correct termination is required. */
1214 result = PATTERN_UNKNOWN;
1217 hexlength = 0; /* Not a hex number. */
1220 if (hexlength == 8 || (!hexprefix && hexlength == 9 && *s == '0'))
1224 result = PATTERN_SHORT_KEYID;
1226 else if (hexlength == 16 || (!hexprefix && hexlength == 17 && *s == '0'))
1228 if (hexlength == 17)
1230 result = PATTERN_LONG_KEYID;
1232 else if (hexlength == 32 || (!hexprefix && hexlength == 33 && *s == '0'))
1234 if (hexlength == 33)
1236 result = PATTERN_FINGERPRINT16;
1238 else if (hexlength == 40 || (!hexprefix && hexlength == 41 && *s == '0'))
1240 if (hexlength == 41)
1242 result = PATTERN_FINGERPRINT20;
1244 else if (!hexprefix)
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)))
1254 for (i=0; i < 20; i++, s += 3)
1257 if (c == -1 || (i < 19 && s[2] != ':'))
1261 result = PATTERN_FINGERPRINT20;
1263 if (result == PATTERN_UNKNOWN) /* Default to substring match. */
1265 result = PATTERN_SUBSTR;
1268 else /* A hex number with a prefix but with a wrong length. */
1269 result = PATTERN_UNKNOWN;
1272 if (result != PATTERN_UNKNOWN)
1273 *r_offset = s - pattern;
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. */
1283 get_certs_bypattern (const char *pattern,
1284 gpg_error_t (*retfnc)(void*,ksba_cert_t),
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;
1295 if (!pattern || !retfnc)
1296 return gpg_error (GPG_ERR_INV_ARG);
1298 class = classify_pattern (pattern, &offset, &sn_offset);
1299 hexserialno = pattern + sn_offset;
1303 case PATTERN_UNKNOWN:
1304 err = gpg_error (GPG_ERR_INV_NAME);
1307 case PATTERN_FINGERPRINT20:
1308 cert = get_cert_byhexfpr (pattern);
1309 err = cert? 0 : gpg_error (GPG_ERR_NOT_FOUND);
1312 case PATTERN_SERIALNO_ISSUER:
1313 serialno = hexsn_to_sexp (hexserialno);
1315 err = gpg_error_from_syserror ();
1318 cert = get_cert_bysn (pattern, serialno);
1319 err = cert? 0 : gpg_error (GPG_ERR_NOT_FOUND);
1323 case PATTERN_ISSUER:
1324 for (seq=0,err=0; !err && (cert = get_cert_byissuer (pattern, seq)); seq++)
1326 err = retfnc (retfnc_data, cert);
1327 ksba_cert_release (cert);
1331 err = gpg_error (GPG_ERR_NOT_FOUND);
1334 case PATTERN_SUBJECT:
1335 for (seq=0,err=0; !err && (cert = get_cert_bysubject (pattern, seq));seq++)
1337 err = retfnc (retfnc_data, cert);
1338 ksba_cert_release (cert);
1342 err = gpg_error (GPG_ERR_NOT_FOUND);
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);
1358 err = retfnc (retfnc_data, cert);
1359 ksba_cert_release (cert);
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. */
1371 find_cert_bysn (ctrl_t ctrl, const char *issuer_dn, ksba_sexp_t serialno)
1375 cert_fetch_context_t context = NULL;
1378 /* First check whether it has already been cached. */
1379 cert = get_cert_bysn (issuer_dn, serialno);
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);
1389 log_error ("serial_hex() failed\n");
1392 buf = strconcat ("#", hexsn, "/", issuer_dn, NULL);
1395 log_error ("can't allocate enough memory: %s\n", strerror (errno));
1401 cert = get_cert_local (ctrl, buf);
1406 return cert; /* Done. */
1410 log_debug ("find_cert_bysn: certificate not returned by caller"
1411 " - doing lookup\n");
1413 /* Retrieve the certificate from external resources. */
1421 err = ca_cert_fetch (ctrl, &context, issuer_dn);
1424 log_error (_("error fetching certificate by S/N: %s\n"),
1425 gpg_strerror (err));
1430 err = fetch_next_ksba_cert (context, &cert);
1433 log_error (_("error fetching certificate by S/N: %s\n"),
1434 gpg_strerror (err) );
1438 issdn = ksba_cert_get_issuer (cert, 0);
1439 if (strcmp (issuer_dn, issdn))
1441 log_debug ("find_cert_bysn: Ooops: issuer DN does not match\n");
1442 ksba_cert_release (cert);
1448 sn = ksba_cert_get_serial (cert);
1452 log_debug (" considering certificate (#");
1455 dump_string (issdn);
1459 if (!compare_serialno (serialno, sn))
1465 log_debug (" found\n");
1471 ksba_cert_release (cert);
1475 end_cert_fetch (context);
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. */
1486 find_cert_bysubject (ctrl_t ctrl, const char *subject_dn, ksba_sexp_t keyid)
1490 ksba_cert_t cert = NULL;
1491 ksba_cert_t first; /* The first certificate found. */
1492 cert_fetch_context_t context = NULL;
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)
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))
1516 ksba_cert_ref (ci->cert);
1517 release_cache_lock ();
1519 log_debug ("%s: certificate found in the cache"
1520 " via ocsp_certs\n", __func__);
1521 return ci->cert; /* We use this certificate. */
1523 release_cache_lock ();
1525 log_debug ("find_cert_bysubject: certificate not in ocsp_certs\n");
1528 /* Now check whether the certificate is cached. */
1531 for (seq=0; (cert = get_cert_bysubject (subject_dn, seq)); seq++)
1534 || (!ksba_cert_get_subj_key_id (cert, NULL, &subj)
1535 && !cmp_simple_canon_sexp (keyid, subj)))
1540 log_debug ("%s: certificate found in the cache"
1541 " %sby subject DN\n", __func__, !keyid?"only ":"");
1543 /* If this a trusted cert - then prefer it. */
1544 if (!is_trusted_cert (cert, (CERTTRUST_CLASS_SYSTEM
1545 | CERTTRUST_CLASS_CONFIG)))
1547 ksba_cert_release (first);
1550 /* We stop at the first trusted certificate and ignore
1551 * any yet found non-trusted certificates. */
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);
1565 ksba_cert_release (cert);
1568 return first; /* Return the first found certificate. */
1570 /* If we do not have a subject DN but have a keyid, try to locate it
1572 if (!subject_dn && keyid)
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))
1583 if (!cmp_simple_canon_sexp (keyid, ski))
1586 ksba_cert_ref (ci->cert);
1587 release_cache_lock ();
1589 log_debug ("%s: certificate found in the cache"
1590 " via ski\n", __func__);
1595 release_cache_lock ();
1599 log_debug ("find_cert_bysubject: certificate not in cache\n");
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. */
1605 cert = get_cert_local_ski (ctrl, subject_dn, keyid);
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. */
1613 buf = strconcat ("/", subject_dn, NULL);
1616 log_error ("can't allocate enough memory: %s\n", strerror (errno));
1619 cert = get_cert_local (ctrl, buf);
1625 return cert; /* Done. */
1629 log_debug ("find_cert_bysubject: certificate not returned by caller"
1630 " - doing lookup\n");
1632 /* Locate the certificate using external resources. */
1639 err = ca_cert_fetch (ctrl, &context, subject_dn);
1642 log_error (_("error fetching certificate by subject: %s\n"),
1643 gpg_strerror (err));
1648 err = fetch_next_ksba_cert (context, &cert);
1651 log_error (_("error fetching certificate by subject: %s\n"),
1652 gpg_strerror (err) );
1656 subjdn = ksba_cert_get_subject (cert, 0);
1657 if (strcmp (subject_dn, subjdn))
1659 log_info ("find_cert_bysubject: subject DN does not match\n");
1660 ksba_cert_release (cert);
1669 log_debug (" considering certificate (/");
1670 dump_string (subjdn);
1675 /* If no key ID has been provided, we return the first match. */
1680 log_debug (" found\n");
1684 /* With the key ID given we need to compare it. */
1685 if (!ksba_cert_get_subj_key_id (cert, NULL, &subj))
1687 if (!cmp_simple_canon_sexp (keyid, subj))
1692 log_debug (" found\n");
1698 ksba_cert_release (cert);
1702 end_cert_fetch (context);
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. */
1712 is_trusted_cert (ksba_cert_t cert, unsigned int trustclasses)
1714 unsigned char fpr[20];
1717 cert_compute_fpr (cert, fpr);
1719 acquire_cache_read_lock ();
1720 for (ci=cert_cache[*fpr]; ci; ci = ci->next)
1721 if (ci->cert && !memcmp (ci->fpr, fpr, 20))
1723 if ((ci->trustclasses & trustclasses))
1725 /* The certificate is trusted in one of the given
1727 release_cache_lock ();
1728 return 0; /* Yes, it is trusted. */
1733 release_cache_lock ();
1734 return gpg_error (GPG_ERR_NOT_TRUSTED);
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. */
1743 find_issuing_cert (ctrl_t ctrl, ksba_cert_t cert, ksba_cert_t *r_cert)
1747 ksba_cert_t issuer_cert = NULL;
1749 ksba_sexp_t authidno;
1754 issuer_dn = ksba_cert_get_issuer (cert, 0);
1757 log_error (_("no issuer found in certificate\n"));
1758 err = gpg_error (GPG_ERR_BAD_CERT);
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);
1767 log_info (_("error getting authorityKeyIdentifier: %s\n"),
1768 gpg_strerror (err));
1772 const char *s = ksba_name_enum (authid, 0);
1775 issuer_cert = find_cert_bysn (ctrl, s, authidno);
1778 if (!issuer_cert && keyid)
1780 /* Not found by issuer+s/n. Now that we have an AKI
1781 * keyIdentifier look for a certificate with a matching
1783 issuer_cert = find_cert_bysubject (ctrl, issuer_dn, keyid);
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. */
1791 log_info ("issuer certificate ");
1795 dump_serial (keyid);
1801 dump_serial (authidno);
1806 log_printf ("not found using authorityKeyIdentifier\n");
1808 ksba_name_release (authid);
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
1816 if (err || !issuer_cert)
1818 issuer_cert = get_cert_bysubject (issuer_dn, 0);
1824 if (!err && !issuer_cert)
1825 err = gpg_error (GPG_ERR_NOT_FOUND);
1830 ksba_cert_release (issuer_cert);
1832 *r_cert = issuer_cert;
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. */
1845 read_certlist_from_stream (certlist_t *r_certlist, estream_t fp)
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;
1856 err = gnupg_ksba_create_reader (&ioctx,
1857 (GNUPG_KSBA_IO_PEM | GNUPG_KSBA_IO_MULTIPEM),
1862 /* Loop to read all certificates from the stream. */
1866 ksba_cert_release (cert);
1868 err = ksba_cert_new (&cert);
1870 err = ksba_cert_read_der (cert, reader);
1873 if (gpg_err_code (err) == GPG_ERR_EOF)
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);
1886 err = gpg_error_from_syserror ();
1889 cert_compute_fpr (cert, cl->fpr);
1890 cl->cert = get_cert_byfpr (cl->fpr);
1898 ksba_reader_clear (reader, NULL, NULL);
1900 while (!gnupg_ksba_reader_eof_seen (ioctx));
1903 ksba_cert_release (cert);
1904 gnupg_ksba_destroy_reader (ioctx);
1906 release_certlist (certlist);
1908 *r_certlist = certlist;
1914 /* Release the certificate list CL. */
1916 release_certlist (certlist_t cl)
1920 certlist_t next = cl->next;
1921 ksba_cert_release (cl->cert);