1 /* certcache.c - Certificate caching
2 * Copyright (C) 2004, 2005, 2007, 2008 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>
33 #include "certcache.h"
36 #define MAX_EXTRA_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. */
71 unsigned int loaded:1; /* It has been explicitly loaded. */
72 unsigned int trusted:1; /* This is a trusted root certificate. */
75 typedef struct cert_item_s *cert_item_t;
77 /* The actual cert cache consisting of 256 slots for items indexed by
78 the first byte of the fingerprint. */
79 static cert_item_t cert_cache[256];
81 /* This is the global cache_lock variable. In general locking is not
82 needed but it would take extra efforts to make sure that no
83 indirect use of npth functions is done, so we simply lock it
84 always. Note: We can't use static initialization, as that is not
85 available through w32-pth. */
86 static npth_rwlock_t cert_cache_lock;
88 /* Flag to track whether the cache has been initialized. */
89 static int initialization_done;
91 /* Total number of certificates loaded during initialization and
92 cached during operation. */
93 static unsigned int total_loaded_certificates;
94 static unsigned int total_extra_certificates;
98 /* Helper to do the cache locking. */
100 init_cache_lock (void)
104 err = npth_rwlock_init (&cert_cache_lock, NULL);
106 log_fatal (_("can't initialize certificate cache lock: %s\n"),
111 acquire_cache_read_lock (void)
115 err = npth_rwlock_rdlock (&cert_cache_lock);
117 log_fatal (_("can't acquire read lock on the certificate cache: %s\n"),
122 acquire_cache_write_lock (void)
126 err = npth_rwlock_wrlock (&cert_cache_lock);
128 log_fatal (_("can't acquire write lock on the certificate cache: %s\n"),
133 release_cache_lock (void)
137 err = npth_rwlock_unlock (&cert_cache_lock);
139 log_fatal (_("can't release lock on the certificate cache: %s\n"),
144 /* Return false if both serial numbers match. Can't be used for
147 compare_serialno (ksba_sexp_t serial1, ksba_sexp_t serial2 )
149 unsigned char *a = serial1;
150 unsigned char *b = serial2;
151 return cmp_simple_canon_sexp (a, b);
156 /* Return a malloced canonical S-Expression with the serial number
157 converted from the hex string HEXSN. Return NULL on memory
160 hexsn_to_sexp (const char *hexsn)
166 len = unhexify (NULL, hexsn);
167 snprintf (numbuf, sizeof numbuf, "(%u:", (unsigned int)len);
168 buffer = xtrymalloc (strlen (numbuf) + len + 2 );
171 p = stpcpy (buffer, numbuf);
172 len = unhexify (p, hexsn);
180 /* Compute the fingerprint of the certificate CERT and put it into
181 the 20 bytes large buffer DIGEST. Return address of this buffer. */
183 cert_compute_fpr (ksba_cert_t cert, unsigned char *digest)
188 err = gcry_md_open (&md, GCRY_MD_SHA1, 0);
190 log_fatal ("gcry_md_open failed: %s\n", gpg_strerror (err));
192 err = ksba_cert_hash (cert, 0, HASH_FNC, md);
195 log_error ("oops: ksba_cert_hash failed: %s\n", gpg_strerror (err));
196 memset (digest, 0xff, 20); /* Use a dummy value. */
201 memcpy (digest, gcry_md_read (md, GCRY_MD_SHA1), 20);
208 /* Cleanup one slot. This releases all resourses but keeps the actual
209 slot in the cache marked for reuse. */
211 clean_cache_slot (cert_item_t ci)
216 return; /* Already cleaned. */
220 ksba_free (ci->issuer_dn);
221 ci->issuer_dn = NULL;
222 ksba_free (ci->subject_dn);
223 ci->subject_dn = NULL;
227 ksba_cert_release (cert);
231 /* Put the certificate CERT into the cache. It is assumed that the
232 cache is locked while this function is called. If FPR_BUFFER is not
233 NULL the fingerprint of the certificate will be stored there.
234 FPR_BUFFER neds to point to a buffer of at least 20 bytes. The
235 fingerprint will be stored on success or when the function returns
236 gpg_err_code(GPG_ERR_DUP_VALUE). */
238 put_cert (ksba_cert_t cert, int is_loaded, int is_trusted, void *fpr_buffer)
240 unsigned char help_fpr_buffer[20], *fpr;
243 fpr = fpr_buffer? fpr_buffer : &help_fpr_buffer;
245 /* If we already reached the caching limit, drop a couple of certs
246 from the cache. Our dropping strategy is simple: We keep a
247 static index counter and use this to start looking for
248 certificates, then we drop 5 percent of the oldest certificates
249 starting at that index. For a large cache this is a fair way of
250 removing items. An LRU strategy would be better of course.
251 Because we append new entries to the head of the list and we want
252 to remove old ones first, we need to do this from the tail. The
253 implementation is not very efficient but compared to the long
254 time it takes to retrieve a certifciate from an external resource
255 it seems to be reasonable. */
256 if (!is_loaded && total_extra_certificates >= MAX_EXTRA_CACHED_CERTS)
261 unsigned int drop_count;
263 drop_count = MAX_EXTRA_CACHED_CERTS / 20;
267 log_info (_("dropping %u certificates from the cache\n"), drop_count);
269 for (i=idx; drop_count; i = ((i+1)%256))
272 for (ci = cert_cache[i]; ci; ci = ci->next)
273 if (ci->cert && !ci->flags.loaded)
277 clean_cache_slot (ci_mark);
279 total_extra_certificates--;
289 cert_compute_fpr (cert, fpr);
290 for (ci=cert_cache[*fpr]; ci; ci = ci->next)
291 if (ci->cert && !memcmp (ci->fpr, fpr, 20))
292 return gpg_error (GPG_ERR_DUP_VALUE);
293 /* Try to reuse an existing entry. */
294 for (ci=cert_cache[*fpr]; ci; ci = ci->next)
298 { /* No: Create a new entry. */
299 ci = xtrycalloc (1, sizeof *ci);
301 return gpg_error_from_errno (errno);
302 ci->next = cert_cache[*fpr];
303 cert_cache[*fpr] = ci;
306 memset (&ci->flags, 0, sizeof ci->flags);
308 ksba_cert_ref (cert);
310 memcpy (ci->fpr, fpr, 20);
311 ci->sn = ksba_cert_get_serial (cert);
312 ci->issuer_dn = ksba_cert_get_issuer (cert, 0);
313 if (!ci->issuer_dn || !ci->sn)
315 clean_cache_slot (ci);
316 return gpg_error (GPG_ERR_INV_CERT_OBJ);
318 ci->subject_dn = ksba_cert_get_subject (cert, 0);
319 ci->flags.loaded = !!is_loaded;
320 ci->flags.trusted = !!is_trusted;
323 total_loaded_certificates++;
325 total_extra_certificates++;
331 /* Load certificates from the directory DIRNAME. All certificates
332 matching the pattern "*.crt" or "*.der" are loaded. We assume that
333 certificates are DER encoded and not PEM encapsulated. The cache
334 should be in a locked state when calling this function. */
336 load_certs_from_dir (const char *dirname, int are_trusted)
344 ksba_reader_t reader;
348 dir = opendir (dirname);
351 return 0; /* We do not consider this a severe error. */
354 while ( (ep=readdir (dir)) )
357 if (*p == '.' || !*p)
358 continue; /* Skip any hidden files and invalid entries. */
360 if ( n < 5 || (strcmp (p+n-4,".crt") && strcmp (p+n-4,".der")))
361 continue; /* Not the desired "*.crt" or "*.der" pattern. */
364 fname = make_filename (dirname, p, NULL);
365 fp = es_fopen (fname, "rb");
368 log_error (_("can't open '%s': %s\n"),
369 fname, strerror (errno));
373 err = create_estream_ksba_reader (&reader, fp);
380 err = ksba_cert_new (&cert);
382 err = ksba_cert_read_der (cert, reader);
383 ksba_reader_release (reader);
387 log_error (_("can't parse certificate '%s': %s\n"),
388 fname, gpg_strerror (err));
389 ksba_cert_release (cert);
393 err = put_cert (cert, 1, are_trusted, NULL);
394 if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
395 log_info (_("certificate '%s' already cached\n"), fname);
399 log_info (_("trusted certificate '%s' loaded\n"), fname);
401 log_info (_("certificate '%s' loaded\n"), fname);
404 p = get_fingerprint_hexstring_colon (cert);
405 log_info (_(" SHA1 fingerprint = %s\n"), p);
408 cert_log_name (_(" issuer ="), cert);
409 cert_log_subject (_(" subject ="), cert);
413 log_error (_("error loading certificate '%s': %s\n"),
414 fname, gpg_strerror (err));
415 ksba_cert_release (cert);
424 /* Initialize the certificate cache if not yet done. */
426 cert_cache_init (void)
430 if (initialization_done)
433 acquire_cache_write_lock ();
435 dname = make_filename (gnupg_sysconfdir (), "trusted-certs", NULL);
436 load_certs_from_dir (dname, 1);
439 dname = make_filename (gnupg_sysconfdir (), "extra-certs", NULL);
440 load_certs_from_dir (dname, 0);
443 initialization_done = 1;
444 release_cache_lock ();
446 cert_cache_print_stats ();
449 /* Deinitialize the certificate cache. With FULL set to true even the
450 unused certificate slots are released. */
452 cert_cache_deinit (int full)
457 if (!initialization_done)
460 acquire_cache_write_lock ();
462 for (i=0; i < 256; i++)
463 for (ci=cert_cache[i]; ci; ci = ci->next)
464 clean_cache_slot (ci);
468 for (i=0; i < 256; i++)
470 for (ci=cert_cache[i]; ci; ci = ci2)
475 cert_cache[i] = NULL;
479 total_loaded_certificates = 0;
480 total_extra_certificates = 0;
481 initialization_done = 0;
482 release_cache_lock ();
485 /* Print some statistics to the log file. */
487 cert_cache_print_stats (void)
489 log_info (_("permanently loaded certificates: %u\n"),
490 total_loaded_certificates);
491 log_info (_(" runtime cached certificates: %u\n"),
492 total_extra_certificates);
496 /* Put CERT into the certificate cache. */
498 cache_cert (ksba_cert_t cert)
502 acquire_cache_write_lock ();
503 err = put_cert (cert, 0, 0, NULL);
504 release_cache_lock ();
505 if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
506 log_info (_("certificate already cached\n"));
508 log_info (_("certificate cached\n"));
510 log_error (_("error caching certificate: %s\n"), gpg_strerror (err));
515 /* Put CERT into the certificate cache and store the fingerprint of
516 the certificate into FPR_BUFFER. If the certificate is already in
517 the cache do not print a warning; just store the
518 fingerprint. FPR_BUFFER needs to be at least 20 bytes. */
520 cache_cert_silent (ksba_cert_t cert, void *fpr_buffer)
524 acquire_cache_write_lock ();
525 err = put_cert (cert, 0, 0, fpr_buffer);
526 release_cache_lock ();
527 if (gpg_err_code (err) == GPG_ERR_DUP_VALUE)
530 log_error (_("error caching certificate: %s\n"), gpg_strerror (err));
536 /* Return a certificate object for the given fingerprint. FPR is
537 expected to be a 20 byte binary SHA-1 fingerprint. If no matching
538 certificate is available in the cache NULL is returned. The caller
539 must release a returned certificate. Note that although we are
540 using reference counting the caller should not just compare the
541 pointers to check for identical certificates. */
543 get_cert_byfpr (const unsigned char *fpr)
547 acquire_cache_read_lock ();
548 for (ci=cert_cache[*fpr]; ci; ci = ci->next)
549 if (ci->cert && !memcmp (ci->fpr, fpr, 20))
551 ksba_cert_ref (ci->cert);
552 release_cache_lock ();
556 release_cache_lock ();
560 /* Return a certificate object for the given fingerprint. STRING is
561 expected to be a SHA-1 fingerprint in standard hex notation with or
562 without colons. If no matching certificate is available in the
563 cache NULL is returned. The caller must release a returned
564 certificate. Note that although we are using reference counting
565 the caller should not just compare the pointers to check for
566 identical certificates. */
568 get_cert_byhexfpr (const char *string)
570 unsigned char fpr[20];
574 if (strchr (string, ':'))
576 for (s=string,i=0; i < 20 && hexdigitp (s) && hexdigitp(s+1);)
578 if (s[2] && s[2] != ':')
579 break; /* Invalid string. */
580 fpr[i++] = xtoi_2 (s);
582 if (i!= 20 && *s == ':')
588 for (s=string,i=0; i < 20 && hexdigitp (s) && hexdigitp(s+1); s+=2 )
589 fpr[i++] = xtoi_2 (s);
593 log_error (_("invalid SHA1 fingerprint string '%s'\n"), string);
597 return get_cert_byfpr (fpr);
602 /* Return the certificate matching ISSUER_DN and SERIALNO. */
604 get_cert_bysn (const char *issuer_dn, ksba_sexp_t serialno)
606 /* Simple and inefficient implementation. fixme! */
610 acquire_cache_read_lock ();
611 for (i=0; i < 256; i++)
613 for (ci=cert_cache[i]; ci; ci = ci->next)
614 if (ci->cert && !strcmp (ci->issuer_dn, issuer_dn)
615 && !compare_serialno (ci->sn, serialno))
617 ksba_cert_ref (ci->cert);
618 release_cache_lock ();
623 release_cache_lock ();
628 /* Return the certificate matching ISSUER_DN. SEQ should initially be
629 set to 0 and bumped up to get the next issuer with that DN. */
631 get_cert_byissuer (const char *issuer_dn, unsigned int seq)
633 /* Simple and very inefficient implementation and API. fixme! */
637 acquire_cache_read_lock ();
638 for (i=0; i < 256; i++)
640 for (ci=cert_cache[i]; ci; ci = ci->next)
641 if (ci->cert && !strcmp (ci->issuer_dn, issuer_dn))
644 ksba_cert_ref (ci->cert);
645 release_cache_lock ();
650 release_cache_lock ();
655 /* Return the certificate matching SUBJECT_DN. SEQ should initially be
656 set to 0 and bumped up to get the next subject with that DN. */
658 get_cert_bysubject (const char *subject_dn, unsigned int seq)
660 /* Simple and very inefficient implementation and API. fixme! */
667 acquire_cache_read_lock ();
668 for (i=0; i < 256; i++)
670 for (ci=cert_cache[i]; ci; ci = ci->next)
671 if (ci->cert && ci->subject_dn
672 && !strcmp (ci->subject_dn, subject_dn))
675 ksba_cert_ref (ci->cert);
676 release_cache_lock ();
681 release_cache_lock ();
687 /* Return a value describing the the class of PATTERN. The offset of
688 the actual string to be used for the comparison is stored at
689 R_OFFSET. The offset of the serialnumer is stored at R_SN_OFFSET. */
690 static enum pattern_class
691 classify_pattern (const char *pattern, size_t *r_offset, size_t *r_sn_offset)
693 enum pattern_class result;
698 *r_offset = *r_sn_offset = 0;
700 /* Skip leading spaces. */
701 for(s = pattern; *s && spacep (s); s++ )
706 case 0: /* Empty string is an error. */
707 result = PATTERN_UNKNOWN;
710 case '.': /* An email address, compare from end. */
711 result = PATTERN_UNKNOWN; /* Not implemented. */
714 case '<': /* An email address. */
715 result = PATTERN_EMAIL;
719 case '@': /* Part of an email address. */
720 result = PATTERN_EMAIL_SUBSTR;
724 case '=': /* Exact compare. */
725 result = PATTERN_UNKNOWN; /* Does not make sense for X.509. */
728 case '*': /* Case insensitive substring search. */
729 result = PATTERN_SUBSTR;
733 case '+': /* Compare individual words. */
734 result = PATTERN_UNKNOWN; /* Not implemented. */
737 case '/': /* Subject's DN. */
739 if (!*s || spacep (s))
740 result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */
742 result = PATTERN_SUBJECT;
745 case '#': /* Serial number or issuer DN. */
752 /* An issuer's DN is indicated by "#/" */
754 if (!*s || spacep (s))
755 result = PATTERN_UNKNOWN; /* No DN or prefixed with a space. */
757 result = PATTERN_ISSUER;
760 { /* Serialnumber + optional issuer ID. */
761 for (si=s; *si && *si != '/'; si++)
762 if (!strchr("01234567890abcdefABCDEF", *si))
764 if (*si && *si != '/')
765 result = PATTERN_UNKNOWN; /* Invalid digit in serial number. */
768 *r_sn_offset = s - pattern;
770 result = PATTERN_SERIALNO;
774 if (!*s || spacep (s))
775 result = PATTERN_UNKNOWN; /* No DN or prefixed
778 result = PATTERN_SERIALNO_ISSUER;
785 case ':': /* Unified fingerprint. */
790 se = strchr (++s, ':');
792 result = PATTERN_UNKNOWN;
795 for (i=0, si=s; si < se; si++, i++ )
796 if (!strchr("01234567890abcdefABCDEF", *si))
799 result = PATTERN_UNKNOWN; /* Invalid digit. */
801 result = PATTERN_FINGERPRINT16;
803 result = PATTERN_FINGERPRINT20;
805 result = PATTERN_UNKNOWN; /* Invalid length for a fingerprint. */
810 case '&': /* Keygrip. */
811 result = PATTERN_UNKNOWN; /* Not implemented. */
815 if (s[0] == '0' && s[1] == 'x')
821 hexlength = strspn(s, "0123456789abcdefABCDEF");
823 /* Check if a hexadecimal number is terminated by EOS or blank. */
824 if (hexlength && s[hexlength] && !spacep (s+hexlength))
826 /* If the "0x" prefix is used a correct termination is required. */
829 result = PATTERN_UNKNOWN;
832 hexlength = 0; /* Not a hex number. */
835 if (hexlength == 8 || (!hexprefix && hexlength == 9 && *s == '0'))
839 result = PATTERN_SHORT_KEYID;
841 else if (hexlength == 16 || (!hexprefix && hexlength == 17 && *s == '0'))
845 result = PATTERN_LONG_KEYID;
847 else if (hexlength == 32 || (!hexprefix && hexlength == 33 && *s == '0'))
851 result = PATTERN_FINGERPRINT16;
853 else if (hexlength == 40 || (!hexprefix && hexlength == 41 && *s == '0'))
857 result = PATTERN_FINGERPRINT20;
861 /* The fingerprints used with X.509 are often delimited by
862 colons, so we try to single this case out. */
863 result = PATTERN_UNKNOWN;
864 hexlength = strspn (s, ":0123456789abcdefABCDEF");
865 if (hexlength == 59 && (!s[hexlength] || spacep (s+hexlength)))
869 for (i=0; i < 20; i++, s += 3)
872 if (c == -1 || (i < 19 && s[2] != ':'))
876 result = PATTERN_FINGERPRINT20;
878 if (result == PATTERN_UNKNOWN) /* Default to substring match. */
880 result = PATTERN_SUBSTR;
883 else /* A hex number with a prefix but with a wrong length. */
884 result = PATTERN_UNKNOWN;
887 if (result != PATTERN_UNKNOWN)
888 *r_offset = s - pattern;
894 /* Given PATTERN, which is a string as used by GnuPG to specify a
895 certificate, return all matching certificates by calling the
896 supplied function RETFNC. */
898 get_certs_bypattern (const char *pattern,
899 gpg_error_t (*retfnc)(void*,ksba_cert_t),
902 gpg_error_t err = GPG_ERR_BUG;
903 enum pattern_class class;
904 size_t offset, sn_offset;
905 const char *hexserialno;
906 ksba_sexp_t serialno = NULL;
907 ksba_cert_t cert = NULL;
910 if (!pattern || !retfnc)
911 return gpg_error (GPG_ERR_INV_ARG);
913 class = classify_pattern (pattern, &offset, &sn_offset);
914 hexserialno = pattern + sn_offset;
918 case PATTERN_UNKNOWN:
919 err = gpg_error (GPG_ERR_INV_NAME);
922 case PATTERN_FINGERPRINT20:
923 cert = get_cert_byhexfpr (pattern);
924 err = cert? 0 : gpg_error (GPG_ERR_NOT_FOUND);
927 case PATTERN_SERIALNO_ISSUER:
928 serialno = hexsn_to_sexp (hexserialno);
930 err = gpg_error_from_syserror ();
933 cert = get_cert_bysn (pattern, serialno);
934 err = cert? 0 : gpg_error (GPG_ERR_NOT_FOUND);
939 for (seq=0,err=0; !err && (cert = get_cert_byissuer (pattern, seq)); seq++)
941 err = retfnc (retfnc_data, cert);
942 ksba_cert_release (cert);
946 err = gpg_error (GPG_ERR_NOT_FOUND);
949 case PATTERN_SUBJECT:
950 for (seq=0,err=0; !err && (cert = get_cert_bysubject (pattern, seq));seq++)
952 err = retfnc (retfnc_data, cert);
953 ksba_cert_release (cert);
957 err = gpg_error (GPG_ERR_NOT_FOUND);
961 case PATTERN_EMAIL_SUBSTR:
962 case PATTERN_FINGERPRINT16:
963 case PATTERN_SHORT_KEYID:
964 case PATTERN_LONG_KEYID:
966 case PATTERN_SERIALNO:
968 err = gpg_error (GPG_ERR_INV_NAME);
973 err = retfnc (retfnc_data, cert);
974 ksba_cert_release (cert);
983 /* Return the certificate matching ISSUER_DN and SERIALNO; if it is
984 not already in the cache, try to find it from other resources. */
986 find_cert_bysn (ctrl_t ctrl, const char *issuer_dn, ksba_sexp_t serialno)
990 cert_fetch_context_t context = NULL;
993 /* First check whether it has already been cached. */
994 cert = get_cert_bysn (issuer_dn, serialno);
998 /* Ask back to the service requester to return the certificate.
999 This is because we can assume that he already used the
1000 certificate while checking for the CRL. */
1001 hexsn = serial_hex (serialno);
1004 log_error ("serial_hex() failed\n");
1007 buf = xtrymalloc (1 + strlen (hexsn) + 1 + strlen (issuer_dn) + 1);
1010 log_error ("can't allocate enough memory: %s\n", strerror (errno));
1014 strcpy (stpcpy (stpcpy (stpcpy (buf, "#"), hexsn),"/"), issuer_dn);
1016 cert = get_cert_local (ctrl, buf);
1021 return cert; /* Done. */
1025 log_debug ("find_cert_bysn: certificate not returned by caller"
1026 " - doing lookup\n");
1028 /* Retrieve the certificate from external resources. */
1036 err = ca_cert_fetch (ctrl, &context, issuer_dn);
1039 log_error (_("error fetching certificate by S/N: %s\n"),
1040 gpg_strerror (err));
1045 err = fetch_next_ksba_cert (context, &cert);
1048 log_error (_("error fetching certificate by S/N: %s\n"),
1049 gpg_strerror (err) );
1053 issdn = ksba_cert_get_issuer (cert, 0);
1054 if (strcmp (issuer_dn, issdn))
1056 log_debug ("find_cert_bysn: Ooops: issuer DN does not match\n");
1057 ksba_cert_release (cert);
1063 sn = ksba_cert_get_serial (cert);
1067 log_debug (" considering certificate (#");
1070 dump_string (issdn);
1074 if (!compare_serialno (serialno, sn))
1080 log_debug (" found\n");
1086 ksba_cert_release (cert);
1090 end_cert_fetch (context);
1095 /* Return the certificate matching SUBJECT_DN and (if not NULL)
1096 KEYID. If it is not already in the cache, try to find it from other
1097 resources. Note, that the external search does not work for user
1098 certificates because the LDAP lookup is on the caCertificate
1099 attribute. For our purposes this is just fine. */
1101 find_cert_bysubject (ctrl_t ctrl, const char *subject_dn, ksba_sexp_t keyid)
1105 ksba_cert_t cert = NULL;
1106 cert_fetch_context_t context = NULL;
1109 /* If we have certificates from an OCSP request we first try to use
1110 them. This is because these certificates will really be the
1111 required ones and thus even in the case that they can't be
1112 uniquely located by the following code we can use them. This is
1113 for example required by Telesec certificates where a keyId is
1114 used but the issuer certificate comes without a subject keyId! */
1115 if (ctrl->ocsp_certs && subject_dn)
1121 /* For efficiency reasons we won't use get_cert_bysubject here. */
1122 acquire_cache_read_lock ();
1123 for (i=0; i < 256; i++)
1124 for (ci=cert_cache[i]; ci; ci = ci->next)
1125 if (ci->cert && ci->subject_dn
1126 && !strcmp (ci->subject_dn, subject_dn))
1127 for (cr=ctrl->ocsp_certs; cr; cr = cr->next)
1128 if (!memcmp (ci->fpr, cr->fpr, 20))
1130 ksba_cert_ref (ci->cert);
1131 release_cache_lock ();
1132 return ci->cert; /* We use this certificate. */
1134 release_cache_lock ();
1136 log_debug ("find_cert_bysubject: certificate not in ocsp_certs\n");
1140 /* First we check whether the certificate is cached. */
1141 for (seq=0; (cert = get_cert_bysubject (subject_dn, seq)); seq++)
1144 break; /* No keyid requested, so return the first one found. */
1145 if (!ksba_cert_get_subj_key_id (cert, NULL, &subj)
1146 && !cmp_simple_canon_sexp (keyid, subj))
1149 break; /* Found matching cert. */
1152 ksba_cert_release (cert);
1155 return cert; /* Done. */
1158 log_debug ("find_cert_bysubject: certificate not in cache\n");
1160 /* Ask back to the service requester to return the certificate.
1161 This is because we can assume that he already used the
1162 certificate while checking for the CRL. */
1164 cert = get_cert_local_ski (ctrl, subject_dn, keyid);
1167 /* In contrast to get_cert_local_ski, get_cert_local uses any
1168 passed pattern, so we need to make sure that an exact subject
1172 buf = xtrymalloc (1 + strlen (subject_dn) + 1);
1175 log_error ("can't allocate enough memory: %s\n", strerror (errno));
1178 strcpy (stpcpy (buf, "/"), subject_dn);
1179 cert = get_cert_local (ctrl, buf);
1185 return cert; /* Done. */
1189 log_debug ("find_cert_bysubject: certificate not returned by caller"
1190 " - doing lookup\n");
1192 /* Locate the certificate using external resources. */
1199 err = ca_cert_fetch (ctrl, &context, subject_dn);
1202 log_error (_("error fetching certificate by subject: %s\n"),
1203 gpg_strerror (err));
1208 err = fetch_next_ksba_cert (context, &cert);
1211 log_error (_("error fetching certificate by subject: %s\n"),
1212 gpg_strerror (err) );
1216 subjdn = ksba_cert_get_subject (cert, 0);
1217 if (strcmp (subject_dn, subjdn))
1219 log_info ("find_cert_bysubject: subject DN does not match\n");
1220 ksba_cert_release (cert);
1229 log_debug (" considering certificate (/");
1230 dump_string (subjdn);
1235 /* If no key ID has been provided, we return the first match. */
1240 log_debug (" found\n");
1244 /* With the key ID given we need to compare it. */
1245 if (!ksba_cert_get_subj_key_id (cert, NULL, &subj))
1247 if (!cmp_simple_canon_sexp (keyid, subj))
1252 log_debug (" found\n");
1258 ksba_cert_release (cert);
1262 end_cert_fetch (context);
1268 /* Return 0 if the certificate is a trusted certificate. Returns
1269 GPG_ERR_NOT_TRUSTED if it is not trusted or other error codes in
1270 case of systems errors. */
1272 is_trusted_cert (ksba_cert_t cert)
1274 unsigned char fpr[20];
1277 cert_compute_fpr (cert, fpr);
1279 acquire_cache_read_lock ();
1280 for (ci=cert_cache[*fpr]; ci; ci = ci->next)
1281 if (ci->cert && !memcmp (ci->fpr, fpr, 20))
1283 if (ci->flags.trusted)
1285 release_cache_lock ();
1286 return 0; /* Yes, it is trusted. */
1291 release_cache_lock ();
1292 return gpg_error (GPG_ERR_NOT_TRUSTED);
1297 /* Given the certificate CERT locate the issuer for this certificate
1298 and return it at R_CERT. Returns 0 on success or
1299 GPG_ERR_NOT_FOUND. */
1301 find_issuing_cert (ctrl_t ctrl, ksba_cert_t cert, ksba_cert_t *r_cert)
1305 ksba_cert_t issuer_cert = NULL;
1307 ksba_sexp_t authidno;
1312 issuer_dn = ksba_cert_get_issuer (cert, 0);
1315 log_error (_("no issuer found in certificate\n"));
1316 err = gpg_error (GPG_ERR_BAD_CERT);
1320 /* First we need to check whether we can return that certificate
1321 using the authorithyKeyIdentifier. */
1322 err = ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno);
1325 log_info (_("error getting authorityKeyIdentifier: %s\n"),
1326 gpg_strerror (err));
1330 const char *s = ksba_name_enum (authid, 0);
1333 issuer_cert = find_cert_bysn (ctrl, s, authidno);
1335 if (!issuer_cert && keyid)
1337 /* Not found by issuer+s/n. Now that we have an AKI
1338 keyIdentifier look for a certificate with a matching
1340 issuer_cert = find_cert_bysubject (ctrl, issuer_dn, keyid);
1342 /* Print a note so that the user does not feel too helpless when
1343 an issuer certificate was found and gpgsm prints BAD
1344 signature because it is not the correct one. */
1347 log_info ("issuer certificate ");
1351 dump_serial (keyid);
1357 dump_serial (authidno);
1362 log_printf ("not found using authorityKeyIdentifier\n");
1364 ksba_name_release (authid);
1369 /* If this did not work, try just with the issuer's name and assume
1370 that there is only one such certificate. We only look into our
1372 if (err || !issuer_cert)
1374 issuer_cert = get_cert_bysubject (issuer_dn, 0);
1380 if (!err && !issuer_cert)
1381 err = gpg_error (GPG_ERR_NOT_FOUND);
1386 ksba_cert_release (issuer_cert);
1388 *r_cert = issuer_cert;