1 /* validate.c - Validate a certificate chain.
2 * Copyright (C) 2001, 2003, 2004, 2008 Free Software Foundation, Inc.
3 * Copyright (C) 2004, 2006, 2008, 2017 g10 Code GmbH
5 * This file is part of DirMngr.
7 * DirMngr is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * DirMngr is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
31 #include "certcache.h"
37 /* Mode parameters for cert_check_usage(). */
40 CERT_USAGE_MODE_SIGN, /* Usable for encryption. */
41 CERT_USAGE_MODE_ENCR, /* Usable for signing. */
42 CERT_USAGE_MODE_VRFY, /* Usable for verification. */
43 CERT_USAGE_MODE_DECR, /* Usable for decryption. */
44 CERT_USAGE_MODE_CERT, /* Usable for cert signing. */
45 CERT_USAGE_MODE_OCSP, /* Usable for OCSP respone signing. */
46 CERT_USAGE_MODE_CRL /* Usable for CRL signing. */
50 /* While running the validation function we need to keep track of the
51 certificates and the validation outcome of each. We use this type
55 struct chain_item_s *next;
56 ksba_cert_t cert; /* The certificate. */
57 unsigned char fpr[20]; /* Fingerprint of the certificate. */
58 int is_self_signed; /* This certificate is self-signed. */
59 int is_valid; /* The certifiate is valid except for revocations. */
61 typedef struct chain_item_s *chain_item_t;
64 /* A couple of constants with Object Identifiers. */
65 static const char oid_kp_serverAuth[] = "1.3.6.1.5.5.7.3.1";
66 static const char oid_kp_clientAuth[] = "1.3.6.1.5.5.7.3.2";
67 static const char oid_kp_codeSigning[] = "1.3.6.1.5.5.7.3.3";
68 static const char oid_kp_emailProtection[]= "1.3.6.1.5.5.7.3.4";
69 static const char oid_kp_timeStamping[] = "1.3.6.1.5.5.7.3.8";
70 static const char oid_kp_ocspSigning[] = "1.3.6.1.5.5.7.3.9";
74 static gpg_error_t check_cert_sig (ksba_cert_t issuer_cert, ksba_cert_t cert);
77 /* Make sure that the values defined in the headers are correct. We
78 * can't use the preprocessor due to the use of enums. */
80 check_header_constants (void)
82 log_assert (CERTTRUST_CLASS_SYSTEM == VALIDATE_FLAG_TRUST_SYSTEM);
83 log_assert (CERTTRUST_CLASS_CONFIG == VALIDATE_FLAG_TRUST_CONFIG);
84 log_assert (CERTTRUST_CLASS_HKP == VALIDATE_FLAG_TRUST_HKP);
85 log_assert (CERTTRUST_CLASS_HKPSPOOL == VALIDATE_FLAG_TRUST_HKPSPOOL);
88 #define X (VALIDATE_FLAG_TRUST_SYSTEM | VALIDATE_FLAG_TRUST_CONFIG \
89 | VALIDATE_FLAG_TRUST_HKP | VALIDATE_FLAG_TRUST_HKPSPOOL)
91 #if ( X & VALIDATE_FLAG_MASK_TRUST ) != X
92 # error VALIDATE_FLAG_MASK_TRUST is bad
94 #if ( ~X & VALIDATE_FLAG_MASK_TRUST )
95 # error VALIDATE_FLAG_MASK_TRUST is bad
102 /* Check whether CERT contains critical extensions we don't know
105 unknown_criticals (ksba_cert_t cert)
107 static const char *known[] = {
108 "2.5.29.15", /* keyUsage */
109 "2.5.29.19", /* basic Constraints */
110 "2.5.29.32", /* certificatePolicies */
111 "2.5.29.37", /* extendedKeyUsage */
121 for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
122 &oid, &crit, NULL, NULL));idx++)
126 for (i=0; known[i] && strcmp (known[i],oid); i++)
128 unsupported = !known[i];
130 /* If this critical extension is not supported, check the list
131 of to be ignored extensions to see whether we claim that it
133 if (unsupported && opt.ignored_cert_extensions)
135 for (sl=opt.ignored_cert_extensions;
136 sl && strcmp (sl->d, oid); sl = sl->next)
144 log_error (_("critical certificate extension %s is not supported"),
146 rc = gpg_error (GPG_ERR_UNSUPPORTED_CERT);
149 if (err && gpg_err_code (err) != GPG_ERR_EOF)
150 rc = err; /* Such an error takes precedence. */
156 /* Basic check for supported policies. */
158 check_cert_policy (ksba_cert_t cert)
160 static const char *allowed[] = {
170 err = ksba_cert_get_cert_policies (cert, &policies);
171 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
172 return 0; /* No policy given. */
176 /* STRING is a line delimited list of certifiate policies as stored
177 in the certificate. The line itself is colon delimited where the
178 first field is the OID of the policy and the second field either
179 N or C for normal or critical extension */
181 log_info ("certificate's policy list: %s\n", policies);
183 /* The check is very minimal but won't give false positives */
184 any_critical = !!strstr (policies, ":C");
186 /* See whether we find ALLOWED (which is an OID) in POLICIES */
187 for (idx=0; allowed[idx]; idx++)
189 for (haystack=policies; (p=strstr (haystack, allowed[idx]));
192 if ( !(p == policies || p[-1] == '\n') )
193 continue; /* Does not match the begin of a line. */
194 if (p[strlen (allowed[idx])] != ':')
195 continue; /* The length does not match. */
196 /* Yep - it does match: Return okay. */
197 ksba_free (policies);
204 log_info (_("Note: non-critical certificate policy not allowed"));
209 log_info (_("certificate policy not allowed"));
210 err = gpg_error (GPG_ERR_NO_POLICY_MATCH);
213 ksba_free (policies);
219 allowed_ca (ksba_cert_t cert, int *chainlen)
224 err = ksba_cert_is_ca (cert, &flag, chainlen);
229 if (!is_trusted_cert (cert, CERTTRUST_CLASS_CONFIG))
231 /* The German SigG Root CA's certificate does not flag
232 itself as a CA; thus we relax this requirement if we
233 trust a root CA. I think this is reasonable. Note, that
234 gpgsm implements a far stricter scheme here but also
235 features a "relax" flag in the trustlist.txt. */
237 *chainlen = 3; /* That is what the SigG implements. */
239 log_info (_("accepting root CA not marked as a CA"));
243 log_error (_("issuer certificate is not marked as a CA"));
244 return gpg_error (GPG_ERR_BAD_CA_CERT);
250 /* Helper for validate_cert_chain. */
252 check_revocations (ctrl_t ctrl, chain_item_t chain)
257 int any_crl_too_old = 0;
258 int any_not_trusted = 0;
261 log_assert (ctrl->check_revocations_nest_level >= 0);
264 if (ctrl->check_revocations_nest_level > 10)
266 log_error (_("CRL checking too deeply nested\n"));
267 return gpg_error(GPG_ERR_BAD_CERT_CHAIN);
269 ctrl->check_revocations_nest_level++;
271 log_info ("[%d] start checking CRLs\n", ctrl->check_revocations_nest_level);
273 for (ci=chain; ci; ci = ci->next)
278 /* It does not make sense to check the root certificate for
279 revocations. In almost all cases this will lead to a
280 catch-22 as the root certificate is the final trust
281 anchor for the certificates and the CRLs. We expect the
282 user to remove root certificates from the list of trusted
283 certificates in case they have been revoked. */
285 cert_log_name (_("not checking CRL for"), ci->cert);
290 cert_log_name (_("checking CRL for"), ci->cert);
291 err = crl_cache_cert_isvalid (ctrl, ci->cert, 0);
292 if (gpg_err_code (err) == GPG_ERR_NO_CRL_KNOWN)
294 err = crl_cache_reload_crl (ctrl, ci->cert);
296 err = crl_cache_cert_isvalid (ctrl, ci->cert, 0);
299 log_info ("[%d] result of checking this CRL: %s\n",
300 ctrl->check_revocations_nest_level, gpg_strerror (err));
301 switch (gpg_err_code (err))
303 case 0: err = 0; break;
304 case GPG_ERR_CERT_REVOKED: any_revoked = 1; err = 0; break;
305 case GPG_ERR_NO_CRL_KNOWN: any_no_crl = 1; err = 0; break;
306 case GPG_ERR_NOT_TRUSTED: any_not_trusted = 1; err = 0; break;
307 case GPG_ERR_CRL_TOO_OLD: any_crl_too_old = 1; err = 0; break;
314 else if (any_revoked)
315 err = gpg_error (GPG_ERR_CERT_REVOKED);
317 err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
318 else if (any_not_trusted)
319 err = gpg_error (GPG_ERR_NOT_TRUSTED);
320 else if (any_crl_too_old)
321 err = gpg_error (GPG_ERR_CRL_TOO_OLD);
325 log_info ("[%d] result of checking all CRLs: %s\n",
326 ctrl->check_revocations_nest_level, gpg_strerror (err));
327 ctrl->check_revocations_nest_level--;
332 /* Check whether CERT is a root certificate. ISSUERDN and SUBJECTDN
333 are the DNs already extracted by the caller from CERT. Returns
334 True if this is the case. */
336 is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn)
340 ksba_sexp_t serialno;
341 ksba_sexp_t ak_keyid;
344 const char *ak_name_str;
345 ksba_sexp_t subj_keyid = NULL;
347 if (!issuerdn || !subjectdn)
350 if (strcmp (issuerdn, subjectdn))
353 err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn);
356 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
357 return 1; /* Yes. Without a authorityKeyIdentifier this needs
358 to be the Root certificate (our trust anchor). */
359 log_error ("error getting authorityKeyIdentifier: %s\n",
361 return 0; /* Well, it is broken anyway. Return No. */
364 serialno = ksba_cert_get_serial (cert);
367 log_error ("error getting serialno: %s\n", gpg_strerror (err));
371 /* Check whether the auth name's matches the issuer name+sn. If
372 that is the case this is a root certificate. */
373 ak_name_str = ksba_name_enum (ak_name, 0);
375 && !strcmp (ak_name_str, issuerdn)
376 && !cmp_simple_canon_sexp (ak_sn, serialno))
378 result = 1; /* Right, CERT is self-signed. */
382 /* Similar for the ak_keyid. */
383 if (ak_keyid && !ksba_cert_get_subj_key_id (cert, NULL, &subj_keyid)
384 && !cmp_simple_canon_sexp (ak_keyid, subj_keyid))
386 result = 1; /* Right, CERT is self-signed. */
392 ksba_free (subj_keyid);
393 ksba_free (ak_keyid);
394 ksba_name_release (ak_name);
396 ksba_free (serialno);
401 /* Validate the certificate CHAIN up to the trust anchor. Optionally
402 return the closest expiration time in R_EXPTIME (this is useful for
403 caching issues). MODE is one of the VALIDATE_MODE_* constants.
405 Note that VALIDATE_MODE_OCSP is not used due to the removal of the
406 system service in 2.1.15. Instead only the callback to gpgsm to
407 validate a certificate is used.
409 If R_TRUST_ANCHOR is not NULL and the validation would fail only
410 because the root certificate is not trusted, the hexified
411 fingerprint of that root certificate is stored at R_TRUST_ANCHOR
412 and success is returned. The caller needs to free the value at
413 R_TRUST_ANCHOR; in all other cases NULL is stored there. */
415 validate_cert_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t r_exptime,
416 unsigned int flags, char **r_trust_anchor)
421 char *subject = NULL;
422 ksba_cert_t subject_cert = NULL;
423 ksba_cert_t issuer_cert = NULL;
424 ksba_isotime_t current_time;
425 ksba_isotime_t exptime;
427 int any_no_policy_match = 0;
430 check_header_constants ();
437 *r_trust_anchor = NULL;
440 dump_cert ("subject", cert);
442 /* May the target certificate be used for this purpose? */
443 if ((flags & VALIDATE_FLAG_OCSP) && (err = check_cert_use_ocsp (cert)))
445 if ((flags & VALIDATE_FLAG_CRL) && (err = check_cert_use_crl (cert)))
448 /* If we already validated the certificate not too long ago, we can
449 avoid the excessive computations and lookups unless the caller
450 asked for the expiration time. */
456 err = ksba_cert_get_user_data (cert, "validated_at",
457 &validated_at, sizeof (validated_at),
459 if (err || buflen != sizeof (validated_at) || !validated_at)
460 err = 0; /* Not available or other error. */
463 /* If the validation is not older than 30 minutes we are ready. */
464 if (validated_at < gnupg_get_time () + (30*60))
467 log_info ("certificate is good (cached)\n");
468 /* Note, that we can't jump to leave here as this would
469 falsely updated the validation timestamp. */
475 /* Get the current time. */
476 gnupg_get_isotime (current_time);
478 /* We walk up the chain until we find a trust anchor. */
480 maxdepth = 10; /* Sensible limit on the length of the chain. */
485 /* Get the subject and issuer name from the current
489 issuer = ksba_cert_get_issuer (subject_cert, 0);
490 subject = ksba_cert_get_subject (subject_cert, 0);
494 log_error (_("no issuer found in certificate\n"));
495 err = gpg_error (GPG_ERR_BAD_CERT);
499 /* Handle the notBefore and notAfter timestamps. */
501 ksba_isotime_t not_before, not_after;
503 err = ksba_cert_get_validity (subject_cert, 0, not_before);
505 err = ksba_cert_get_validity (subject_cert, 1, not_after);
508 log_error (_("certificate with invalid validity: %s"),
510 err = gpg_error (GPG_ERR_BAD_CERT);
514 /* Keep track of the nearest expiration time in EXPTIME. */
518 gnupg_copy_time (exptime, not_after);
519 else if (strcmp (not_after, exptime) < 0 )
520 gnupg_copy_time (exptime, not_after);
523 /* Check whether the certificate is already valid. */
524 if (*not_before && strcmp (current_time, not_before) < 0 )
526 log_error (_("certificate not yet valid"));
527 log_info ("(valid from ");
528 dump_isotime (not_before);
530 err = gpg_error (GPG_ERR_CERT_TOO_YOUNG);
534 /* Now check whether the certificate has expired. */
535 if (*not_after && strcmp (current_time, not_after) > 0 )
537 log_error (_("certificate has expired"));
538 log_info ("(expired at ");
539 dump_isotime (not_after);
545 /* Do we have any critical extensions in the certificate we
547 err = unknown_criticals (subject_cert);
549 goto leave; /* yes. */
551 /* Check that given policies are allowed. */
552 err = check_cert_policy (subject_cert);
553 if (gpg_err_code (err) == GPG_ERR_NO_POLICY_MATCH)
555 any_no_policy_match = 1;
561 /* Is this a self-signed certificate? */
562 if (is_root_cert (subject_cert, issuer, subject))
564 /* There is no need to check the signature of the trust anchor. */
565 /* if (check_cert_sig (subject_cert, subject_cert) ) */
567 /* log_error (_("selfsigned certificate has a BAD signature")); */
568 /* err = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN */
569 /* : GPG_ERR_BAD_CERT); */
573 /* Is this certificate allowed to act as a CA. */
574 err = allowed_ca (subject_cert, NULL);
576 goto leave; /* No. */
578 err = is_trusted_cert (subject_cert,
579 (flags & VALIDATE_FLAG_MASK_TRUST));
581 ; /* Yes we trust this cert. */
582 else if (gpg_err_code (err) == GPG_ERR_NOT_TRUSTED)
586 log_error (_("root certificate is not marked trusted"));
587 fpr = get_fingerprint_hexstring (subject_cert);
588 log_info (_("fingerprint=%s\n"), fpr? fpr : "?");
589 dump_cert ("issuer", subject_cert);
592 /* Caller wants to do another trustiness check. */
593 *r_trust_anchor = fpr;
601 log_error (_("checking trustworthiness of "
602 "root certificate failed: %s\n"),
608 /* Prepend the certificate to our list. */
612 ci = xtrycalloc (1, sizeof *ci);
615 err = gpg_error_from_errno (errno);
618 ksba_cert_ref (subject_cert);
619 ci->cert = subject_cert;
620 cert_compute_fpr (subject_cert, ci->fpr);
627 if (r_trust_anchor && *r_trust_anchor)
628 log_info ("root certificate is good but not trusted\n");
630 log_info ("root certificate is good and trusted\n");
633 break; /* Okay: a self-signed certificate is an end-point. */
636 /* To avoid loops, we use an arbitrary limit on the length of
639 if (depth > maxdepth)
641 log_error (_("certificate chain too long\n"));
642 err = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
646 /* Find the next cert up the tree. */
647 ksba_cert_release (issuer_cert); issuer_cert = NULL;
648 err = find_issuing_cert (ctrl, subject_cert, &issuer_cert);
651 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
653 log_error (_("issuer certificate not found"));
654 log_info ("issuer certificate: #/");
655 dump_string (issuer);
659 log_error (_("issuer certificate not found: %s\n"),
661 /* Use a better understandable error code. */
662 err = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
666 /* try_another_cert: */
669 log_debug ("got issuer's certificate:\n");
670 dump_cert ("issuer", issuer_cert);
673 /* Now check the signature of the certificate. FIXME: we should
674 * delay this until later so that faked certificates can't be
675 * turned into a DoS easily. */
676 err = check_cert_sig (issuer_cert, subject_cert);
679 log_error (_("certificate has a BAD signature"));
681 if (gpg_err_code (err) == GPG_ERR_BAD_SIGNATURE)
683 /* We now try to find other issuer certificates which
684 might have been used. This is required because some
685 CAs are reusing the issuer and subject DN for new
686 root certificates without using a authorityKeyIdentifier. */
687 rc = find_up (kh, subject_cert, issuer, 1);
690 ksba_cert_t tmp_cert;
692 rc = keydb_get_cert (kh, &tmp_cert);
693 if (rc || !compare_certs (issuer_cert, tmp_cert))
695 /* The find next did not work or returned an
696 identical certificate. We better stop here
697 to avoid infinite checks. */
698 rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
699 ksba_cert_release (tmp_cert);
703 do_list (0, lm, fp, _("found another possible matching "
704 "CA certificate - trying again"));
705 ksba_cert_release (issuer_cert);
706 issuer_cert = tmp_cert;
707 goto try_another_cert;
712 /* Return a more descriptive error code than the one
713 * returned from the signature checking. */
714 err = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
718 /* Check that the length of the chain is not longer than allowed
723 err = allowed_ca (issuer_cert, &chainlen);
726 if (chainlen >= 0 && (depth - 1) > chainlen)
728 log_error (_("certificate chain longer than allowed by CA (%d)"),
730 err = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
735 /* May that certificate be used for certification? */
736 err = check_cert_use_cert (issuer_cert);
738 goto leave; /* No. */
740 /* Prepend the certificate to our list. */
744 ci = xtrycalloc (1, sizeof *ci);
747 err = gpg_error_from_errno (errno);
750 ksba_cert_ref (subject_cert);
751 ci->cert = subject_cert;
752 cert_compute_fpr (subject_cert, ci->fpr);
758 log_info (_("certificate is good\n"));
760 /* Now to the next level up. */
761 subject_cert = issuer_cert;
765 /* Even if we have no error here we need to check whether we
766 * encountered an error somewhere during the checks. Set the error
767 * code to the most critical one. */
771 err = gpg_error (GPG_ERR_CERT_EXPIRED);
772 else if (any_no_policy_match)
773 err = gpg_error (GPG_ERR_NO_POLICY_MATCH);
776 if (!err && opt.verbose)
780 log_info (_("certificate chain is good\n"));
781 for (citem = chain; citem; citem = citem->next)
782 cert_log_name (" certificate", citem->cert);
785 /* Now check for revocations unless CRL checks are disabled or we
786 * are non-recursive CRL mode. */
788 && !(flags & VALIDATE_FLAG_NOCRLCHECK)
789 && !((flags & VALIDATE_FLAG_CRL)
790 && !(flags & VALIDATE_FLAG_RECURSIVE)))
791 { /* Now that everything is fine, walk the chain and check each
792 * certificate for revocations.
794 * 1. item in the chain - The root certificate.
795 * 2. item - the CA below the root
796 * last item - the target certificate.
798 * Now for each certificate in the chain check whether it has
799 * been included in a CRL and thus be revoked. We don't do OCSP
800 * here because this does not seem to make much sense. This
801 * might become a recursive process and we should better cache
802 * our validity results to avoid double work. Far worse a
803 * catch-22 may happen for an improper setup hierarchy and we
804 * need a way to break up such a deadlock. */
805 err = check_revocations (ctrl, chain);
808 if (!err && opt.verbose)
810 if (r_trust_anchor && *r_trust_anchor)
811 log_info ("target certificate may be valid\n");
813 log_info ("target certificate is valid\n");
815 else if (err && opt.verbose)
816 log_info ("target certificate is NOT valid\n");
820 if (!err && !(r_trust_anchor && *r_trust_anchor))
822 /* With no error we can update the validation cache. We do this
823 * for all certificates in the chain. Note that we can't use
824 * the cache if the caller requested to check the trustiness of
825 * the root certificate himself. Adding such a feature would
826 * require us to also store the fingerprint of root
829 time_t validated_at = gnupg_get_time ();
831 for (citem = chain; citem; citem = citem->next)
833 err = ksba_cert_set_user_data (citem->cert, "validated_at",
834 &validated_at, sizeof (validated_at));
837 log_error ("set_user_data(validated_at) failed: %s\n",
845 gnupg_copy_time (r_exptime, exptime);
848 ksba_cert_release (issuer_cert);
849 if (subject_cert != cert)
850 ksba_cert_release (subject_cert);
853 chain_item_t ci_next = chain->next;
855 ksba_cert_release (chain->cert);
859 if (err && r_trust_anchor && *r_trust_anchor)
861 xfree (*r_trust_anchor);
862 *r_trust_anchor = NULL;
869 /* Return the public key algorithm id from the S-expression PKEY.
870 FIXME: libgcrypt should provide such a function. Note that this
871 implementation uses the names as used by libksba. */
873 pk_algo_from_sexp (gcry_sexp_t pkey)
880 l1 = gcry_sexp_find_token (pkey, "public-key", 0);
882 return 0; /* Not found. */
883 l2 = gcry_sexp_cadr (l1);
884 gcry_sexp_release (l1);
886 name = gcry_sexp_nth_data (l2, 0, &n);
888 algo = 0; /* Not found. */
889 else if (n==3 && !memcmp (name, "rsa", 3))
891 else if (n==3 && !memcmp (name, "dsa", 3))
893 else if (n==3 && !memcmp (name, "ecc", 3))
895 else if (n==13 && !memcmp (name, "ambiguous-rsa", 13))
899 gcry_sexp_release (l2);
904 /* Return the hash algorithm's algo id from its name given in the
905 * non-null termnated string in (buffer,buflen). Returns 0 on failure
906 * or if the algo is not known. */
908 hash_algo_from_buffer (const void *buffer, size_t buflen)
913 string = xtrymalloc (buflen + 1);
916 log_error (_("out of core\n"));
919 memcpy (string, buffer, buflen);
921 algo = gcry_md_map_name (string);
923 log_error ("unknown digest algorithm '%s' used in certificate\n", string);
929 /* Return an unsigned integer from the non-null termnated string
930 * (buffer,buflen). Returns 0 on failure. */
932 uint_from_buffer (const void *buffer, size_t buflen)
937 string = xtrymalloc (buflen + 1);
940 log_error (_("out of core\n"));
943 memcpy (string, buffer, buflen);
945 val = strtoul (string, NULL, 10);
951 /* Check the signature on CERT using the ISSUER_CERT. This function
952 * does only test the cryptographic signature and nothing else. It is
953 * assumed that the ISSUER_CERT is valid. */
955 check_cert_sig (ksba_cert_t issuer_cert, ksba_cert_t cert)
963 gcry_sexp_t s_sig, s_pkey;
964 gcry_sexp_t s_hash = NULL;
965 const char *algo_name; /* hash algorithm name converted to lower case. */
967 unsigned char *digest;
969 unsigned int saltlen = 0; /* (use is actually controlled by use_pss) */
971 /* Hash the target certificate using the algorithm from that certificate. */
972 algoid = ksba_cert_get_digest_algo (cert);
973 algo = gcry_md_map_name (algoid);
974 if (!algo && algoid && !strcmp (algoid, "1.2.840.113549.1.1.10"))
978 log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?");
979 return gpg_error (GPG_ERR_GENERAL);
982 /* Get the signature value out of the target certificate. */
983 p = ksba_cert_get_sig_val (cert);
984 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
987 log_error ("libksba did not return a proper S-Exp\n");
989 return gpg_error (GPG_ERR_BUG);
991 err = gcry_sexp_sscan ( &s_sig, NULL, p, n);
995 log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (err));
999 gcry_log_debugsxp ("sigval", s_sig);
1003 /* Extract the hash algorithm and the salt length from the sigval. */
1004 gcry_buffer_t ioarray[2] = { {0}, {0} };
1006 err = gcry_sexp_extract_param (s_sig, "sig-val",
1007 "&'hash-algo''salt-length'",
1008 ioarray+0, ioarray+1, NULL);
1011 gcry_sexp_release (s_sig);
1012 log_error ("extracting params from PSS failed: %s\n",
1013 gpg_strerror (err));
1016 algo = hash_algo_from_buffer (ioarray[0].data, ioarray[0].len);
1017 saltlen = uint_from_buffer (ioarray[1].data, ioarray[1].len);
1018 xfree (ioarray[0].data);
1019 xfree (ioarray[1].data);
1022 log_error ("length of PSS salt too short\n");
1023 gcry_sexp_release (s_sig);
1024 return gpg_error (GPG_ERR_DIGEST_ALGO);
1028 gcry_sexp_release (s_sig);
1029 return gpg_error (GPG_ERR_DIGEST_ALGO);
1031 /* Add some restrictions; see ../sm/certcheck.c for details. */
1035 case GCRY_MD_SHA256:
1036 case GCRY_MD_SHA384:
1037 case GCRY_MD_SHA512:
1038 case GCRY_MD_SHA3_256:
1039 case GCRY_MD_SHA3_384:
1040 case GCRY_MD_SHA3_512:
1043 log_error ("PSS hash algorithm '%s' rejected\n",
1044 gcry_md_algo_name (algo));
1045 gcry_sexp_release (s_sig);
1046 return gpg_error (GPG_ERR_DIGEST_ALGO);
1049 if (gcry_md_get_algo_dlen (algo) != saltlen)
1051 log_error ("PSS hash algorithm '%s' rejected due to salt length %u\n",
1052 gcry_md_algo_name (algo), saltlen);
1053 gcry_sexp_release (s_sig);
1054 return gpg_error (GPG_ERR_DIGEST_ALGO);
1058 algo_name = hash_algo_to_string (algo);
1059 err = gcry_md_open (&md, algo, 0);
1062 log_error ("md_open failed: %s\n", gpg_strerror (err));
1063 gcry_sexp_release (s_sig);
1067 gcry_md_debug (md, "hash.cert");
1069 err = ksba_cert_hash (cert, 1, HASH_FNC, md);
1072 log_error ("ksba_cert_hash failed: %s\n", gpg_strerror (err));
1074 gcry_sexp_release (s_sig);
1079 /* Get the public key from the issuer certificate. */
1080 p = ksba_cert_get_public_key (issuer_cert);
1081 n = gcry_sexp_canon_len (p, 0, NULL, NULL);
1084 log_error ("libksba did not return a proper S-Exp\n");
1087 gcry_sexp_release (s_sig);
1088 return gpg_error (GPG_ERR_BUG);
1090 err = gcry_sexp_sscan ( &s_pkey, NULL, p, n);
1094 log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (err));
1096 gcry_sexp_release (s_sig);
1101 /* Prepare the values for signature verification. At this point we
1102 * have these values:
1104 * S_PKEY - S-expression with the issuer's public key.
1105 * S_SIG - Signature value as given in the certificate.
1106 * MD - Finalized hash context with hash of the certificate.
1107 * ALGO_NAME - Lowercase hash algorithm name
1108 * SALTLEN - Salt length for rsaPSS.
1110 digestlen = gcry_md_get_algo_dlen (algo);
1111 digest = gcry_md_read (md, algo);
1114 err = gcry_sexp_build (&s_hash, NULL,
1117 "(salt-length %u))",
1123 else if (pk_algo_from_sexp (s_pkey) == GCRY_PK_ECC)
1125 unsigned int qbits0, qbits;
1127 qbits0 = gcry_pk_get_nbits (s_pkey);
1128 qbits = qbits0 == 521? 512 : qbits0;
1132 log_error ("ECDSA requires the hash length to be a"
1133 " multiple of 8 bits\n");
1134 err = gpg_error (GPG_ERR_INTERNAL);
1138 /* Don't allow any Q smaller than 160 bits. */
1141 log_error (_("%s key uses an unsafe (%u bit) hash\n"),
1143 err = gpg_error (GPG_ERR_INTERNAL);
1147 /* Check if we're too short. */
1148 if (digestlen < qbits/8)
1150 log_error (_("a %u bit hash is not valid for a %u bit %s key\n"),
1151 (unsigned int)digestlen*8,
1156 err = gpg_error (GPG_ERR_INTERNAL);
1162 if (digestlen > qbits/8)
1163 digestlen = qbits/8;
1165 err = gcry_sexp_build (&s_hash, NULL, "(data(flags raw)(value %b))",
1166 (int)digestlen, digest);
1168 else /* Not DSA - we assume RSA */
1170 err = gcry_sexp_build (&s_hash, NULL, "(data(flags pkcs1)(hash %s %b))",
1171 algo_name, (int)digestlen, digest);
1175 err = gcry_pk_verify (s_sig, s_hash, s_pkey);
1177 log_debug ("%s: gcry_pk_verify: %s\n", __func__, gpg_strerror (err));
1181 gcry_sexp_release (s_sig);
1182 gcry_sexp_release (s_hash);
1183 gcry_sexp_release (s_pkey);
1189 /* Return 0 if CERT is usable for MODE. */
1191 check_cert_usage (ksba_cert_t cert, enum cert_usage_modes mode)
1196 int have_ocsp_signing = 0;
1198 err = ksba_cert_get_ext_key_usages (cert, &extkeyusages);
1199 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1200 err = 0; /* No policy given. */
1203 unsigned int extusemask = ~0; /* Allow all. */
1208 int any_critical = 0;
1213 while (p && (pend=strchr (p, ':')))
1216 /* Only care about critical flagged usages. */
1220 if ( !strcmp (p, oid_kp_serverAuth))
1221 extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1222 | KSBA_KEYUSAGE_KEY_ENCIPHERMENT
1223 | KSBA_KEYUSAGE_KEY_AGREEMENT);
1224 else if ( !strcmp (p, oid_kp_clientAuth))
1225 extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1226 | KSBA_KEYUSAGE_KEY_AGREEMENT);
1227 else if ( !strcmp (p, oid_kp_codeSigning))
1228 extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE);
1229 else if ( !strcmp (p, oid_kp_emailProtection))
1230 extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1231 | KSBA_KEYUSAGE_NON_REPUDIATION
1232 | KSBA_KEYUSAGE_KEY_ENCIPHERMENT
1233 | KSBA_KEYUSAGE_KEY_AGREEMENT);
1234 else if ( !strcmp (p, oid_kp_timeStamping))
1235 extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1236 | KSBA_KEYUSAGE_NON_REPUDIATION);
1239 /* This is a hack to cope with OCSP. Note that we do
1240 not yet fully comply with the requirements and that
1241 the entire CRL/OCSP checking thing should undergo a
1242 thorough review and probably redesign. */
1243 if ( !strcmp (p, oid_kp_ocspSigning))
1244 have_ocsp_signing = 1;
1246 if ((p = strchr (pend, '\n')))
1249 ksba_free (extkeyusages);
1250 extkeyusages = NULL;
1253 extusemask = ~0; /* Reset to the don't care mask. */
1257 err = ksba_cert_get_key_usage (cert, &use);
1258 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1261 if (opt.verbose && (mode == CERT_USAGE_MODE_SIGN
1262 || mode == CERT_USAGE_MODE_ENCR))
1263 log_info (_("no key usage specified - assuming all usages\n"));
1267 /* Apply extKeyUsage. */
1273 log_error (_("error getting key usage information: %s\n"),
1274 gpg_strerror (err));
1275 ksba_free (extkeyusages);
1281 case CERT_USAGE_MODE_SIGN:
1282 case CERT_USAGE_MODE_VRFY:
1283 if ((use & (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1284 | KSBA_KEYUSAGE_NON_REPUDIATION)))
1286 log_info (mode == CERT_USAGE_MODE_VRFY
1287 ? _("certificate should not have been used for signing\n")
1288 : _("certificate is not usable for signing\n"));
1291 case CERT_USAGE_MODE_ENCR:
1292 case CERT_USAGE_MODE_DECR:
1293 if ((use & (KSBA_KEYUSAGE_KEY_ENCIPHERMENT
1294 | KSBA_KEYUSAGE_DATA_ENCIPHERMENT)))
1296 log_info (mode == CERT_USAGE_MODE_DECR
1297 ? _("certificate should not have been used for encryption\n")
1298 : _("certificate is not usable for encryption\n"));
1301 case CERT_USAGE_MODE_CERT:
1302 if ((use & (KSBA_KEYUSAGE_KEY_CERT_SIGN)))
1304 log_info (_("certificate should not have "
1305 "been used for certification\n"));
1308 case CERT_USAGE_MODE_OCSP:
1310 && (have_ocsp_signing
1311 || (use & (KSBA_KEYUSAGE_KEY_CERT_SIGN
1312 |KSBA_KEYUSAGE_CRL_SIGN))))
1314 log_info (_("certificate should not have "
1315 "been used for OCSP response signing\n"));
1318 case CERT_USAGE_MODE_CRL:
1319 if ((use & (KSBA_KEYUSAGE_CRL_SIGN)))
1321 log_info (_("certificate should not have "
1322 "been used for CRL signing\n"));
1326 return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1330 /* Return 0 if the certificate CERT is usable for certification. */
1332 check_cert_use_cert (ksba_cert_t cert)
1334 return check_cert_usage (cert, CERT_USAGE_MODE_CERT);
1337 /* Return 0 if the certificate CERT is usable for signing OCSP
1340 check_cert_use_ocsp (ksba_cert_t cert)
1342 return check_cert_usage (cert, CERT_USAGE_MODE_OCSP);
1345 /* Return 0 if the certificate CERT is usable for signing CRLs. */
1347 check_cert_use_crl (ksba_cert_t cert)
1349 return check_cert_usage (cert, CERT_USAGE_MODE_CRL);