2006-12-21 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / sm / certchain.c
blob09ffe014e091517b655c8b1efa664ca5ef2c82fa
1 /* certchain.c - certificate chain validation
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2006 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 * USA.
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <time.h>
30 #include <stdarg.h>
31 #include <assert.h>
33 #define JNLIB_NEED_LOG_LOGV /* We need log_logv. */
35 #include "gpgsm.h"
36 #include <gcrypt.h>
37 #include <ksba.h>
39 #include "keydb.h"
40 #include "../kbx/keybox.h" /* for KEYBOX_FLAG_* */
41 #include "i18n.h"
44 /* Object to keep track of certain root certificates. */
45 struct marktrusted_info_s
47 struct marktrusted_info_s *next;
48 unsigned char fpr[20];
50 static struct marktrusted_info_s *marktrusted_info;
53 static int get_regtp_ca_info (ksba_cert_t cert, int *chainlen);
56 /* This function returns true if we already asked during this session
57 whether the root certificate CERT shall be marked as trusted. */
58 static int
59 already_asked_marktrusted (ksba_cert_t cert)
61 unsigned char fpr[20];
62 struct marktrusted_info_s *r;
64 gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
65 /* No context switches in the loop! */
66 for (r=marktrusted_info; r; r= r->next)
67 if (!memcmp (r->fpr, fpr, 20))
68 return 1;
69 return 0;
72 /* Flag certificate CERT as already asked whether it shall be marked
73 as trusted. */
74 static void
75 set_already_asked_marktrusted (ksba_cert_t cert)
77 unsigned char fpr[20];
78 struct marktrusted_info_s *r;
80 gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
81 for (r=marktrusted_info; r; r= r->next)
82 if (!memcmp (r->fpr, fpr, 20))
83 return; /* Already marked. */
84 r = xtrycalloc (1, sizeof *r);
85 if (!r)
86 return;
87 memcpy (r->fpr, fpr, 20);
88 r->next = marktrusted_info;
89 marktrusted_info = r;
92 /* If LISTMODE is true, print FORMAT using LISTMODE to FP. If
93 LISTMODE is false, use the string to print an log_info or, if
94 IS_ERROR is true, and log_error. */
95 static void
96 do_list (int is_error, int listmode, FILE *fp, const char *format, ...)
98 va_list arg_ptr;
100 va_start (arg_ptr, format) ;
101 if (listmode)
103 if (fp)
105 fputs (" [", fp);
106 vfprintf (fp, format, arg_ptr);
107 fputs ("]\n", fp);
110 else
112 log_logv (is_error? JNLIB_LOG_ERROR: JNLIB_LOG_INFO, format, arg_ptr);
113 log_printf ("\n");
115 va_end (arg_ptr);
118 /* Return 0 if A and B are equal. */
119 static int
120 compare_certs (ksba_cert_t a, ksba_cert_t b)
122 const unsigned char *img_a, *img_b;
123 size_t len_a, len_b;
125 img_a = ksba_cert_get_image (a, &len_a);
126 if (!img_a)
127 return 1;
128 img_b = ksba_cert_get_image (b, &len_b);
129 if (!img_b)
130 return 1;
131 return !(len_a == len_b && !memcmp (img_a, img_b, len_a));
135 static int
136 unknown_criticals (ksba_cert_t cert, int listmode, FILE *fp)
138 static const char *known[] = {
139 "2.5.29.15", /* keyUsage */
140 "2.5.29.19", /* basic Constraints */
141 "2.5.29.32", /* certificatePolicies */
142 "2.5.29.37", /* extendedKeyUsage - handled by certlist.c */
143 NULL
145 int rc = 0, i, idx, crit;
146 const char *oid;
147 gpg_error_t err;
149 for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
150 &oid, &crit, NULL, NULL));idx++)
152 if (!crit)
153 continue;
154 for (i=0; known[i] && strcmp (known[i],oid); i++)
156 if (!known[i])
158 do_list (1, listmode, fp,
159 _("critical certificate extension %s is not supported"),
160 oid);
161 rc = gpg_error (GPG_ERR_UNSUPPORTED_CERT);
164 /* We ignore the error codes EOF as well as no-value. The later will
165 occur for certificates with no extensions at all. */
166 if (err
167 && gpg_err_code (err) != GPG_ERR_EOF
168 && gpg_err_code (err) != GPG_ERR_NO_VALUE)
169 rc = err;
171 return rc;
175 /* Check whether CERT is an allowed certificate. This requires that
176 CERT matches all requirements for such a CA, i.e. the
177 BasicConstraints extension. The function returns 0 on success and
178 the awlloed length of the chain at CHAINLEN. */
179 static int
180 allowed_ca (ksba_cert_t cert, int *chainlen, int listmode, FILE *fp)
182 gpg_error_t err;
183 int flag;
185 err = ksba_cert_is_ca (cert, &flag, chainlen);
186 if (err)
187 return err;
188 if (!flag)
190 if (get_regtp_ca_info (cert, chainlen))
192 /* Note that dirmngr takes a different way to cope with such
193 certs. */
194 return 0; /* RegTP issued certificate. */
197 do_list (1, listmode, fp,_("issuer certificate is not marked as a CA"));
198 return gpg_error (GPG_ERR_BAD_CA_CERT);
200 return 0;
204 static int
205 check_cert_policy (ksba_cert_t cert, int listmode, FILE *fplist)
207 gpg_error_t err;
208 char *policies;
209 FILE *fp;
210 int any_critical;
212 err = ksba_cert_get_cert_policies (cert, &policies);
213 if (gpg_err_code (err) == GPG_ERR_NO_DATA
214 || gpg_err_code (err) == GPG_ERR_NO_VALUE)
215 return 0; /* No policy given. */
216 if (err)
217 return err;
219 /* STRING is a line delimited list of certifiate policies as stored
220 in the certificate. The line itself is colon delimited where the
221 first field is the OID of the policy and the second field either
222 N or C for normal or critical extension */
224 if (opt.verbose > 1 && !listmode)
225 log_info ("certificate's policy list: %s\n", policies);
227 /* The check is very minimal but won't give false positives */
228 any_critical = !!strstr (policies, ":C");
230 if (!opt.policy_file)
232 xfree (policies);
233 if (any_critical)
235 do_list (1, listmode, fplist,
236 _("critical marked policy without configured policies"));
237 return gpg_error (GPG_ERR_NO_POLICY_MATCH);
239 return 0;
242 fp = fopen (opt.policy_file, "r");
243 if (!fp)
245 if (opt.verbose || errno != ENOENT)
246 log_info (_("failed to open `%s': %s\n"),
247 opt.policy_file, strerror (errno));
248 xfree (policies);
249 /* With no critical policies this is only a warning */
250 if (!any_critical)
252 do_list (0, listmode, fplist,
253 _("note: non-critical certificate policy not allowed"));
254 return 0;
256 do_list (1, listmode, fplist,
257 _("certificate policy not allowed"));
258 return gpg_error (GPG_ERR_NO_POLICY_MATCH);
261 for (;;)
263 int c;
264 char *p, line[256];
265 char *haystack, *allowed;
267 /* read line */
270 if (!fgets (line, DIM(line)-1, fp) )
272 gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
274 xfree (policies);
275 if (feof (fp))
277 fclose (fp);
278 /* With no critical policies this is only a warning */
279 if (!any_critical)
281 do_list (0, listmode, fplist,
282 _("note: non-critical certificate policy not allowed"));
283 return 0;
285 do_list (1, listmode, fplist,
286 _("certificate policy not allowed"));
287 return gpg_error (GPG_ERR_NO_POLICY_MATCH);
289 fclose (fp);
290 return tmperr;
293 if (!*line || line[strlen(line)-1] != '\n')
295 /* eat until end of line */
296 while ( (c=getc (fp)) != EOF && c != '\n')
298 fclose (fp);
299 xfree (policies);
300 return gpg_error (*line? GPG_ERR_LINE_TOO_LONG
301 : GPG_ERR_INCOMPLETE_LINE);
304 /* Allow for empty lines and spaces */
305 for (p=line; spacep (p); p++)
308 while (!*p || *p == '\n' || *p == '#');
310 /* parse line */
311 for (allowed=line; spacep (allowed); allowed++)
313 p = strpbrk (allowed, " :\n");
314 if (!*p || p == allowed)
316 fclose (fp);
317 xfree (policies);
318 return gpg_error (GPG_ERR_CONFIGURATION);
320 *p = 0; /* strip the rest of the line */
321 /* See whether we find ALLOWED (which is an OID) in POLICIES */
322 for (haystack=policies; (p=strstr (haystack, allowed)); haystack = p+1)
324 if ( !(p == policies || p[-1] == '\n') )
325 continue; /* Does not match the begin of a line. */
326 if (p[strlen (allowed)] != ':')
327 continue; /* The length does not match. */
328 /* Yep - it does match so return okay. */
329 fclose (fp);
330 xfree (policies);
331 return 0;
337 /* Helper function for find_up. This resets the key handle and search
338 for an issuer ISSUER with a subjectKeyIdentifier of KEYID. Returns
339 0 obn success or -1 when not found. */
340 static int
341 find_up_search_by_keyid (KEYDB_HANDLE kh,
342 const char *issuer, ksba_sexp_t keyid)
344 int rc;
345 ksba_cert_t cert = NULL;
346 ksba_sexp_t subj = NULL;
348 keydb_search_reset (kh);
349 while (!(rc = keydb_search_subject (kh, issuer)))
351 ksba_cert_release (cert); cert = NULL;
352 rc = keydb_get_cert (kh, &cert);
353 if (rc)
355 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
356 rc = -1;
357 break;
359 xfree (subj);
360 if (!ksba_cert_get_subj_key_id (cert, NULL, &subj))
362 if (!cmp_simple_canon_sexp (keyid, subj))
363 break; /* Found matching cert. */
367 ksba_cert_release (cert);
368 xfree (subj);
369 return rc? -1:0;
373 static void
374 find_up_store_certs_cb (void *cb_value, ksba_cert_t cert)
376 if (keydb_store_cert (cert, 1, NULL))
377 log_error ("error storing issuer certificate as ephemeral\n");
378 ++*(int*)cb_value;
382 /* Helper for find_up(). Locate the certificate for ISSUER using an
383 external lookup. KH is the keydb context we are currently using.
384 On success 0 is returned and the certificate may be retrieved from
385 the keydb using keydb_get_cert(). KEYID is the keyIdentifier from
386 the AKI or NULL. */
387 static int
388 find_up_external (KEYDB_HANDLE kh, const char *issuer, ksba_sexp_t keyid)
390 int rc;
391 strlist_t names = NULL;
392 int count = 0;
393 char *pattern;
394 const char *s;
396 if (opt.verbose)
397 log_info (_("looking up issuer at external location\n"));
398 /* The DIRMNGR process is confused about unknown attributes. As a
399 quick and ugly hack we locate the CN and use the issuer string
400 starting at this attribite. Fixme: we should have far better
401 parsing in the dirmngr. */
402 s = strstr (issuer, "CN=");
403 if (!s || s == issuer || s[-1] != ',')
404 s = issuer;
406 pattern = xtrymalloc (strlen (s)+2);
407 if (!pattern)
408 return gpg_error_from_syserror ();
409 strcpy (stpcpy (pattern, "/"), s);
410 add_to_strlist (&names, pattern);
411 xfree (pattern);
413 rc = gpgsm_dirmngr_lookup (NULL, names, find_up_store_certs_cb, &count);
414 free_strlist (names);
416 if (opt.verbose)
417 log_info (_("number of issuers matching: %d\n"), count);
418 if (rc)
420 log_error ("external key lookup failed: %s\n", gpg_strerror (rc));
421 rc = -1;
423 else if (!count)
424 rc = -1;
425 else
427 int old;
428 /* The issuers are currently stored in the ephemeral key DB, so
429 we temporary switch to ephemeral mode. */
430 old = keydb_set_ephemeral (kh, 1);
431 if (keyid)
432 rc = find_up_search_by_keyid (kh, issuer, keyid);
433 else
435 keydb_search_reset (kh);
436 rc = keydb_search_subject (kh, issuer);
438 keydb_set_ephemeral (kh, old);
440 return rc;
444 /* Locate issuing certificate for CERT. ISSUER is the name of the
445 issuer used as a fallback if the other methods don't work. If
446 FIND_NEXT is true, the function shall return the next possible
447 issuer. The certificate itself is not directly returned but a
448 keydb_get_cert on the keyDb context KH will return it. Returns 0
449 on success, -1 if not found or an error code. */
450 static int
451 find_up (KEYDB_HANDLE kh, ksba_cert_t cert, const char *issuer, int find_next)
453 ksba_name_t authid;
454 ksba_sexp_t authidno;
455 ksba_sexp_t keyid;
456 int rc = -1;
458 if (!ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno))
460 const char *s = ksba_name_enum (authid, 0);
461 if (s && *authidno)
463 rc = keydb_search_issuer_sn (kh, s, authidno);
464 if (rc)
465 keydb_search_reset (kh);
467 /* In case of an error try the ephemeral DB. We can't do
468 that in find_next mode because we can't keep the search
469 state then. */
470 if (rc == -1 && !find_next)
472 int old = keydb_set_ephemeral (kh, 1);
473 if (!old)
475 rc = keydb_search_issuer_sn (kh, s, authidno);
476 if (rc)
477 keydb_search_reset (kh);
479 keydb_set_ephemeral (kh, old);
484 if (rc == -1 && keyid && !find_next)
486 /* Not found by AIK.issuer_sn. Lets try the AIY.ki
487 instead. Loop over all certificates with that issuer as
488 subject and stop for the one with a matching
489 subjectKeyIdentifier. */
490 rc = find_up_search_by_keyid (kh, issuer, keyid);
491 if (rc)
493 int old = keydb_set_ephemeral (kh, 1);
494 if (!old)
495 rc = find_up_search_by_keyid (kh, issuer, keyid);
496 keydb_set_ephemeral (kh, old);
498 if (rc)
499 rc = -1; /* Need to make sure to have this error code. */
502 /* If we still didn't found it, try an external lookup. */
503 if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
504 rc = find_up_external (kh, issuer, keyid);
506 /* Print a note so that the user does not feel too helpless when
507 an issuer certificate was found and gpgsm prints BAD
508 signature because it is not the correct one. */
509 if (rc == -1)
511 log_info ("%sissuer certificate ", find_next?"next ":"");
512 if (keyid)
514 log_printf ("{");
515 gpgsm_dump_serial (keyid);
516 log_printf ("} ");
518 if (authidno)
520 log_printf ("(#");
521 gpgsm_dump_serial (authidno);
522 log_printf ("/");
523 gpgsm_dump_string (s);
524 log_printf (") ");
526 log_printf ("not found using authorityKeyIdentifier\n");
528 else if (rc)
529 log_error ("failed to find authorityKeyIdentifier: rc=%d\n", rc);
530 xfree (keyid);
531 ksba_name_release (authid);
532 xfree (authidno);
535 if (rc) /* Not found via authorithyKeyIdentifier, try regular issuer name. */
536 rc = keydb_search_subject (kh, issuer);
537 if (rc == -1 && !find_next)
539 /* Not found, lets see whether we have one in the ephemeral key DB. */
540 int old = keydb_set_ephemeral (kh, 1);
541 if (!old)
543 keydb_search_reset (kh);
544 rc = keydb_search_subject (kh, issuer);
546 keydb_set_ephemeral (kh, old);
549 /* Still not found. If enabled, try an external lookup. */
550 if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
551 rc = find_up_external (kh, issuer, NULL);
553 return rc;
557 /* Return the next certificate up in the chain starting at START.
558 Returns -1 when there are no more certificates. */
560 gpgsm_walk_cert_chain (ksba_cert_t start, ksba_cert_t *r_next)
562 int rc = 0;
563 char *issuer = NULL;
564 char *subject = NULL;
565 KEYDB_HANDLE kh = keydb_new (0);
567 *r_next = NULL;
568 if (!kh)
570 log_error (_("failed to allocated keyDB handle\n"));
571 rc = gpg_error (GPG_ERR_GENERAL);
572 goto leave;
575 issuer = ksba_cert_get_issuer (start, 0);
576 subject = ksba_cert_get_subject (start, 0);
577 if (!issuer)
579 log_error ("no issuer found in certificate\n");
580 rc = gpg_error (GPG_ERR_BAD_CERT);
581 goto leave;
583 if (!subject)
585 log_error ("no subject found in certificate\n");
586 rc = gpg_error (GPG_ERR_BAD_CERT);
587 goto leave;
590 if (!strcmp (issuer, subject))
592 rc = -1; /* we are at the root */
593 goto leave;
596 rc = find_up (kh, start, issuer, 0);
597 if (rc)
599 /* it is quite common not to have a certificate, so better don't
600 print an error here */
601 if (rc != -1 && opt.verbose > 1)
602 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
603 rc = gpg_error (GPG_ERR_MISSING_CERT);
604 goto leave;
607 rc = keydb_get_cert (kh, r_next);
608 if (rc)
610 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
611 rc = gpg_error (GPG_ERR_GENERAL);
614 leave:
615 xfree (issuer);
616 xfree (subject);
617 keydb_release (kh);
618 return rc;
622 /* Check whether the CERT is a root certificate. Returns True if this
623 is the case. */
625 gpgsm_is_root_cert (ksba_cert_t cert)
627 char *issuer;
628 char *subject;
629 int yes;
631 issuer = ksba_cert_get_issuer (cert, 0);
632 subject = ksba_cert_get_subject (cert, 0);
633 yes = (issuer && subject && !strcmp (issuer, subject));
634 xfree (issuer);
635 xfree (subject);
636 return yes;
640 /* This is a helper for gpgsm_validate_chain. */
641 static gpg_error_t
642 is_cert_still_valid (ctrl_t ctrl, int lm, FILE *fp,
643 ksba_cert_t subject_cert, ksba_cert_t issuer_cert,
644 int *any_revoked, int *any_no_crl, int *any_crl_too_old)
646 if (!opt.no_crl_check || ctrl->use_ocsp)
648 gpg_error_t err;
650 err = gpgsm_dirmngr_isvalid (ctrl,
651 subject_cert, issuer_cert, ctrl->use_ocsp);
652 if (err)
654 /* Fixme: We should change the wording because we may
655 have used OCSP. */
656 if (!lm)
657 gpgsm_cert_log_name (NULL, subject_cert);
658 switch (gpg_err_code (err))
660 case GPG_ERR_CERT_REVOKED:
661 do_list (1, lm, fp, _("certificate has been revoked"));
662 *any_revoked = 1;
663 /* Store that in the keybox so that key listings are
664 able to return the revoked flag. We don't care
665 about error, though. */
666 keydb_set_cert_flags (subject_cert, KEYBOX_FLAG_VALIDITY, 0,
667 VALIDITY_REVOKED);
668 break;
669 case GPG_ERR_NO_CRL_KNOWN:
670 do_list (1, lm, fp, _("no CRL found for certificate"));
671 *any_no_crl = 1;
672 break;
673 case GPG_ERR_CRL_TOO_OLD:
674 do_list (1, lm, fp, _("the available CRL is too old"));
675 if (!lm)
676 log_info (_("please make sure that the "
677 "\"dirmngr\" is properly installed\n"));
678 *any_crl_too_old = 1;
679 break;
680 default:
681 do_list (1, lm, fp, _("checking the CRL failed: %s"),
682 gpg_strerror (err));
683 return err;
687 return 0;
692 /* Validate a chain and optionally return the nearest expiration time
693 in R_EXPTIME. With LISTMODE set to 1 a special listmode is
694 activated where only information about the certificate is printed
695 to FP and no output is send to the usual log stream.
697 Defined flag bits: 0 - do not do any dirmngr isvalid checks.
700 gpgsm_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t r_exptime,
701 int listmode, FILE *fp, unsigned int flags)
703 int rc = 0, depth = 0, maxdepth;
704 char *issuer = NULL;
705 char *subject = NULL;
706 KEYDB_HANDLE kh = NULL;
707 ksba_cert_t subject_cert = NULL, issuer_cert = NULL;
708 ksba_isotime_t current_time;
709 ksba_isotime_t exptime;
710 int any_expired = 0;
711 int any_revoked = 0;
712 int any_no_crl = 0;
713 int any_crl_too_old = 0;
714 int any_no_policy_match = 0;
715 int is_qualified = -1; /* Indicates whether the certificate stems
716 from a qualified root certificate.
717 -1 = unknown, 0 = no, 1 = yes. */
718 int lm = listmode;
720 gnupg_get_isotime (current_time);
721 if (r_exptime)
722 *r_exptime = 0;
723 *exptime = 0;
725 if (opt.no_chain_validation && !listmode)
727 log_info ("WARNING: bypassing certificate chain validation\n");
728 return 0;
731 kh = keydb_new (0);
732 if (!kh)
734 log_error (_("failed to allocated keyDB handle\n"));
735 rc = gpg_error (GPG_ERR_GENERAL);
736 goto leave;
739 if (DBG_X509 && !listmode)
740 gpgsm_dump_cert ("target", cert);
742 subject_cert = cert;
743 ksba_cert_ref (subject_cert);
744 maxdepth = 50;
746 for (;;)
748 int is_root;
749 gpg_error_t istrusted_rc = -1;
750 struct rootca_flags_s rootca_flags;
752 xfree (issuer);
753 xfree (subject);
754 issuer = ksba_cert_get_issuer (subject_cert, 0);
755 subject = ksba_cert_get_subject (subject_cert, 0);
757 if (!issuer)
759 do_list (1, lm, fp, _("no issuer found in certificate"));
760 rc = gpg_error (GPG_ERR_BAD_CERT);
761 goto leave;
764 /* Is this a self-issued certificate (i.e. the root certificate)? */
765 is_root = (subject && !strcmp (issuer, subject));
766 if (is_root)
768 /* Check early whether the certificate is listed as trusted.
769 We used to do this only later but changed it to call the
770 check right here so that we can access special flags
771 associated with that specific root certificate. */
772 istrusted_rc = gpgsm_agent_istrusted (ctrl, subject_cert,
773 &rootca_flags);
777 /* Check the validity period. */
779 ksba_isotime_t not_before, not_after;
781 rc = ksba_cert_get_validity (subject_cert, 0, not_before);
782 if (!rc)
783 rc = ksba_cert_get_validity (subject_cert, 1, not_after);
784 if (rc)
786 do_list (1, lm, fp, _("certificate with invalid validity: %s"),
787 gpg_strerror (rc));
788 rc = gpg_error (GPG_ERR_BAD_CERT);
789 goto leave;
792 if (*not_after)
794 if (!*exptime)
795 gnupg_copy_time (exptime, not_after);
796 else if (strcmp (not_after, exptime) < 0 )
797 gnupg_copy_time (exptime, not_after);
800 if (*not_before && strcmp (current_time, not_before) < 0 )
802 do_list (1, lm, fp, _("certificate not yet valid"));
803 if (!lm)
805 log_info ("(valid from ");
806 gpgsm_dump_time (not_before);
807 log_printf (")\n");
809 rc = gpg_error (GPG_ERR_CERT_TOO_YOUNG);
810 goto leave;
812 if (*not_after && strcmp (current_time, not_after) > 0 )
814 do_list (opt.ignore_expiration?0:1, lm, fp,
815 _("certificate has expired"));
816 if (!lm)
818 log_info ("(expired at ");
819 gpgsm_dump_time (not_after);
820 log_printf (")\n");
822 if (opt.ignore_expiration)
823 log_info ("WARNING: ignoring expiration\n");
824 else
825 any_expired = 1;
829 /* Assert that we understand all critical extensions. */
830 rc = unknown_criticals (subject_cert, listmode, fp);
831 if (rc)
832 goto leave;
834 /* Do a policy check. */
835 if (!opt.no_policy_check)
837 rc = check_cert_policy (subject_cert, listmode, fp);
838 if (gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH)
840 any_no_policy_match = 1;
841 rc = 1;
843 else if (rc)
844 goto leave;
848 /* Is this a self-issued certificate? */
849 if (is_root)
851 if (!istrusted_rc)
852 ; /* No need to check the certificate for a trusted one. */
853 else if (gpgsm_check_cert_sig (subject_cert, subject_cert) )
855 /* We only check the signature if the certificate is not
856 trusted for better diagnostics. */
857 do_list (1, lm, fp,
858 _("self-signed certificate has a BAD signature"));
859 if (DBG_X509)
861 gpgsm_dump_cert ("self-signing cert", subject_cert);
863 rc = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN
864 : GPG_ERR_BAD_CERT);
865 goto leave;
867 if (!rootca_flags.relax)
869 rc = allowed_ca (subject_cert, NULL, listmode, fp);
870 if (rc)
871 goto leave;
875 /* Set the flag for qualified signatures. This flag is
876 deduced from a list of root certificates allowed for
877 qualified signatures. */
878 if (is_qualified == -1)
880 gpg_error_t err;
881 size_t buflen;
882 char buf[1];
884 if (!ksba_cert_get_user_data (cert, "is_qualified",
885 &buf, sizeof (buf),
886 &buflen) && buflen)
888 /* We already checked this for this certificate,
889 thus we simply take it from the user data. */
890 is_qualified = !!*buf;
892 else
894 /* Need to consult the list of root certificates for
895 qualified signatures. */
896 err = gpgsm_is_in_qualified_list (ctrl, subject_cert, NULL);
897 if (!err)
898 is_qualified = 1;
899 else if ( gpg_err_code (err) == GPG_ERR_NOT_FOUND)
900 is_qualified = 0;
901 else
902 log_error ("checking the list of qualified "
903 "root certificates failed: %s\n",
904 gpg_strerror (err));
905 if ( is_qualified != -1 )
907 /* Cache the result but don't care too much
908 about an error. */
909 buf[0] = !!is_qualified;
910 err = ksba_cert_set_user_data (subject_cert,
911 "is_qualified", buf, 1);
912 if (err)
913 log_error ("set_user_data(is_qualified) failed: %s\n",
914 gpg_strerror (err));
920 /* Act on the check for a trusted root certificates. */
921 rc = istrusted_rc;
922 if (!rc)
924 else if (gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
926 do_list (0, lm, fp, _("root certificate is not marked trusted"));
927 /* If we already figured out that the certificate is
928 expired it does not make much sense to ask the user
929 whether we wants to trust the root certificate. He
930 should do this only if the certificate under question
931 will then be usable. We also check whether the agent
932 is at all enabled to allo marktrusted and don't call
933 it in this session again if it is not. */
934 if ( !any_expired
935 && (!lm || !already_asked_marktrusted (subject_cert)))
937 static int no_more_questions; /* during this session. */
938 int rc2;
939 char *fpr = gpgsm_get_fingerprint_string (subject_cert,
940 GCRY_MD_SHA1);
941 log_info (_("fingerprint=%s\n"), fpr? fpr : "?");
942 xfree (fpr);
943 if (no_more_questions)
944 rc2 = gpg_error (GPG_ERR_NOT_SUPPORTED);
945 else
946 rc2 = gpgsm_agent_marktrusted (ctrl, subject_cert);
947 if (!rc2)
949 log_info (_("root certificate has now"
950 " been marked as trusted\n"));
951 rc = 0;
953 else if (!lm)
955 gpgsm_dump_cert ("issuer", subject_cert);
956 log_info ("after checking the fingerprint, you may want "
957 "to add it manually to the list of trusted "
958 "certificates.\n");
961 if (gpg_err_code (rc2) == GPG_ERR_NOT_SUPPORTED)
963 if (!no_more_questions)
964 log_info (_("interactive marking as trusted "
965 "not enabled in gpg-agent\n"));
966 no_more_questions = 1;
968 else if (gpg_err_code (rc2) == GPG_ERR_CANCELED)
970 log_info (_("interactive marking as trusted "
971 "disabled for this session\n"));
972 no_more_questions = 1;
974 else
975 set_already_asked_marktrusted (subject_cert);
978 else
980 log_error (_("checking the trust list failed: %s\n"),
981 gpg_strerror (rc));
984 if (rc)
985 goto leave;
987 /* Check for revocations etc. */
988 if ((flags & 1))
990 else if (opt.no_trusted_cert_crl_check || rootca_flags.relax)
992 else
993 rc = is_cert_still_valid (ctrl, lm, fp,
994 subject_cert, subject_cert,
995 &any_revoked, &any_no_crl,
996 &any_crl_too_old);
997 if (rc)
998 goto leave;
1000 break; /* Okay: a self-signed certicate is an end-point. */
1003 /* Take care that the chain does not get too long. */
1004 depth++;
1005 if (depth > maxdepth)
1007 do_list (1, lm, fp, _("certificate chain too long\n"));
1008 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1009 goto leave;
1012 /* Find the next cert up the tree. */
1013 keydb_search_reset (kh);
1014 rc = find_up (kh, subject_cert, issuer, 0);
1015 if (rc)
1017 if (rc == -1)
1019 do_list (0, lm, fp, _("issuer certificate not found"));
1020 if (!lm)
1022 log_info ("issuer certificate: #/");
1023 gpgsm_dump_string (issuer);
1024 log_printf ("\n");
1027 else
1028 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
1029 rc = gpg_error (GPG_ERR_MISSING_CERT);
1030 goto leave;
1033 ksba_cert_release (issuer_cert); issuer_cert = NULL;
1034 rc = keydb_get_cert (kh, &issuer_cert);
1035 if (rc)
1037 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
1038 rc = gpg_error (GPG_ERR_GENERAL);
1039 goto leave;
1042 try_another_cert:
1043 if (DBG_X509)
1045 log_debug ("got issuer's certificate:\n");
1046 gpgsm_dump_cert ("issuer", issuer_cert);
1049 rc = gpgsm_check_cert_sig (issuer_cert, subject_cert);
1050 if (rc)
1052 do_list (0, lm, fp, _("certificate has a BAD signature"));
1053 if (DBG_X509)
1055 gpgsm_dump_cert ("signing issuer", issuer_cert);
1056 gpgsm_dump_cert ("signed subject", subject_cert);
1058 if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
1060 /* We now try to find other issuer certificates which
1061 might have been used. This is required because some
1062 CAs are reusing the issuer and subject DN for new
1063 root certificates. */
1064 /* FIXME: Do this only if we don't have an
1065 AKI.keyIdentifier */
1066 rc = find_up (kh, subject_cert, issuer, 1);
1067 if (!rc)
1069 ksba_cert_t tmp_cert;
1071 rc = keydb_get_cert (kh, &tmp_cert);
1072 if (rc || !compare_certs (issuer_cert, tmp_cert))
1074 /* The find next did not work or returned an
1075 identical certificate. We better stop here
1076 to avoid infinite checks. */
1077 rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
1078 ksba_cert_release (tmp_cert);
1080 else
1082 do_list (0, lm, fp, _("found another possible matching "
1083 "CA certificate - trying again"));
1084 ksba_cert_release (issuer_cert);
1085 issuer_cert = tmp_cert;
1086 goto try_another_cert;
1091 /* We give a more descriptive error code than the one
1092 returned from the signature checking. */
1093 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1094 goto leave;
1097 is_root = 0;
1098 istrusted_rc = -1;
1100 /* Check that a CA is allowed to issue certificates. */
1102 int chainlen;
1104 rc = allowed_ca (issuer_cert, &chainlen, listmode, fp);
1105 if (rc)
1107 /* Not allowed. Check whether this is a trusted root
1108 certificate and whether we allow special exceptions.
1109 We could carry the result of the test over to the
1110 regular root check at the top of the loop but for
1111 clarity we won't do that. Given that the majority of
1112 certificates carry proper BasicContraints our way of
1113 overriding an error in the way is justified for
1114 performance reasons. */
1115 if (gpgsm_is_root_cert (issuer_cert))
1117 is_root = 1;
1118 istrusted_rc = gpgsm_agent_istrusted (ctrl, issuer_cert,
1119 &rootca_flags);
1120 if (!istrusted_rc && rootca_flags.relax)
1122 /* Ignore the error due to the relax flag. */
1123 rc = 0;
1124 chainlen = -1;
1128 if (rc)
1129 goto leave;
1130 if (chainlen >= 0 && (depth - 1) > chainlen)
1132 do_list (1, lm, fp,
1133 _("certificate chain longer than allowed by CA (%d)"),
1134 chainlen);
1135 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1136 goto leave;
1140 /* Is the certificate allowed to sign other certificates. */
1141 if (!listmode)
1143 rc = gpgsm_cert_use_cert_p (issuer_cert);
1144 if (rc)
1146 char numbuf[50];
1147 sprintf (numbuf, "%d", rc);
1148 gpgsm_status2 (ctrl, STATUS_ERROR, "certcert.issuer.keyusage",
1149 numbuf, NULL);
1150 goto leave;
1154 /* Check for revocations etc. Note that for a root certioficate
1155 this test is done a second time later. This should eventually
1156 be fixed. */
1157 if ((flags & 1))
1158 rc = 0;
1159 else if (is_root && (opt.no_trusted_cert_crl_check
1160 || (!istrusted_rc && rootca_flags.relax)))
1162 else
1163 rc = is_cert_still_valid (ctrl, lm, fp,
1164 subject_cert, issuer_cert,
1165 &any_revoked, &any_no_crl, &any_crl_too_old);
1166 if (rc)
1167 goto leave;
1170 if (opt.verbose && !listmode)
1171 log_info ("certificate is good\n");
1173 /* For the next round the current issuer becomes the new subject. */
1174 keydb_search_reset (kh);
1175 ksba_cert_release (subject_cert);
1176 subject_cert = issuer_cert;
1177 issuer_cert = NULL;
1178 } /* End chain traversal. */
1180 if (!listmode)
1182 if (opt.no_policy_check)
1183 log_info ("policies not checked due to %s option\n",
1184 "--disable-policy-checks");
1185 if (opt.no_crl_check && !ctrl->use_ocsp)
1186 log_info ("CRLs not checked due to %s option\n",
1187 "--disable-crl-checks");
1190 if (!rc)
1191 { /* If we encountered an error somewhere during the checks, set
1192 the error code to the most critical one */
1193 if (any_revoked)
1194 rc = gpg_error (GPG_ERR_CERT_REVOKED);
1195 else if (any_expired)
1196 rc = gpg_error (GPG_ERR_CERT_EXPIRED);
1197 else if (any_no_crl)
1198 rc = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1199 else if (any_crl_too_old)
1200 rc = gpg_error (GPG_ERR_CRL_TOO_OLD);
1201 else if (any_no_policy_match)
1202 rc = gpg_error (GPG_ERR_NO_POLICY_MATCH);
1205 leave:
1206 if (is_qualified != -1)
1208 /* We figured something about the qualified signature capability
1209 of the certificate under question. Store the result as user
1210 data in the certificate object. We do this even if the
1211 validation itself failed. */
1212 /* Fixme: We should set this flag for all certificates in the
1213 chain for optimizing reasons. */
1214 char buf[1];
1215 gpg_error_t err;
1217 buf[0] = !!is_qualified;
1218 err = ksba_cert_set_user_data (cert, "is_qualified", buf, 1);
1219 if (err)
1221 log_error ("set_user_data(is_qualified) failed: %s\n",
1222 gpg_strerror (err));
1223 if (!rc)
1224 rc = err;
1227 if (r_exptime)
1228 gnupg_copy_time (r_exptime, exptime);
1229 xfree (issuer);
1230 xfree (subject);
1231 keydb_release (kh);
1232 ksba_cert_release (issuer_cert);
1233 ksba_cert_release (subject_cert);
1234 return rc;
1238 /* Check that the given certificate is valid but DO NOT check any
1239 constraints. We assume that the issuers certificate is already in
1240 the DB and that this one is valid; which it should be because it
1241 has been checked using this function. */
1243 gpgsm_basic_cert_check (ksba_cert_t cert)
1245 int rc = 0;
1246 char *issuer = NULL;
1247 char *subject = NULL;
1248 KEYDB_HANDLE kh;
1249 ksba_cert_t issuer_cert = NULL;
1251 if (opt.no_chain_validation)
1253 log_info ("WARNING: bypassing basic certificate checks\n");
1254 return 0;
1257 kh = keydb_new (0);
1258 if (!kh)
1260 log_error (_("failed to allocated keyDB handle\n"));
1261 rc = gpg_error (GPG_ERR_GENERAL);
1262 goto leave;
1265 issuer = ksba_cert_get_issuer (cert, 0);
1266 subject = ksba_cert_get_subject (cert, 0);
1267 if (!issuer)
1269 log_error ("no issuer found in certificate\n");
1270 rc = gpg_error (GPG_ERR_BAD_CERT);
1271 goto leave;
1274 if (subject && !strcmp (issuer, subject))
1276 rc = gpgsm_check_cert_sig (cert, cert);
1277 if (rc)
1279 log_error ("self-signed certificate has a BAD signature: %s\n",
1280 gpg_strerror (rc));
1281 if (DBG_X509)
1283 gpgsm_dump_cert ("self-signing cert", cert);
1285 rc = gpg_error (GPG_ERR_BAD_CERT);
1286 goto leave;
1289 else
1291 /* Find the next cert up the tree. */
1292 keydb_search_reset (kh);
1293 rc = find_up (kh, cert, issuer, 0);
1294 if (rc)
1296 if (rc == -1)
1298 log_info ("issuer certificate (#/");
1299 gpgsm_dump_string (issuer);
1300 log_printf (") not found\n");
1302 else
1303 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
1304 rc = gpg_error (GPG_ERR_MISSING_CERT);
1305 goto leave;
1308 ksba_cert_release (issuer_cert); issuer_cert = NULL;
1309 rc = keydb_get_cert (kh, &issuer_cert);
1310 if (rc)
1312 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
1313 rc = gpg_error (GPG_ERR_GENERAL);
1314 goto leave;
1317 rc = gpgsm_check_cert_sig (issuer_cert, cert);
1318 if (rc)
1320 log_error ("certificate has a BAD signature: %s\n",
1321 gpg_strerror (rc));
1322 if (DBG_X509)
1324 gpgsm_dump_cert ("signing issuer", issuer_cert);
1325 gpgsm_dump_cert ("signed subject", cert);
1327 rc = gpg_error (GPG_ERR_BAD_CERT);
1328 goto leave;
1330 if (opt.verbose)
1331 log_info ("certificate is good\n");
1334 leave:
1335 xfree (issuer);
1336 keydb_release (kh);
1337 ksba_cert_release (issuer_cert);
1338 return rc;
1343 /* Check whether the certificate CERT has been issued by the German
1344 authority for qualified signature. They do not set the
1345 basicConstraints and thus we need this workaround. It works by
1346 looking up the root certificate and checking whether that one is
1347 listed as a qualified certificate for Germany.
1349 We also try to cache this data but as long as don't keep a
1350 reference to the certificate this won't be used.
1352 Returns: True if CERT is a RegTP issued CA cert (i.e. the root
1353 certificate itself or one of the CAs). In that case CHAINLEN will
1354 receive the length of the chain which is either 0 or 1.
1356 static int
1357 get_regtp_ca_info (ksba_cert_t cert, int *chainlen)
1359 gpg_error_t err;
1360 ksba_cert_t next;
1361 int rc = 0;
1362 int i, depth;
1363 char country[3];
1364 ksba_cert_t array[4];
1365 char buf[2];
1366 size_t buflen;
1367 int dummy_chainlen;
1369 if (!chainlen)
1370 chainlen = &dummy_chainlen;
1372 *chainlen = 0;
1373 err = ksba_cert_get_user_data (cert, "regtp_ca_chainlen",
1374 &buf, sizeof (buf), &buflen);
1375 if (!err)
1377 /* Got info. */
1378 if (buflen < 2 || !*buf)
1379 return 0; /* Nothing found. */
1380 *chainlen = buf[1];
1381 return 1; /* This is a regtp CA. */
1383 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1385 log_error ("ksba_cert_get_user_data(%s) failed: %s\n",
1386 "regtp_ca_chainlen", gpg_strerror (err));
1387 return 0; /* Nothing found. */
1390 /* Need to gather the info. This requires to walk up the chain
1391 until we have found the root. Because we are only interested in
1392 German Bundesnetzagentur (former RegTP) derived certificates 3
1393 levels are enough. (The German signature law demands a 3 tier
1394 hierachy; thus there is only one CA between the EE and the Root
1395 CA.) */
1396 memset (&array, 0, sizeof array);
1398 depth = 0;
1399 ksba_cert_ref (cert);
1400 array[depth++] = cert;
1401 ksba_cert_ref (cert);
1402 while (depth < DIM(array) && !(rc=gpgsm_walk_cert_chain (cert, &next)))
1404 ksba_cert_release (cert);
1405 ksba_cert_ref (next);
1406 array[depth++] = next;
1407 cert = next;
1409 ksba_cert_release (cert);
1410 if (rc != -1 || !depth || depth == DIM(array) )
1412 /* We did not reached the root. */
1413 goto leave;
1416 /* If this is a German signature law issued certificate, we store
1417 additional additional information. */
1418 if (!gpgsm_is_in_qualified_list (NULL, array[depth-1], country)
1419 && !strcmp (country, "de"))
1421 /* Setting the pathlen for the root CA and the CA flag for the
1422 next one is all what we need to do. */
1423 err = ksba_cert_set_user_data (array[depth-1], "regtp_ca_chainlen",
1424 "\x01\x01", 2);
1425 if (!err && depth > 1)
1426 err = ksba_cert_set_user_data (array[depth-2], "regtp_ca_chainlen",
1427 "\x01\x00", 2);
1428 if (err)
1429 log_error ("ksba_set_user_data(%s) failed: %s\n",
1430 "regtp_ca_chainlen", gpg_strerror (err));
1431 for (i=0; i < depth; i++)
1432 ksba_cert_release (array[i]);
1433 *chainlen = (depth>1? 0:1);
1434 return 1;
1437 leave:
1438 /* Nothing special with this certificate. Mark the target
1439 certificate anyway to avoid duplicate lookups. */
1440 err = ksba_cert_set_user_data (cert, "regtp_ca_chainlen", "", 1);
1441 if (err)
1442 log_error ("ksba_set_user_data(%s) failed: %s\n",
1443 "regtp_ca_chainlen", gpg_strerror (err));
1444 for (i=0; i < depth; i++)
1445 ksba_cert_release (array[i]);
1446 return 0;