chiark / gitweb /
gnupg2 (2.1.17-3) unstable; urgency=medium
[gnupg2.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 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 /* While running the validation function we need to keep track of the
37    certificates and the validation outcome of each.  We use this type
38    for it.  */
39 struct chain_item_s
40 {
41   struct chain_item_s *next;
42   ksba_cert_t cert;      /* The certificate.  */
43   unsigned char fpr[20]; /* Fingerprint of the certificate.  */
44   int is_self_signed;    /* This certificate is self-signed.  */
45   int is_valid;          /* The certifiate is valid except for revocations.  */
46 };
47 typedef struct chain_item_s *chain_item_t;
48
49
50 /* A couple of constants with Object Identifiers.  */
51 static const char oid_kp_serverAuth[]     = "1.3.6.1.5.5.7.3.1";
52 static const char oid_kp_clientAuth[]     = "1.3.6.1.5.5.7.3.2";
53 static const char oid_kp_codeSigning[]    = "1.3.6.1.5.5.7.3.3";
54 static const char oid_kp_emailProtection[]= "1.3.6.1.5.5.7.3.4";
55 static const char oid_kp_timeStamping[]   = "1.3.6.1.5.5.7.3.8";
56 static const char oid_kp_ocspSigning[]    = "1.3.6.1.5.5.7.3.9";
57
58
59 /* Prototypes.  */
60 static gpg_error_t check_cert_sig (ksba_cert_t issuer_cert, ksba_cert_t cert);
61
62
63
64
65 /* Check whether CERT contains critical extensions we don't know
66    about.  */
67 static gpg_error_t
68 unknown_criticals (ksba_cert_t cert)
69 {
70   static const char *known[] = {
71     "2.5.29.15", /* keyUsage */
72     "2.5.29.19", /* basic Constraints */
73     "2.5.29.32", /* certificatePolicies */
74     "2.5.29.37", /* extendedKeyUsage */
75     NULL
76   };
77   int i, idx, crit;
78   const char *oid;
79   int unsupported;
80   strlist_t sl;
81   gpg_error_t err, rc;
82
83   rc = 0;
84   for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
85                                              &oid, &crit, NULL, NULL));idx++)
86     {
87       if (!crit)
88         continue;
89       for (i=0; known[i] && strcmp (known[i],oid); i++)
90         ;
91       unsupported = !known[i];
92
93       /* If this critical extension is not supported, check the list
94          of to be ignored extensions to see whether we claim that it
95          is supported.  */
96       if (unsupported && opt.ignored_cert_extensions)
97         {
98           for (sl=opt.ignored_cert_extensions;
99                sl && strcmp (sl->d, oid); sl = sl->next)
100             ;
101           if (sl)
102             unsupported = 0;
103         }
104
105       if (unsupported)
106         {
107           log_error (_("critical certificate extension %s is not supported"),
108                      oid);
109           rc = gpg_error (GPG_ERR_UNSUPPORTED_CERT);
110         }
111     }
112   if (err && gpg_err_code (err) != GPG_ERR_EOF)
113     rc = err; /* Such an error takes precendence.  */
114
115   return rc;
116 }
117
118
119 /* Basic check for supported policies.  */
120 static gpg_error_t
121 check_cert_policy (ksba_cert_t cert)
122 {
123   static const char *allowed[] = {
124     "2.289.9.9",
125     NULL
126   };
127   gpg_error_t err;
128   int idx;
129   char *p, *haystack;
130   char *policies;
131   int any_critical;
132
133   err = ksba_cert_get_cert_policies (cert, &policies);
134   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
135     return 0; /* No policy given. */
136   if (err)
137     return err;
138
139   /* STRING is a line delimited list of certifiate policies as stored
140      in the certificate.  The line itself is colon delimited where the
141      first field is the OID of the policy and the second field either
142      N or C for normal or critical extension */
143   if (opt.verbose > 1)
144     log_info ("certificate's policy list: %s\n", policies);
145
146   /* The check is very minimal but won't give false positives */
147   any_critical = !!strstr (policies, ":C");
148
149   /* See whether we find ALLOWED (which is an OID) in POLICIES */
150   for (idx=0; allowed[idx]; idx++)
151     {
152       for (haystack=policies; (p=strstr (haystack, allowed[idx]));
153            haystack = p+1)
154         {
155           if ( !(p == policies || p[-1] == '\n') )
156             continue; /* Does not match the begin of a line. */
157           if (p[strlen (allowed[idx])] != ':')
158             continue; /* The length does not match. */
159           /* Yep - it does match: Return okay. */
160           ksba_free (policies);
161           return 0;
162         }
163     }
164
165   if (!any_critical)
166     {
167       log_info (_("Note: non-critical certificate policy not allowed"));
168       err = 0;
169     }
170   else
171     {
172       log_info (_("certificate policy not allowed"));
173       err = gpg_error (GPG_ERR_NO_POLICY_MATCH);
174     }
175
176   ksba_free (policies);
177   return err;
178 }
179
180
181 static gpg_error_t
182 allowed_ca (ksba_cert_t cert, int *chainlen)
183 {
184   gpg_error_t err;
185   int flag;
186
187   err = ksba_cert_is_ca (cert, &flag, chainlen);
188   if (err)
189     return err;
190   if (!flag)
191     {
192       if (!is_trusted_cert (cert))
193         {
194           /* The German SigG Root CA's certificate does not flag
195              itself as a CA; thus we relax this requirement if we
196              trust a root CA.  I think this is reasonable.  Note, that
197              gpgsm implements a far stricter scheme here. */
198           if (chainlen)
199             *chainlen = 3; /* That is what the SigG implements. */
200           if (opt.verbose)
201             log_info (_("accepting root CA not marked as a CA"));
202         }
203       else
204         {
205           log_error (_("issuer certificate is not marked as a CA"));
206           return gpg_error (GPG_ERR_BAD_CA_CERT);
207         }
208     }
209   return 0;
210 }
211
212 /* Helper for validate_cert_chain.  */
213 static gpg_error_t
214 check_revocations (ctrl_t ctrl, chain_item_t chain)
215 {
216   gpg_error_t err = 0;
217   int any_revoked = 0;
218   int any_no_crl = 0;
219   int any_crl_too_old = 0;
220   chain_item_t ci;
221
222   assert (ctrl->check_revocations_nest_level >= 0);
223   assert (chain);
224
225   if (ctrl->check_revocations_nest_level > 10)
226     {
227       log_error (_("CRL checking too deeply nested\n"));
228       return gpg_error(GPG_ERR_BAD_CERT_CHAIN);
229     }
230   ctrl->check_revocations_nest_level++;
231
232
233   for (ci=chain; ci; ci = ci->next)
234     {
235       assert (ci->cert);
236       if (ci == chain)
237         {
238           /* It does not make sense to check the root certificate for
239              revocations.  In almost all cases this will lead to a
240              catch-22 as the root certificate is the final trust
241              anchor for the certificates and the CRLs.  We expect the
242              user to remove root certificates from the list of trusted
243              certificates in case they have been revoked. */
244           if (opt.verbose)
245             cert_log_name (_("not checking CRL for"), ci->cert);
246           continue;
247         }
248
249       if (opt.verbose)
250         cert_log_name (_("checking CRL for"), ci->cert);
251       err = crl_cache_cert_isvalid (ctrl, ci->cert, 0);
252       if (gpg_err_code (err) == GPG_ERR_NO_CRL_KNOWN)
253         {
254           err = crl_cache_reload_crl (ctrl, ci->cert);
255           if (!err)
256             err = crl_cache_cert_isvalid (ctrl, ci->cert, 0);
257         }
258       switch (gpg_err_code (err))
259         {
260         case 0: err = 0; break;
261         case GPG_ERR_CERT_REVOKED: any_revoked = 1; err = 0; break;
262         case GPG_ERR_NO_CRL_KNOWN: any_no_crl = 1; err = 0; break;
263         case GPG_ERR_CRL_TOO_OLD: any_crl_too_old = 1; err = 0; break;
264         default: break;
265         }
266     }
267   ctrl->check_revocations_nest_level--;
268
269
270   if (err)
271     ;
272   else if (any_revoked)
273     err = gpg_error (GPG_ERR_CERT_REVOKED);
274   else if (any_no_crl)
275     err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
276   else if (any_crl_too_old)
277     err = gpg_error (GPG_ERR_CRL_TOO_OLD);
278   else
279     err = 0;
280   return err;
281 }
282
283
284 /* Check whether CERT is a root certificate.  ISSUERDN and SUBJECTDN
285    are the DNs already extracted by the caller from CERT.  Returns
286    True if this is the case. */
287 static int
288 is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn)
289 {
290   gpg_error_t err;
291   int result = 0;
292   ksba_sexp_t serialno;
293   ksba_sexp_t ak_keyid;
294   ksba_name_t ak_name;
295   ksba_sexp_t ak_sn;
296   const char *ak_name_str;
297   ksba_sexp_t subj_keyid = NULL;
298
299   if (!issuerdn || !subjectdn)
300     return 0;  /* No.  */
301
302   if (strcmp (issuerdn, subjectdn))
303     return 0;  /* No.  */
304
305   err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn);
306   if (err)
307     {
308       if (gpg_err_code (err) == GPG_ERR_NO_DATA)
309         return 1; /* Yes. Without a authorityKeyIdentifier this needs
310                      to be the Root certifcate (our trust anchor).  */
311       log_error ("error getting authorityKeyIdentifier: %s\n",
312                  gpg_strerror (err));
313       return 0; /* Well, it is broken anyway.  Return No. */
314     }
315
316   serialno = ksba_cert_get_serial (cert);
317   if (!serialno)
318     {
319       log_error ("error getting serialno: %s\n", gpg_strerror (err));
320       goto leave;
321     }
322
323   /* Check whether the auth name's matches the issuer name+sn.  If
324      that is the case this is a root certificate.  */
325   ak_name_str = ksba_name_enum (ak_name, 0);
326   if (ak_name_str
327       && !strcmp (ak_name_str, issuerdn)
328       && !cmp_simple_canon_sexp (ak_sn, serialno))
329     {
330       result = 1;  /* Right, CERT is self-signed.  */
331       goto leave;
332     }
333
334   /* Similar for the ak_keyid. */
335   if (ak_keyid && !ksba_cert_get_subj_key_id (cert, NULL, &subj_keyid)
336       && !cmp_simple_canon_sexp (ak_keyid, subj_keyid))
337     {
338       result = 1;  /* Right, CERT is self-signed.  */
339       goto leave;
340     }
341
342
343  leave:
344   ksba_free (subj_keyid);
345   ksba_free (ak_keyid);
346   ksba_name_release (ak_name);
347   ksba_free (ak_sn);
348   ksba_free (serialno);
349   return result;
350 }
351
352
353 /* Validate the certificate CHAIN up to the trust anchor. Optionally
354    return the closest expiration time in R_EXPTIME (this is useful for
355    caching issues).  MODE is one of the VALIDATE_MODE_* constants.
356
357    Note that VALIDATE_MODE_OCSP is not used due to the removal of the
358    system service in 2.1.15.  Instead only the callback to gpgsm to
359    validate a certificate is used.
360
361    If R_TRUST_ANCHOR is not NULL and the validation would fail only
362    because the root certificate is not trusted, the hexified
363    fingerprint of that root certificate is stored at R_TRUST_ANCHOR
364    and success is returned.  The caller needs to free the value at
365    R_TRUST_ANCHOR; in all other cases NULL is stored there.  */
366 gpg_error_t
367 validate_cert_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t r_exptime,
368                      int mode, char **r_trust_anchor)
369 {
370   gpg_error_t err = 0;
371   int depth, maxdepth;
372   char *issuer = NULL;
373   char *subject = NULL;
374   ksba_cert_t subject_cert = NULL, issuer_cert = NULL;
375   ksba_isotime_t current_time;
376   ksba_isotime_t exptime;
377   int any_expired = 0;
378   int any_no_policy_match = 0;
379   chain_item_t chain;
380
381
382   if (r_exptime)
383     *r_exptime = 0;
384   *exptime = 0;
385
386   if (r_trust_anchor)
387     *r_trust_anchor = NULL;
388
389   if (DBG_X509)
390     dump_cert ("subject", cert);
391
392   /* May the target certificate be used for this purpose?  */
393   switch (mode)
394     {
395     case VALIDATE_MODE_OCSP:
396       err = cert_use_ocsp_p (cert);
397       break;
398     case VALIDATE_MODE_CRL:
399     case VALIDATE_MODE_CRL_RECURSIVE:
400       err = cert_use_crl_p (cert);
401       break;
402     default:
403       err = 0;
404       break;
405     }
406   if (err)
407     return err;
408
409   /* If we already validated the certificate not too long ago, we can
410      avoid the excessive computations and lookups unless the caller
411      asked for the expiration time.  */
412   if (!r_exptime)
413     {
414       size_t buflen;
415       time_t validated_at;
416
417       err = ksba_cert_get_user_data (cert, "validated_at",
418                                      &validated_at, sizeof (validated_at),
419                                      &buflen);
420       if (err || buflen != sizeof (validated_at) || !validated_at)
421         err = 0; /* Not available or other error. */
422       else
423         {
424           /* If the validation is not older than 30 minutes we are ready. */
425           if (validated_at < gnupg_get_time () + (30*60))
426             {
427               if (opt.verbose)
428                 log_info ("certificate is good (cached)\n");
429               /* Note, that we can't jump to leave here as this would
430                  falsely updated the validation timestamp.  */
431               return 0;
432             }
433         }
434     }
435
436   /* Get the current time. */
437   gnupg_get_isotime (current_time);
438
439   /* We walk up the chain until we find a trust anchor. */
440   subject_cert = cert;
441   maxdepth = 10;
442   chain = NULL;
443   depth = 0;
444   for (;;)
445     {
446       /* Get the subject and issuer name from the current
447          certificate.  */
448       ksba_free (issuer);
449       ksba_free (subject);
450       issuer = ksba_cert_get_issuer (subject_cert, 0);
451       subject = ksba_cert_get_subject (subject_cert, 0);
452
453       if (!issuer)
454         {
455           log_error (_("no issuer found in certificate\n"));
456           err = gpg_error (GPG_ERR_BAD_CERT);
457           goto leave;
458         }
459
460       /* Handle the notBefore and notAfter timestamps.  */
461       {
462         ksba_isotime_t not_before, not_after;
463
464         err = ksba_cert_get_validity (subject_cert, 0, not_before);
465         if (!err)
466           err = ksba_cert_get_validity (subject_cert, 1, not_after);
467         if (err)
468           {
469             log_error (_("certificate with invalid validity: %s"),
470                        gpg_strerror (err));
471             err = gpg_error (GPG_ERR_BAD_CERT);
472             goto leave;
473           }
474
475         /* Keep track of the nearest expiration time in EXPTIME.  */
476         if (*not_after)
477           {
478             if (!*exptime)
479               gnupg_copy_time (exptime, not_after);
480             else if (strcmp (not_after, exptime) < 0 )
481               gnupg_copy_time (exptime, not_after);
482           }
483
484         /* Check whether the certificate is already valid.  */
485         if (*not_before && strcmp (current_time, not_before) < 0 )
486           {
487             log_error (_("certificate not yet valid"));
488             log_info ("(valid from ");
489             dump_isotime (not_before);
490             log_printf (")\n");
491             err = gpg_error (GPG_ERR_CERT_TOO_YOUNG);
492             goto leave;
493           }
494
495         /* Now check whether the certificate has expired.  */
496         if (*not_after && strcmp (current_time, not_after) > 0 )
497           {
498             log_error (_("certificate has expired"));
499             log_info ("(expired at ");
500             dump_isotime (not_after);
501             log_printf (")\n");
502             any_expired = 1;
503           }
504       }
505
506       /* Do we have any critical extensions in the certificate we
507          can't handle? */
508       err = unknown_criticals (subject_cert);
509       if (err)
510         goto leave; /* yes. */
511
512       /* Check that given policies are allowed.  */
513       err = check_cert_policy (subject_cert);
514       if (gpg_err_code (err) == GPG_ERR_NO_POLICY_MATCH)
515         {
516           any_no_policy_match = 1;
517           err = 0;
518         }
519       else if (err)
520         goto leave;
521
522       /* Is this a self-signed certificate? */
523       if (is_root_cert ( subject_cert, issuer, subject))
524         {
525           /* Yes, this is our trust anchor.  */
526           if (check_cert_sig (subject_cert, subject_cert) )
527             {
528               log_error (_("selfsigned certificate has a BAD signature"));
529               err = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN
530                                     : GPG_ERR_BAD_CERT);
531               goto leave;
532             }
533
534           /* Is this certificate allowed to act as a CA.  */
535           err = allowed_ca (subject_cert, NULL);
536           if (err)
537             goto leave;  /* No. */
538
539           err = is_trusted_cert (subject_cert);
540           if (!err)
541             ; /* Yes we trust this cert.  */
542           else if (gpg_err_code (err) == GPG_ERR_NOT_TRUSTED)
543             {
544               char *fpr;
545
546               log_error (_("root certificate is not marked trusted"));
547               fpr = get_fingerprint_hexstring (subject_cert);
548               log_info (_("fingerprint=%s\n"), fpr? fpr : "?");
549               dump_cert ("issuer", subject_cert);
550               if (r_trust_anchor)
551                 {
552                   /* Caller wants to do another trustiness check.  */
553                   *r_trust_anchor = fpr;
554                   err = 0;
555                 }
556               else
557                 xfree (fpr);
558             }
559           else
560             {
561               log_error (_("checking trustworthiness of "
562                            "root certificate failed: %s\n"),
563                          gpg_strerror (err));
564             }
565           if (err)
566             goto leave;
567
568           /* Prepend the certificate to our list.  */
569           {
570             chain_item_t ci;
571
572             ci = xtrycalloc (1, sizeof *ci);
573             if (!ci)
574               {
575                 err = gpg_error_from_errno (errno);
576                 goto leave;
577               }
578             ksba_cert_ref (subject_cert);
579             ci->cert = subject_cert;
580             cert_compute_fpr (subject_cert, ci->fpr);
581             ci->next = chain;
582             chain = ci;
583           }
584
585           if (opt.verbose)
586             {
587               if (r_trust_anchor && *r_trust_anchor)
588                 log_info ("root certificate is good but not trusted\n");
589               else
590                 log_info ("root certificate is good and trusted\n");
591             }
592
593           break;  /* Okay: a self-signed certicate is an end-point. */
594         }
595
596       /* To avoid loops, we use an arbitrary limit on the length of
597          the chain. */
598       depth++;
599       if (depth > maxdepth)
600         {
601           log_error (_("certificate chain too long\n"));
602           err = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
603           goto leave;
604         }
605
606       /* Find the next cert up the tree. */
607       ksba_cert_release (issuer_cert); issuer_cert = NULL;
608       err = find_issuing_cert (ctrl, subject_cert, &issuer_cert);
609       if (err)
610         {
611           if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
612             {
613               log_error (_("issuer certificate not found"));
614               log_info ("issuer certificate: #/");
615               dump_string (issuer);
616               log_printf ("\n");
617             }
618           else
619             log_error (_("issuer certificate not found: %s\n"),
620                          gpg_strerror (err));
621           /* Use a better understandable error code.  */
622           err = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
623           goto leave;
624         }
625
626 /*     try_another_cert: */
627       if (DBG_X509)
628         {
629           log_debug ("got issuer's certificate:\n");
630           dump_cert ("issuer", issuer_cert);
631         }
632
633       /* Now check the signature of the certificate.  Well, we
634          should delay this until later so that faked certificates
635          can't be turned into a DoS easily.  */
636       err = check_cert_sig (issuer_cert, subject_cert);
637       if (err)
638         {
639           log_error (_("certificate has a BAD signature"));
640 #if 0
641           if (gpg_err_code (err) == GPG_ERR_BAD_SIGNATURE)
642             {
643               /* We now try to find other issuer certificates which
644                  might have been used.  This is required because some
645                  CAs are reusing the issuer and subject DN for new
646                  root certificates without using a  authorityKeyIdentifier. */
647               rc = find_up (kh, subject_cert, issuer, 1);
648               if (!rc)
649                 {
650                   ksba_cert_t tmp_cert;
651
652                   rc = keydb_get_cert (kh, &tmp_cert);
653                   if (rc || !compare_certs (issuer_cert, tmp_cert))
654                     {
655                       /* The find next did not work or returned an
656                          identical certificate.  We better stop here
657                          to avoid infinite checks. */
658                       rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
659                       ksba_cert_release (tmp_cert);
660                     }
661                   else
662                     {
663                       do_list (0, lm, fp, _("found another possible matching "
664                                             "CA certificate - trying again"));
665                       ksba_cert_release (issuer_cert);
666                       issuer_cert = tmp_cert;
667                       goto try_another_cert;
668                     }
669                 }
670             }
671 #endif
672           /* We give a more descriptive error code than the one
673              returned from the signature checking. */
674           err = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
675           goto leave;
676         }
677
678       /* Check that the length of the chain is not longer than allowed
679          by the CA.  */
680       {
681         int chainlen;
682
683         err = allowed_ca (issuer_cert, &chainlen);
684         if (err)
685           goto leave;
686         if (chainlen >= 0 && (depth - 1) > chainlen)
687           {
688             log_error (_("certificate chain longer than allowed by CA (%d)"),
689                        chainlen);
690             err = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
691             goto leave;
692           }
693       }
694
695       /* May that certificate be used for certification? */
696       err = cert_use_cert_p (issuer_cert);
697       if (err)
698         goto leave;  /* No.  */
699
700       /* Prepend the certificate to our list.  */
701       {
702         chain_item_t ci;
703
704         ci = xtrycalloc (1, sizeof *ci);
705         if (!ci)
706           {
707             err = gpg_error_from_errno (errno);
708             goto leave;
709           }
710         ksba_cert_ref (subject_cert);
711         ci->cert = subject_cert;
712         cert_compute_fpr (subject_cert, ci->fpr);
713         ci->next = chain;
714         chain = ci;
715       }
716
717       if (opt.verbose)
718         log_info (_("certificate is good\n"));
719
720       /* Now to the next level up.  */
721       subject_cert = issuer_cert;
722       issuer_cert = NULL;
723     }
724
725   if (!err)
726     { /* If we encountered an error somewhere during the checks, set
727          the error code to the most critical one */
728       if (any_expired)
729         err = gpg_error (GPG_ERR_CERT_EXPIRED);
730       else if (any_no_policy_match)
731         err = gpg_error (GPG_ERR_NO_POLICY_MATCH);
732     }
733
734   if (!err && opt.verbose)
735     {
736       chain_item_t citem;
737
738       log_info (_("certificate chain is good\n"));
739       for (citem = chain; citem; citem = citem->next)
740         cert_log_name ("  certificate", citem->cert);
741     }
742
743   if (!err && mode != VALIDATE_MODE_CRL)
744     { /* Now that everything is fine, walk the chain and check each
745          certificate for revocations.
746
747          1. item in the chain  - The root certificate.
748          2. item               - the CA below the root
749          last item             - the target certificate.
750
751          Now for each certificate in the chain check whether it has
752          been included in a CRL and thus be revoked.  We don't do OCSP
753          here because this does not seem to make much sense.  This
754          might become a recursive process and we should better cache
755          our validity results to avoid double work.  Far worse a
756          catch-22 may happen for an improper setup hierarchy and we
757          need a way to break up such a deadlock. */
758       err = check_revocations (ctrl, chain);
759     }
760
761   if (!err && opt.verbose)
762     {
763       if (r_trust_anchor && *r_trust_anchor)
764         log_info ("target certificate may be valid\n");
765       else
766         log_info ("target certificate is valid\n");
767     }
768   else if (err && opt.verbose)
769     log_info ("target certificate is NOT valid\n");
770
771
772  leave:
773   if (!err && !(r_trust_anchor && *r_trust_anchor))
774     {
775       /* With no error we can update the validation cache.  We do this
776          for all certificates in the chain.  Note that we can't use
777          the cache if the caller requested to check the trustiness of
778          the root certificate himself.  Adding such a feature would
779          require us to also store the fingerprint of root
780          certificate.  */
781       chain_item_t citem;
782       time_t validated_at = gnupg_get_time ();
783
784       for (citem = chain; citem; citem = citem->next)
785         {
786           err = ksba_cert_set_user_data (citem->cert, "validated_at",
787                                          &validated_at, sizeof (validated_at));
788           if (err)
789             {
790               log_error ("set_user_data(validated_at) failed: %s\n",
791                          gpg_strerror (err));
792               err = 0;
793             }
794         }
795     }
796
797   if (r_exptime)
798     gnupg_copy_time (r_exptime, exptime);
799   ksba_free (issuer);
800   ksba_free (subject);
801   ksba_cert_release (issuer_cert);
802   if (subject_cert != cert)
803     ksba_cert_release (subject_cert);
804   while (chain)
805     {
806       chain_item_t ci_next = chain->next;
807       if (chain->cert)
808         ksba_cert_release (chain->cert);
809       xfree (chain);
810       chain = ci_next;
811     }
812   if (err && r_trust_anchor && *r_trust_anchor)
813     {
814       xfree (*r_trust_anchor);
815       *r_trust_anchor = NULL;
816     }
817   return err;
818 }
819
820
821 \f
822 /* Return the public key algorithm id from the S-expression PKEY.
823    FIXME: libgcrypt should provide such a function.  Note that this
824    implementation uses the names as used by libksba.  */
825 static int
826 pk_algo_from_sexp (gcry_sexp_t pkey)
827 {
828   gcry_sexp_t l1, l2;
829   const char *name;
830   size_t n;
831   int algo;
832
833   l1 = gcry_sexp_find_token (pkey, "public-key", 0);
834   if (!l1)
835     return 0; /* Not found.  */
836   l2 = gcry_sexp_cadr (l1);
837   gcry_sexp_release (l1);
838
839   name = gcry_sexp_nth_data (l2, 0, &n);
840   if (!name)
841     algo = 0; /* Not found. */
842   else if (n==3 && !memcmp (name, "rsa", 3))
843     algo = GCRY_PK_RSA;
844   else if (n==3 && !memcmp (name, "dsa", 3))
845     algo = GCRY_PK_DSA;
846   else if (n==13 && !memcmp (name, "ambiguous-rsa", 13))
847     algo = GCRY_PK_RSA;
848   else
849     algo = 0;
850   gcry_sexp_release (l2);
851   return algo;
852 }
853
854
855 /* Check the signature on CERT using the ISSUER_CERT.  This function
856    does only test the cryptographic signature and nothing else.  It is
857    assumed that the ISSUER_CERT is valid. */
858 static gpg_error_t
859 check_cert_sig (ksba_cert_t issuer_cert, ksba_cert_t cert)
860 {
861   gpg_error_t err;
862   const char *algoid;
863   gcry_md_hd_t md;
864   int i, algo;
865   ksba_sexp_t p;
866   size_t n;
867   gcry_sexp_t s_sig, s_hash, s_pkey;
868   const char *s;
869   char algo_name[16+1]; /* hash algorithm name converted to lower case. */
870   int digestlen;
871   unsigned char *digest;
872
873   /* Hash the target certificate using the algorithm from that certificate.  */
874   algoid = ksba_cert_get_digest_algo (cert);
875   algo = gcry_md_map_name (algoid);
876   if (!algo)
877     {
878       log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?");
879       return gpg_error (GPG_ERR_GENERAL);
880     }
881   s = gcry_md_algo_name (algo);
882   for (i=0; *s && i < sizeof algo_name - 1; s++, i++)
883     algo_name[i] = tolower (*s);
884   algo_name[i] = 0;
885
886   err = gcry_md_open (&md, algo, 0);
887   if (err)
888     {
889       log_error ("md_open failed: %s\n", gpg_strerror (err));
890       return err;
891     }
892   if (DBG_HASHING)
893     gcry_md_debug (md, "hash.cert");
894
895   err = ksba_cert_hash (cert, 1, HASH_FNC, md);
896   if (err)
897     {
898       log_error ("ksba_cert_hash failed: %s\n", gpg_strerror (err));
899       gcry_md_close (md);
900       return err;
901     }
902   gcry_md_final (md);
903
904   /* Get the signature value out of the target certificate.  */
905   p = ksba_cert_get_sig_val (cert);
906   n = gcry_sexp_canon_len (p, 0, NULL, NULL);
907   if (!n)
908     {
909       log_error ("libksba did not return a proper S-Exp\n");
910       gcry_md_close (md);
911       ksba_free (p);
912       return gpg_error (GPG_ERR_BUG);
913     }
914   if (DBG_CRYPTO)
915     {
916       int j;
917       log_debug ("signature value:");
918       for (j=0; j < n; j++)
919         log_printf (" %02X", p[j]);
920       log_printf ("\n");
921     }
922
923   err = gcry_sexp_sscan ( &s_sig, NULL, p, n);
924   ksba_free (p);
925   if (err)
926     {
927       log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (err));
928       gcry_md_close (md);
929       return err;
930     }
931
932   /* Get the public key from the issuer certificate.  */
933   p = ksba_cert_get_public_key (issuer_cert);
934   n = gcry_sexp_canon_len (p, 0, NULL, NULL);
935   if (!n)
936     {
937       log_error ("libksba did not return a proper S-Exp\n");
938       gcry_md_close (md);
939       ksba_free (p);
940       gcry_sexp_release (s_sig);
941       return gpg_error (GPG_ERR_BUG);
942     }
943   err = gcry_sexp_sscan ( &s_pkey, NULL, p, n);
944   ksba_free (p);
945   if (err)
946     {
947       log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (err));
948       gcry_md_close (md);
949       gcry_sexp_release (s_sig);
950       return err;
951     }
952
953
954   /* Prepare the values for signature verification. At this point we
955      have these values:
956
957      S_PKEY    - S-expression with the issuer's public key.
958      S_SIG     - Signature value as given in the certrificate.
959      MD        - Finalized hash context with hash of the certificate.
960      ALGO_NAME - Lowercase hash algorithm name
961    */
962   digestlen = gcry_md_get_algo_dlen (algo);
963   digest = gcry_md_read (md, algo);
964   if (pk_algo_from_sexp (s_pkey) == GCRY_PK_DSA)
965     {
966       if (digestlen != 20)
967         {
968           log_error (_("DSA requires the use of a 160 bit hash algorithm\n"));
969           gcry_md_close (md);
970           gcry_sexp_release (s_sig);
971           gcry_sexp_release (s_pkey);
972           return gpg_error (GPG_ERR_INTERNAL);
973         }
974       if ( gcry_sexp_build (&s_hash, NULL, "(data(flags raw)(value %b))",
975                             (int)digestlen, digest) )
976         BUG ();
977     }
978   else /* Not DSA.  */
979     {
980       if ( gcry_sexp_build (&s_hash, NULL, "(data(flags pkcs1)(hash %s %b))",
981                             algo_name, (int)digestlen, digest) )
982         BUG ();
983
984     }
985
986   err = gcry_pk_verify (s_sig, s_hash, s_pkey);
987   if (DBG_X509)
988     log_debug ("gcry_pk_verify: %s\n", gpg_strerror (err));
989   gcry_md_close (md);
990   gcry_sexp_release (s_sig);
991   gcry_sexp_release (s_hash);
992   gcry_sexp_release (s_pkey);
993   return err;
994 }
995
996
997 \f
998 /* Return 0 if the cert is usable for encryption.  A MODE of 0 checks
999    for signing, a MODE of 1 checks for encryption, a MODE of 2 checks
1000    for verification and a MODE of 3 for decryption (just for
1001    debugging).  MODE 4 is for certificate signing, MODE 5 for OCSP
1002    response signing, MODE 6 is for CRL signing. */
1003 static int
1004 cert_usage_p (ksba_cert_t cert, int mode)
1005 {
1006   gpg_error_t err;
1007   unsigned int use;
1008   char *extkeyusages;
1009   int have_ocsp_signing = 0;
1010
1011   err = ksba_cert_get_ext_key_usages (cert, &extkeyusages);
1012   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1013     err = 0; /* No policy given. */
1014   if (!err)
1015     {
1016       unsigned int extusemask = ~0; /* Allow all. */
1017
1018       if (extkeyusages)
1019         {
1020           char *p, *pend;
1021           int any_critical = 0;
1022
1023           extusemask = 0;
1024
1025           p = extkeyusages;
1026           while (p && (pend=strchr (p, ':')))
1027             {
1028               *pend++ = 0;
1029               /* Only care about critical flagged usages. */
1030               if ( *pend == 'C' )
1031                 {
1032                   any_critical = 1;
1033                   if ( !strcmp (p, oid_kp_serverAuth))
1034                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1035                                    | KSBA_KEYUSAGE_KEY_ENCIPHERMENT
1036                                    | KSBA_KEYUSAGE_KEY_AGREEMENT);
1037                   else if ( !strcmp (p, oid_kp_clientAuth))
1038                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1039                                    | KSBA_KEYUSAGE_KEY_AGREEMENT);
1040                   else if ( !strcmp (p, oid_kp_codeSigning))
1041                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE);
1042                   else if ( !strcmp (p, oid_kp_emailProtection))
1043                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1044                                    | KSBA_KEYUSAGE_NON_REPUDIATION
1045                                    | KSBA_KEYUSAGE_KEY_ENCIPHERMENT
1046                                    | KSBA_KEYUSAGE_KEY_AGREEMENT);
1047                   else if ( !strcmp (p, oid_kp_timeStamping))
1048                     extusemask |= (KSBA_KEYUSAGE_DIGITAL_SIGNATURE
1049                                    | KSBA_KEYUSAGE_NON_REPUDIATION);
1050                 }
1051
1052               /* This is a hack to cope with OCSP.  Note that we do
1053                  not yet fully comply with the requirements and that
1054                  the entire CRL/OCSP checking thing should undergo a
1055                  thorough review and probably redesign. */
1056               if ( !strcmp (p, oid_kp_ocspSigning))
1057                 have_ocsp_signing = 1;
1058
1059               if ((p = strchr (pend, '\n')))
1060                 p++;
1061             }
1062           ksba_free (extkeyusages);
1063           extkeyusages = NULL;
1064
1065           if (!any_critical)
1066             extusemask = ~0; /* Reset to the don't care mask. */
1067         }
1068
1069
1070       err = ksba_cert_get_key_usage (cert, &use);
1071       if (gpg_err_code (err) == GPG_ERR_NO_DATA)
1072         {
1073           err = 0;
1074           if (opt.verbose && mode < 2)
1075             log_info (_("no key usage specified - assuming all usages\n"));
1076           use = ~0;
1077         }
1078
1079       /* Apply extKeyUsage. */
1080       use &= extusemask;
1081
1082     }
1083   if (err)
1084     {
1085       log_error (_("error getting key usage information: %s\n"),
1086                  gpg_strerror (err));
1087       ksba_free (extkeyusages);
1088       return err;
1089     }
1090
1091   if (mode == 4)
1092     {
1093       if ((use & (KSBA_KEYUSAGE_KEY_CERT_SIGN)))
1094         return 0;
1095       log_info (_("certificate should not have "
1096                   "been used for certification\n"));
1097       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1098     }
1099
1100   if (mode == 5)
1101     {
1102       if (use != ~0
1103           && (have_ocsp_signing
1104               || (use & (KSBA_KEYUSAGE_KEY_CERT_SIGN
1105                          |KSBA_KEYUSAGE_CRL_SIGN))))
1106         return 0;
1107       log_info (_("certificate should not have "
1108                   "been used for OCSP response signing\n"));
1109       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1110     }
1111
1112   if (mode == 6)
1113     {
1114       if ((use & (KSBA_KEYUSAGE_CRL_SIGN)))
1115         return 0;
1116       log_info (_("certificate should not have "
1117                   "been used for CRL signing\n"));
1118       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1119     }
1120
1121   if ((use & ((mode&1)?
1122               (KSBA_KEYUSAGE_KEY_ENCIPHERMENT|KSBA_KEYUSAGE_DATA_ENCIPHERMENT):
1123               (KSBA_KEYUSAGE_DIGITAL_SIGNATURE|KSBA_KEYUSAGE_NON_REPUDIATION)))
1124       )
1125     return 0;
1126
1127   log_info (mode==3? _("certificate should not have been used "
1128                        "for encryption\n"):
1129             mode==2? _("certificate should not have been used for signing\n"):
1130             mode==1? _("certificate is not usable for encryption\n"):
1131                      _("certificate is not usable for signing\n"));
1132   return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
1133 }
1134
1135 /* Return 0 if the certificate CERT is usable for certification.  */
1136 gpg_error_t
1137 cert_use_cert_p (ksba_cert_t cert)
1138 {
1139   return cert_usage_p (cert, 4);
1140 }
1141
1142 /* Return 0 if the certificate CERT is usable for signing OCSP
1143    responses.  */
1144 gpg_error_t
1145 cert_use_ocsp_p (ksba_cert_t cert)
1146 {
1147   return cert_usage_p (cert, 5);
1148 }
1149
1150 /* Return 0 if the certificate CERT is usable for signing CRLs. */
1151 gpg_error_t
1152 cert_use_crl_p (ksba_cert_t cert)
1153 {
1154   return cert_usage_p (cert, 6);
1155 }