Bump to 2.4.3
[platform/upstream/gpg2.git] / dirmngr / validate.c
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
4  *
5  * This file is part of DirMngr.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 #include <config.h>
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <ctype.h>
29
30 #include "dirmngr.h"
31 #include "certcache.h"
32 #include "crlcache.h"
33 #include "validate.h"
34 #include "misc.h"
35
36
37 /* Mode parameters for cert_check_usage().  */
38 enum cert_usage_modes
39   {
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.           */
47   };
48
49
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
52    for it.  */
53 struct chain_item_s
54 {
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.  */
60 };
61 typedef struct chain_item_s *chain_item_t;
62
63
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";
71
72
73 /* Prototypes.  */
74 static gpg_error_t check_cert_sig (ksba_cert_t issuer_cert, ksba_cert_t cert);
75
76
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.  */
79 static void
80 check_header_constants (void)
81 {
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);
86
87 #undef  X
88 #define X (VALIDATE_FLAG_TRUST_SYSTEM | VALIDATE_FLAG_TRUST_CONFIG  \
89            | VALIDATE_FLAG_TRUST_HKP | VALIDATE_FLAG_TRUST_HKPSPOOL)
90
91 #if ( X & VALIDATE_FLAG_MASK_TRUST ) !=  X
92 # error VALIDATE_FLAG_MASK_TRUST is bad
93 #endif
94 #if ( ~X & VALIDATE_FLAG_MASK_TRUST )
95 # error VALIDATE_FLAG_MASK_TRUST is bad
96 #endif
97
98 #undef X
99 }
100
101
102 /* Check whether CERT contains critical extensions we don't know
103    about.  */
104 static gpg_error_t
105 unknown_criticals (ksba_cert_t cert)
106 {
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 */
112     NULL
113   };
114   int i, idx, crit;
115   const char *oid;
116   int unsupported;
117   strlist_t sl;
118   gpg_error_t err, rc;
119
120   rc = 0;
121   for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
122                                              &oid, &crit, NULL, NULL));idx++)
123     {
124       if (!crit)
125         continue;
126       for (i=0; known[i] && strcmp (known[i],oid); i++)
127         ;
128       unsupported = !known[i];
129
130       /* If this critical extension is not supported, check the list
131          of to be ignored extensions to see whether we claim that it
132          is supported.  */
133       if (unsupported && opt.ignored_cert_extensions)
134         {
135           for (sl=opt.ignored_cert_extensions;
136                sl && strcmp (sl->d, oid); sl = sl->next)
137             ;
138           if (sl)
139             unsupported = 0;
140         }
141
142       if (unsupported)
143         {
144           log_error (_("critical certificate extension %s is not supported"),
145                      oid);
146           rc = gpg_error (GPG_ERR_UNSUPPORTED_CERT);
147         }
148     }
149   if (err && gpg_err_code (err) != GPG_ERR_EOF)
150     rc = err; /* Such an error takes precedence.  */
151
152   return rc;
153 }
154
155
156 /* Basic check for supported policies.  */
157 static gpg_error_t
158 check_cert_policy (ksba_cert_t cert)
159 {
160   static const char *allowed[] = {
161     "2.289.9.9",
162     NULL
163   };
164   gpg_error_t err;
165   int idx;
166   char *p, *haystack;
167   char *policies;
168   int any_critical;
169
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. */
173   if (err)
174     return err;
175
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 */
180   if (opt.verbose > 1)
181     log_info ("certificate's policy list: %s\n", policies);
182
183   /* The check is very minimal but won't give false positives */
184   any_critical = !!strstr (policies, ":C");
185
186   /* See whether we find ALLOWED (which is an OID) in POLICIES */
187   for (idx=0; allowed[idx]; idx++)
188     {
189       for (haystack=policies; (p=strstr (haystack, allowed[idx]));
190            haystack = p+1)
191         {
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);
198           return 0;
199         }
200     }
201
202   if (!any_critical)
203     {
204       log_info (_("Note: non-critical certificate policy not allowed"));
205       err = 0;
206     }
207   else
208     {
209       log_info (_("certificate policy not allowed"));
210       err = gpg_error (GPG_ERR_NO_POLICY_MATCH);
211     }
212
213   ksba_free (policies);
214   return err;
215 }
216
217
218 static gpg_error_t
219 allowed_ca (ksba_cert_t cert, int *chainlen)
220 {
221   gpg_error_t err;
222   int flag;
223
224   err = ksba_cert_is_ca (cert, &flag, chainlen);
225   if (err)
226     return err;
227   if (!flag)
228     {
229       if (!is_trusted_cert (cert, CERTTRUST_CLASS_CONFIG))
230         {
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. */
236           if (chainlen)
237             *chainlen = 3; /* That is what the SigG implements. */
238           if (opt.verbose)
239             log_info (_("accepting root CA not marked as a CA"));
240         }
241       else
242         {
243           log_error (_("issuer certificate is not marked as a CA"));
244           return gpg_error (GPG_ERR_BAD_CA_CERT);
245         }
246     }
247   return 0;
248 }
249
250 /* Helper for validate_cert_chain.  */
251 static gpg_error_t
252 check_revocations (ctrl_t ctrl, chain_item_t chain)
253 {
254   gpg_error_t err = 0;
255   int any_revoked = 0;
256   int any_no_crl = 0;
257   int any_crl_too_old = 0;
258   int any_not_trusted = 0;
259   chain_item_t ci;
260
261   log_assert (ctrl->check_revocations_nest_level >= 0);
262   log_assert (chain);
263
264   if (ctrl->check_revocations_nest_level > 10)
265     {
266       log_error (_("CRL checking too deeply nested\n"));
267       return gpg_error(GPG_ERR_BAD_CERT_CHAIN);
268     }
269   ctrl->check_revocations_nest_level++;
270   if (opt.verbose)
271     log_info ("[%d] start checking CRLs\n", ctrl->check_revocations_nest_level);
272
273   for (ci=chain; ci; ci = ci->next)
274     {
275       assert (ci->cert);
276       if (ci == chain)
277         {
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. */
284           if (opt.verbose)
285             cert_log_name (_("not checking CRL for"), ci->cert);
286           continue;
287         }
288
289       if (opt.verbose)
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)
293         {
294           err = crl_cache_reload_crl (ctrl, ci->cert);
295           if (!err)
296             err = crl_cache_cert_isvalid (ctrl, ci->cert, 0);
297         }
298       if (opt.verbose)
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))
302         {
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;
308         default: break;
309         }
310     }
311
312   if (err)
313     ;
314   else if (any_revoked)
315     err = gpg_error (GPG_ERR_CERT_REVOKED);
316   else if (any_no_crl)
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);
322   else
323     err = 0;
324   if (opt.verbose)
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--;
328   return err;
329 }
330
331
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. */
335 static int
336 is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn)
337 {
338   gpg_error_t err;
339   int result = 0;
340   ksba_sexp_t serialno;
341   ksba_sexp_t ak_keyid;
342   ksba_name_t ak_name;
343   ksba_sexp_t ak_sn;
344   const char *ak_name_str;
345   ksba_sexp_t subj_keyid = NULL;
346
347   if (!issuerdn || !subjectdn)
348     return 0;  /* No.  */
349
350   if (strcmp (issuerdn, subjectdn))
351     return 0;  /* No.  */
352
353   err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn);
354   if (err)
355     {
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",
360                  gpg_strerror (err));
361       return 0; /* Well, it is broken anyway.  Return No. */
362     }
363
364   serialno = ksba_cert_get_serial (cert);
365   if (!serialno)
366     {
367       log_error ("error getting serialno: %s\n", gpg_strerror (err));
368       goto leave;
369     }
370
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);
374   if (ak_name_str
375       && !strcmp (ak_name_str, issuerdn)
376       && !cmp_simple_canon_sexp (ak_sn, serialno))
377     {
378       result = 1;  /* Right, CERT is self-signed.  */
379       goto leave;
380     }
381
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))
385     {
386       result = 1;  /* Right, CERT is self-signed.  */
387       goto leave;
388     }
389
390
391  leave:
392   ksba_free (subj_keyid);
393   ksba_free (ak_keyid);
394   ksba_name_release (ak_name);
395   ksba_free (ak_sn);
396   ksba_free (serialno);
397   return result;
398 }
399
400
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.
404
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.
408
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.  */
414 gpg_error_t
415 validate_cert_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t r_exptime,
416                      unsigned int flags, char **r_trust_anchor)
417 {
418   gpg_error_t err = 0;
419   int depth, maxdepth;
420   char *issuer = NULL;
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;
426   int any_expired = 0;
427   int any_no_policy_match = 0;
428   chain_item_t chain;
429
430   check_header_constants ();
431
432   if (r_exptime)
433     *r_exptime = 0;
434   *exptime = 0;
435
436   if (r_trust_anchor)
437     *r_trust_anchor = NULL;
438
439   if (DBG_X509)
440     dump_cert ("subject", cert);
441
442   /* May the target certificate be used for this purpose?  */
443   if ((flags & VALIDATE_FLAG_OCSP) && (err = check_cert_use_ocsp (cert)))
444     return err;
445   if ((flags & VALIDATE_FLAG_CRL) && (err = check_cert_use_crl (cert)))
446     return err;
447
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.  */
451   if (!r_exptime)
452     {
453       size_t buflen;
454       time_t validated_at;
455
456       err = ksba_cert_get_user_data (cert, "validated_at",
457                                      &validated_at, sizeof (validated_at),
458                                      &buflen);
459       if (err || buflen != sizeof (validated_at) || !validated_at)
460         err = 0; /* Not available or other error. */
461       else
462         {
463           /* If the validation is not older than 30 minutes we are ready. */
464           if (validated_at < gnupg_get_time () + (30*60))
465             {
466               if (opt.verbose)
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.  */
470               return 0;
471             }
472         }
473     }
474
475   /* Get the current time. */
476   gnupg_get_isotime (current_time);
477
478   /* We walk up the chain until we find a trust anchor. */
479   subject_cert = cert;
480   maxdepth = 10;  /* Sensible limit on the length of the chain.  */
481   chain = NULL;
482   depth = 0;
483   for (;;)
484     {
485       /* Get the subject and issuer name from the current
486          certificate.  */
487       ksba_free (issuer);
488       ksba_free (subject);
489       issuer = ksba_cert_get_issuer (subject_cert, 0);
490       subject = ksba_cert_get_subject (subject_cert, 0);
491
492       if (!issuer)
493         {
494           log_error (_("no issuer found in certificate\n"));
495           err = gpg_error (GPG_ERR_BAD_CERT);
496           goto leave;
497         }
498
499       /* Handle the notBefore and notAfter timestamps.  */
500       {
501         ksba_isotime_t not_before, not_after;
502
503         err = ksba_cert_get_validity (subject_cert, 0, not_before);
504         if (!err)
505           err = ksba_cert_get_validity (subject_cert, 1, not_after);
506         if (err)
507           {
508             log_error (_("certificate with invalid validity: %s"),
509                        gpg_strerror (err));
510             err = gpg_error (GPG_ERR_BAD_CERT);
511             goto leave;
512           }
513
514         /* Keep track of the nearest expiration time in EXPTIME.  */
515         if (*not_after)
516           {
517             if (!*exptime)
518               gnupg_copy_time (exptime, not_after);
519             else if (strcmp (not_after, exptime) < 0 )
520               gnupg_copy_time (exptime, not_after);
521           }
522
523         /* Check whether the certificate is already valid.  */
524         if (*not_before && strcmp (current_time, not_before) < 0 )
525           {
526             log_error (_("certificate not yet valid"));
527             log_info ("(valid from ");
528             dump_isotime (not_before);
529             log_printf (")\n");
530             err = gpg_error (GPG_ERR_CERT_TOO_YOUNG);
531             goto leave;
532           }
533
534         /* Now check whether the certificate has expired.  */
535         if (*not_after && strcmp (current_time, not_after) > 0 )
536           {
537             log_error (_("certificate has expired"));
538             log_info ("(expired at ");
539             dump_isotime (not_after);
540             log_printf (")\n");
541             any_expired = 1;
542           }
543       }
544
545       /* Do we have any critical extensions in the certificate we
546          can't handle? */
547       err = unknown_criticals (subject_cert);
548       if (err)
549         goto leave; /* yes. */
550
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)
554         {
555           any_no_policy_match = 1;
556           err = 0;
557         }
558       else if (err)
559         goto leave;
560
561       /* Is this a self-signed certificate? */
562       if (is_root_cert (subject_cert, issuer, subject))
563         {
564           /* There is no need to check the signature of the trust anchor.  */
565           /* if (check_cert_sig (subject_cert, subject_cert) ) */
566           /*   { */
567           /*     log_error (_("selfsigned certificate has a BAD signature")); */
568           /*     err = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN */
569           /*                           : GPG_ERR_BAD_CERT); */
570           /*     goto leave; */
571           /*   } */
572
573           /* Is this certificate allowed to act as a CA.  */
574           err = allowed_ca (subject_cert, NULL);
575           if (err)
576             goto leave;  /* No. */
577
578           err = is_trusted_cert (subject_cert,
579                                  (flags & VALIDATE_FLAG_MASK_TRUST));
580           if (!err)
581             ; /* Yes we trust this cert.  */
582           else if (gpg_err_code (err) == GPG_ERR_NOT_TRUSTED)
583             {
584               char *fpr;
585
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);
590               if (r_trust_anchor)
591                 {
592                   /* Caller wants to do another trustiness check.  */
593                   *r_trust_anchor = fpr;
594                   err = 0;
595                 }
596               else
597                 xfree (fpr);
598             }
599           else
600             {
601               log_error (_("checking trustworthiness of "
602                            "root certificate failed: %s\n"),
603                          gpg_strerror (err));
604             }
605           if (err)
606             goto leave;
607
608           /* Prepend the certificate to our list.  */
609           {
610             chain_item_t ci;
611
612             ci = xtrycalloc (1, sizeof *ci);
613             if (!ci)
614               {
615                 err = gpg_error_from_errno (errno);
616                 goto leave;
617               }
618             ksba_cert_ref (subject_cert);
619             ci->cert = subject_cert;
620             cert_compute_fpr (subject_cert, ci->fpr);
621             ci->next = chain;
622             chain = ci;
623           }
624
625           if (opt.verbose)
626             {
627               if (r_trust_anchor && *r_trust_anchor)
628                 log_info ("root certificate is good but not trusted\n");
629               else
630                 log_info ("root certificate is good and trusted\n");
631             }
632
633           break;  /* Okay: a self-signed certificate is an end-point. */
634         }
635
636       /* To avoid loops, we use an arbitrary limit on the length of
637          the chain. */
638       depth++;
639       if (depth > maxdepth)
640         {
641           log_error (_("certificate chain too long\n"));
642           err = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
643           goto leave;
644         }
645
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);
649       if (err)
650         {
651           if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
652             {
653               log_error (_("issuer certificate not found"));
654               log_info ("issuer certificate: #/");
655               dump_string (issuer);
656               log_printf ("\n");
657             }
658           else
659             log_error (_("issuer certificate not found: %s\n"),
660                          gpg_strerror (err));
661           /* Use a better understandable error code.  */
662           err = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
663           goto leave;
664         }
665
666 /*     try_another_cert: */
667       if (DBG_X509)
668         {
669           log_debug ("got issuer's certificate:\n");
670           dump_cert ("issuer", issuer_cert);
671         }
672
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);
677       if (err)
678         {
679           log_error (_("certificate has a BAD signature"));
680 #if 0
681           if (gpg_err_code (err) == GPG_ERR_BAD_SIGNATURE)
682             {
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);
688               if (!rc)
689                 {
690                   ksba_cert_t tmp_cert;
691
692                   rc = keydb_get_cert (kh, &tmp_cert);
693                   if (rc || !compare_certs (issuer_cert, tmp_cert))
694                     {
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);
700                     }
701                   else
702                     {
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;
708                     }
709                 }
710             }
711 #endif
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);
715           goto leave;
716         }
717
718       /* Check that the length of the chain is not longer than allowed
719        * by the CA.  */
720       {
721         int chainlen;
722
723         err = allowed_ca (issuer_cert, &chainlen);
724         if (err)
725           goto leave;
726         if (chainlen >= 0 && (depth - 1) > chainlen)
727           {
728             log_error (_("certificate chain longer than allowed by CA (%d)"),
729                        chainlen);
730             err = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
731             goto leave;
732           }
733       }
734
735       /* May that certificate be used for certification? */
736       err = check_cert_use_cert (issuer_cert);
737       if (err)
738         goto leave;  /* No.  */
739
740       /* Prepend the certificate to our list.  */
741       {
742         chain_item_t ci;
743
744         ci = xtrycalloc (1, sizeof *ci);
745         if (!ci)
746           {
747             err = gpg_error_from_errno (errno);
748             goto leave;
749           }
750         ksba_cert_ref (subject_cert);
751         ci->cert = subject_cert;
752         cert_compute_fpr (subject_cert, ci->fpr);
753         ci->next = chain;
754         chain = ci;
755       }
756
757       if (opt.verbose)
758         log_info (_("certificate is good\n"));
759
760       /* Now to the next level up.  */
761       subject_cert = issuer_cert;
762       issuer_cert = NULL;
763     }
764
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.  */
768   if (!err)
769     {
770       if (any_expired)
771         err = gpg_error (GPG_ERR_CERT_EXPIRED);
772       else if (any_no_policy_match)
773         err = gpg_error (GPG_ERR_NO_POLICY_MATCH);
774     }
775
776   if (!err && opt.verbose)
777     {
778       chain_item_t citem;
779
780       log_info (_("certificate chain is good\n"));
781       for (citem = chain; citem; citem = citem->next)
782         cert_log_name ("  certificate", citem->cert);
783     }
784
785   /* Now check for revocations unless CRL checks are disabled or we
786    * are non-recursive CRL mode.  */
787   if (!err
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.
793        *
794        * 1. item in the chain  - The root certificate.
795        * 2. item               - the CA below the root
796        * last item             - the target certificate.
797        *
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);
806     }
807
808   if (!err && opt.verbose)
809     {
810       if (r_trust_anchor && *r_trust_anchor)
811         log_info ("target certificate may be valid\n");
812       else
813         log_info ("target certificate is valid\n");
814     }
815   else if (err && opt.verbose)
816     log_info ("target certificate is NOT valid\n");
817
818
819  leave:
820   if (!err && !(r_trust_anchor && *r_trust_anchor))
821     {
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
827        * certificate.  */
828       chain_item_t citem;
829       time_t validated_at = gnupg_get_time ();
830
831       for (citem = chain; citem; citem = citem->next)
832         {
833           err = ksba_cert_set_user_data (citem->cert, "validated_at",
834                                          &validated_at, sizeof (validated_at));
835           if (err)
836             {
837               log_error ("set_user_data(validated_at) failed: %s\n",
838                          gpg_strerror (err));
839               err = 0;
840             }
841         }
842     }
843
844   if (r_exptime)
845     gnupg_copy_time (r_exptime, exptime);
846   ksba_free (issuer);
847   ksba_free (subject);
848   ksba_cert_release (issuer_cert);
849   if (subject_cert != cert)
850     ksba_cert_release (subject_cert);
851   while (chain)
852     {
853       chain_item_t ci_next = chain->next;
854       if (chain->cert)
855         ksba_cert_release (chain->cert);
856       xfree (chain);
857       chain = ci_next;
858     }
859   if (err && r_trust_anchor && *r_trust_anchor)
860     {
861       xfree (*r_trust_anchor);
862       *r_trust_anchor = NULL;
863     }
864   return err;
865 }
866
867
868 \f
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.  */
872 int
873 pk_algo_from_sexp (gcry_sexp_t pkey)
874 {
875   gcry_sexp_t l1, l2;
876   const char *name;
877   size_t n;
878   int algo;
879
880   l1 = gcry_sexp_find_token (pkey, "public-key", 0);
881   if (!l1)
882     return 0; /* Not found.  */
883   l2 = gcry_sexp_cadr (l1);
884   gcry_sexp_release (l1);
885
886   name = gcry_sexp_nth_data (l2, 0, &n);
887   if (!name)
888     algo = 0; /* Not found. */
889   else if (n==3 && !memcmp (name, "rsa", 3))
890     algo = GCRY_PK_RSA;
891   else if (n==3 && !memcmp (name, "dsa", 3))
892     algo = GCRY_PK_DSA;
893   else if (n==3 && !memcmp (name, "ecc", 3))
894     algo = GCRY_PK_ECC;
895   else if (n==13 && !memcmp (name, "ambiguous-rsa", 13))
896     algo = GCRY_PK_RSA;
897   else
898     algo = 0;
899   gcry_sexp_release (l2);
900   return algo;
901 }
902
903
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.  */
907 static int
908 hash_algo_from_buffer (const void *buffer, size_t buflen)
909 {
910   char *string;
911   int algo;
912
913   string = xtrymalloc (buflen + 1);
914   if (!string)
915     {
916       log_error (_("out of core\n"));
917       return 0;
918     }
919   memcpy (string, buffer, buflen);
920   string[buflen] = 0;
921   algo = gcry_md_map_name (string);
922   if (!algo)
923     log_error ("unknown digest algorithm '%s' used in certificate\n", string);
924   xfree (string);
925   return algo;
926 }
927
928
929 /* Return an unsigned integer from the non-null termnated string
930  * (buffer,buflen).  Returns 0 on failure.  */
931 static unsigned int
932 uint_from_buffer (const void *buffer, size_t buflen)
933 {
934   char *string;
935   unsigned int val;
936
937   string = xtrymalloc (buflen + 1);
938   if (!string)
939     {
940       log_error (_("out of core\n"));
941       return 0;
942     }
943   memcpy (string, buffer, buflen);
944   string[buflen] = 0;
945   val = strtoul (string, NULL, 10);
946   xfree (string);
947   return val;
948 }
949
950
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.  */
954 static gpg_error_t
955 check_cert_sig (ksba_cert_t issuer_cert, ksba_cert_t cert)
956 {
957   gpg_error_t err;
958   const char *algoid;
959   gcry_md_hd_t md;
960   int algo;
961   ksba_sexp_t p;
962   size_t n;
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. */
966   int digestlen;
967   unsigned char *digest;
968   int use_pss = 0;
969   unsigned int saltlen = 0;  /* (use is actually controlled by use_pss) */
970
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"))
975     use_pss = 1;
976   else if (!algo)
977     {
978       log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?");
979       return gpg_error (GPG_ERR_GENERAL);
980     }
981
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);
985   if (!n)
986     {
987       log_error ("libksba did not return a proper S-Exp\n");
988       ksba_free (p);
989       return gpg_error (GPG_ERR_BUG);
990     }
991   err = gcry_sexp_sscan ( &s_sig, NULL, p, n);
992   ksba_free (p);
993   if (err)
994     {
995       log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (err));
996       return err;
997     }
998   if (DBG_CRYPTO)
999     gcry_log_debugsxp ("sigval", s_sig);
1000
1001   if (use_pss)
1002     {
1003       /* Extract the hash algorithm and the salt length from the sigval.  */
1004       gcry_buffer_t ioarray[2] = { {0}, {0} };
1005
1006       err = gcry_sexp_extract_param (s_sig, "sig-val",
1007                                     "&'hash-algo''salt-length'",
1008                                     ioarray+0, ioarray+1, NULL);
1009       if (err)
1010         {
1011           gcry_sexp_release (s_sig);
1012           log_error ("extracting params from PSS failed: %s\n",
1013                      gpg_strerror (err));
1014           return err;
1015         }
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);
1020       if (saltlen < 20)
1021         {
1022           log_error ("length of PSS salt too short\n");
1023           gcry_sexp_release (s_sig);
1024           return gpg_error (GPG_ERR_DIGEST_ALGO);
1025         }
1026       if (!algo)
1027         {
1028           gcry_sexp_release (s_sig);
1029           return gpg_error (GPG_ERR_DIGEST_ALGO);
1030         }
1031       /* Add some restrictions; see ../sm/certcheck.c for details.  */
1032       switch (algo)
1033         {
1034         case GCRY_MD_SHA1:
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:
1041           break;
1042         default:
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);
1047         }
1048
1049       if (gcry_md_get_algo_dlen (algo) != saltlen)
1050         {
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);
1055         }
1056     }
1057
1058   algo_name = hash_algo_to_string (algo);
1059   err = gcry_md_open (&md, algo, 0);
1060   if (err)
1061     {
1062       log_error ("md_open failed: %s\n", gpg_strerror (err));
1063       gcry_sexp_release (s_sig);
1064       return err;
1065     }
1066   if (DBG_HASHING)
1067     gcry_md_debug (md, "hash.cert");
1068
1069   err = ksba_cert_hash (cert, 1, HASH_FNC, md);
1070   if (err)
1071     {
1072       log_error ("ksba_cert_hash failed: %s\n", gpg_strerror (err));
1073       gcry_md_close (md);
1074       gcry_sexp_release (s_sig);
1075       return err;
1076     }
1077   gcry_md_final (md);
1078
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);
1082   if (!n)
1083     {
1084       log_error ("libksba did not return a proper S-Exp\n");
1085       gcry_md_close (md);
1086       ksba_free (p);
1087       gcry_sexp_release (s_sig);
1088       return gpg_error (GPG_ERR_BUG);
1089     }
1090   err = gcry_sexp_sscan ( &s_pkey, NULL, p, n);
1091   ksba_free (p);
1092   if (err)
1093     {
1094       log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (err));
1095       gcry_md_close (md);
1096       gcry_sexp_release (s_sig);
1097       return err;
1098     }
1099
1100
1101   /* Prepare the values for signature verification. At this point we
1102    * have these values:
1103    *
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.
1109    */
1110   digestlen = gcry_md_get_algo_dlen (algo);
1111   digest = gcry_md_read (md, algo);
1112   if (use_pss)
1113     {
1114       err = gcry_sexp_build (&s_hash, NULL,
1115                              "(data (flags pss)"
1116                              "(hash %s %b)"
1117                              "(salt-length %u))",
1118                              algo_name,
1119                              (int)digestlen,
1120                              digest,
1121                              saltlen);
1122     }
1123   else if (pk_algo_from_sexp (s_pkey) == GCRY_PK_ECC)
1124     {
1125       unsigned int qbits0, qbits;
1126
1127       qbits0 = gcry_pk_get_nbits (s_pkey);
1128       qbits = qbits0 == 521? 512 : qbits0;
1129
1130       if ((qbits%8))
1131         {
1132           log_error ("ECDSA requires the hash length to be a"
1133                      " multiple of 8 bits\n");
1134           err = gpg_error (GPG_ERR_INTERNAL);
1135           goto leave;
1136         }
1137
1138       /* Don't allow any Q smaller than 160 bits.  */
1139       if (qbits < 160)
1140         {
1141           log_error (_("%s key uses an unsafe (%u bit) hash\n"),
1142                      "ECDSA", qbits0);
1143           err = gpg_error (GPG_ERR_INTERNAL);
1144           goto leave;
1145         }
1146
1147       /* Check if we're too short.  */
1148       if (digestlen < qbits/8)
1149         {
1150           log_error (_("a %u bit hash is not valid for a %u bit %s key\n"),
1151                      (unsigned int)digestlen*8,
1152                      qbits0,
1153                      "ECDSA");
1154           if (digestlen < 20)
1155             {
1156               err = gpg_error (GPG_ERR_INTERNAL);
1157               goto leave;
1158             }
1159         }
1160
1161       /* Truncate.  */
1162       if (digestlen > qbits/8)
1163         digestlen = qbits/8;
1164
1165       err = gcry_sexp_build (&s_hash, NULL, "(data(flags raw)(value %b))",
1166                              (int)digestlen, digest);
1167     }
1168   else /* Not DSA - we assume RSA  */
1169     {
1170       err = gcry_sexp_build (&s_hash, NULL, "(data(flags pkcs1)(hash %s %b))",
1171                              algo_name, (int)digestlen, digest);
1172     }
1173
1174   if (!err)
1175     err = gcry_pk_verify (s_sig, s_hash, s_pkey);
1176   if (DBG_X509)
1177     log_debug ("%s: gcry_pk_verify: %s\n", __func__, gpg_strerror (err));
1178
1179  leave:
1180   gcry_md_close (md);
1181   gcry_sexp_release (s_sig);
1182   gcry_sexp_release (s_hash);
1183   gcry_sexp_release (s_pkey);
1184   return err;
1185 }
1186
1187
1188 \f
1189 /* Return 0 if CERT is usable for MODE.  */
1190 static gpg_error_t
1191 check_cert_usage (ksba_cert_t cert, enum cert_usage_modes mode)
1192 {
1193   gpg_error_t err;
1194   unsigned int use;
1195   char *extkeyusages;
1196   int have_ocsp_signing = 0;
1197
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. */
1201   if (!err)
1202     {
1203       unsigned int extusemask = ~0; /* Allow all. */
1204
1205       if (extkeyusages)
1206         {
1207           char *p, *pend;
1208           int any_critical = 0;
1209
1210           extusemask = 0;
1211
1212           p = extkeyusages;
1213           while (p && (pend=strchr (p, ':')))
1214             {
1215               *pend++ = 0;
1216               /* Only care about critical flagged usages. */
1217               if ( *pend == 'C' )
1218                 {
1219                   any_critical = 1;
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);
1237                 }
1238
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;
1245
1246               if ((p = strchr (pend, '\n')))
1247                 p++;
1248             }
1249           ksba_free (extkeyusages);
1250           extkeyusages = NULL;
1251
1252           if (!any_critical)
1253             extusemask = ~0; /* Reset to the don't care mask. */
1254         }
1255
1256
1257       err = ksba_cert_get_key_usage (cert, &use);
1258       if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1259         {
1260           err = 0;
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"));
1264           use = ~0;
1265         }
1266
1267       /* Apply extKeyUsage. */
1268       use &= extusemask;
1269
1270     }
1271   if (err)
1272     {
1273       log_error (_("error getting key usage information: %s\n"),
1274                  gpg_strerror (err));
1275       ksba_free (extkeyusages);
1276       return err;
1277     }
1278
1279   switch (mode)
1280     {
1281     case CERT_USAGE_MODE_SIGN:
1282     case CERT_USAGE_MODE_VRFY:
1283       if ((use & (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1284                   | KSBA_KEYUSAGE_NON_REPUDIATION)))
1285         return 0;
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"));
1289       break;
1290
1291     case CERT_USAGE_MODE_ENCR:
1292     case CERT_USAGE_MODE_DECR:
1293       if ((use & (KSBA_KEYUSAGE_KEY_ENCIPHERMENT
1294                   | KSBA_KEYUSAGE_DATA_ENCIPHERMENT)))
1295         return 0;
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"));
1299       break;
1300
1301     case CERT_USAGE_MODE_CERT:
1302       if ((use & (KSBA_KEYUSAGE_KEY_CERT_SIGN)))
1303         return 0;
1304       log_info (_("certificate should not have "
1305                   "been used for certification\n"));
1306       break;
1307
1308     case CERT_USAGE_MODE_OCSP:
1309       if (use != ~0
1310           && (have_ocsp_signing
1311               || (use & (KSBA_KEYUSAGE_KEY_CERT_SIGN
1312                          |KSBA_KEYUSAGE_CRL_SIGN))))
1313         return 0;
1314       log_info (_("certificate should not have "
1315                   "been used for OCSP response signing\n"));
1316       break;
1317
1318     case CERT_USAGE_MODE_CRL:
1319       if ((use & (KSBA_KEYUSAGE_CRL_SIGN)))
1320         return 0;
1321       log_info (_("certificate should not have "
1322                   "been used for CRL signing\n"));
1323       break;
1324     }
1325
1326   return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1327 }
1328
1329
1330 /* Return 0 if the certificate CERT is usable for certification.  */
1331 gpg_error_t
1332 check_cert_use_cert (ksba_cert_t cert)
1333 {
1334   return check_cert_usage (cert, CERT_USAGE_MODE_CERT);
1335 }
1336
1337 /* Return 0 if the certificate CERT is usable for signing OCSP
1338    responses.  */
1339 gpg_error_t
1340 check_cert_use_ocsp (ksba_cert_t cert)
1341 {
1342   return check_cert_usage (cert, CERT_USAGE_MODE_OCSP);
1343 }
1344
1345 /* Return 0 if the certificate CERT is usable for signing CRLs. */
1346 gpg_error_t
1347 check_cert_use_crl (ksba_cert_t cert)
1348 {
1349   return check_cert_usage (cert, CERT_USAGE_MODE_CRL);
1350 }