chiark / gitweb /
build: Enable gcc warnings to detect non-portable code.
[gnupg2.git] / sm / certchain.c
1 /* certchain.c - certificate chain validation
2  * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3  *               2006, 2007, 2008, 2011 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <time.h>
28 #include <stdarg.h>
29 #include <assert.h>
30
31 #include "gpgsm.h"
32 #include <gcrypt.h>
33 #include <ksba.h>
34
35 #include "keydb.h"
36 #include "../kbx/keybox.h" /* for KEYBOX_FLAG_* */
37 #include "i18n.h"
38 #include "tlv.h"
39
40
41 /* Object to keep track of certain root certificates. */
42 struct marktrusted_info_s
43 {
44   struct marktrusted_info_s *next;
45   unsigned char fpr[20];
46 };
47 static struct marktrusted_info_s *marktrusted_info;
48
49
50 /* While running the validation function we want to keep track of the
51    certificates in the chain.  This type is used for that.  */
52 struct chain_item_s
53 {
54   struct chain_item_s *next;
55   ksba_cert_t cert;      /* The certificate.  */
56   int is_root;           /* The certificate is the root certificate.  */
57 };
58 typedef struct chain_item_s *chain_item_t;
59
60
61 static int is_root_cert (ksba_cert_t cert,
62                          const char *issuerdn, const char *subjectdn);
63 static int get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen);
64
65
66 /* This function returns true if we already asked during this session
67    whether the root certificate CERT shall be marked as trusted.  */
68 static int
69 already_asked_marktrusted (ksba_cert_t cert)
70 {
71   unsigned char fpr[20];
72   struct marktrusted_info_s *r;
73
74   gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
75   /* No context switches in the loop! */
76   for (r=marktrusted_info; r; r= r->next)
77     if (!memcmp (r->fpr, fpr, 20))
78       return 1;
79   return 0;
80 }
81
82 /* Flag certificate CERT as already asked whether it shall be marked
83    as trusted.  */
84 static void
85 set_already_asked_marktrusted (ksba_cert_t cert)
86 {
87  unsigned char fpr[20];
88  struct marktrusted_info_s *r;
89
90  gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
91  for (r=marktrusted_info; r; r= r->next)
92    if (!memcmp (r->fpr, fpr, 20))
93      return; /* Already marked. */
94  r = xtrycalloc (1, sizeof *r);
95  if (!r)
96    return;
97  memcpy (r->fpr, fpr, 20);
98  r->next = marktrusted_info;
99  marktrusted_info = r;
100 }
101
102 /* If LISTMODE is true, print FORMAT using LISTMODE to FP.  If
103    LISTMODE is false, use the string to print an log_info or, if
104    IS_ERROR is true, and log_error. */
105 static void
106 do_list (int is_error, int listmode, estream_t fp, const char *format, ...)
107 {
108   va_list arg_ptr;
109
110   va_start (arg_ptr, format) ;
111   if (listmode)
112     {
113       if (fp)
114         {
115           es_fputs ("  [", fp);
116           es_vfprintf (fp, format, arg_ptr);
117           es_fputs ("]\n", fp);
118         }
119     }
120   else
121     {
122       log_logv (is_error? GPGRT_LOG_ERROR: GPGRT_LOG_INFO, format, arg_ptr);
123       log_printf ("\n");
124     }
125   va_end (arg_ptr);
126 }
127
128 /* Return 0 if A and B are equal. */
129 static int
130 compare_certs (ksba_cert_t a, ksba_cert_t b)
131 {
132   const unsigned char *img_a, *img_b;
133   size_t len_a, len_b;
134
135   img_a = ksba_cert_get_image (a, &len_a);
136   if (!img_a)
137     return 1;
138   img_b = ksba_cert_get_image (b, &len_b);
139   if (!img_b)
140     return 1;
141   return !(len_a == len_b && !memcmp (img_a, img_b, len_a));
142 }
143
144
145 /* Return true if CERT has the validityModel extensions and defines
146    the use of the chain model.  */
147 static int
148 has_validation_model_chain (ksba_cert_t cert, int listmode, estream_t listfp)
149 {
150   gpg_error_t err;
151   int idx, yes;
152   const char *oid;
153   size_t off, derlen, objlen, hdrlen;
154   const unsigned char *der;
155   int class, tag, constructed, ndef;
156   char *oidbuf;
157
158   for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
159                                              &oid, NULL, &off, &derlen));idx++)
160     if (!strcmp (oid, "1.3.6.1.4.1.8301.3.5") )
161       break;
162   if (err)
163     return 0; /* Not found.  */
164   der = ksba_cert_get_image (cert, NULL);
165   if (!der)
166     {
167       err = gpg_error (GPG_ERR_INV_OBJ); /* Oops  */
168       goto leave;
169     }
170   der += off;
171
172   err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
173                           &ndef, &objlen, &hdrlen);
174   if (!err && (objlen > derlen || tag != TAG_SEQUENCE))
175     err = gpg_error (GPG_ERR_INV_OBJ);
176   if (err)
177     goto leave;
178   derlen = objlen;
179   err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
180                           &ndef, &objlen, &hdrlen);
181   if (!err && (objlen > derlen || tag != TAG_OBJECT_ID))
182     err = gpg_error (GPG_ERR_INV_OBJ);
183   if (err)
184     goto leave;
185   oidbuf = ksba_oid_to_str (der, objlen);
186   if (!oidbuf)
187     {
188       err = gpg_error_from_syserror ();
189       goto leave;
190     }
191
192   if (opt.verbose)
193     do_list (0, listmode, listfp,
194              _("validation model requested by certificate: %s"),
195               !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1")? _("chain") :
196               !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.2")? _("shell") :
197               /* */                                       oidbuf);
198   yes = !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1");
199   ksba_free (oidbuf);
200   return yes;
201
202
203  leave:
204   log_error ("error parsing validityModel: %s\n", gpg_strerror (err));
205   return 0;
206 }
207
208
209
210 static int
211 unknown_criticals (ksba_cert_t cert, int listmode, estream_t fp)
212 {
213   static const char *known[] = {
214     "2.5.29.15", /* keyUsage */
215     "2.5.29.17", /* subjectAltName
216                     Japanese DoCoMo certs mark them as critical.  PKIX
217                     only requires them as critical if subjectName is
218                     empty.  I don't know whether our code gracefully
219                     handles such empry subjectNames but that is
220                     another story. */
221     "2.5.29.19", /* basic Constraints */
222     "2.5.29.32", /* certificatePolicies */
223     "2.5.29.37", /* extendedKeyUsage - handled by certlist.c */
224     "1.3.6.1.4.1.8301.3.5", /* validityModel - handled here. */
225     NULL
226   };
227   int rc = 0, i, idx, crit;
228   const char *oid;
229   gpg_error_t err;
230   int unsupported;
231   strlist_t sl;
232
233   for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
234                                              &oid, &crit, NULL, NULL));idx++)
235     {
236       if (!crit)
237         continue;
238       for (i=0; known[i] && strcmp (known[i],oid); i++)
239         ;
240       unsupported = !known[i];
241
242       /* If this critical extension is not supported.  Check the list
243          of to be ignored extensions to see whether we claim that it
244          is supported.  */
245       if (unsupported && opt.ignored_cert_extensions)
246         {
247           for (sl=opt.ignored_cert_extensions;
248                sl && strcmp (sl->d, oid); sl = sl->next)
249             ;
250           if (sl)
251             unsupported = 0;
252         }
253       if (unsupported)
254         {
255           do_list (1, listmode, fp,
256                    _("critical certificate extension %s is not supported"),
257                    oid);
258           rc = gpg_error (GPG_ERR_UNSUPPORTED_CERT);
259         }
260     }
261   /* We ignore the error codes EOF as well as no-value. The later will
262      occur for certificates with no extensions at all. */
263   if (err
264       && gpg_err_code (err) != GPG_ERR_EOF
265       && gpg_err_code (err) != GPG_ERR_NO_VALUE)
266     rc = err;
267
268   return rc;
269 }
270
271
272 /* Check whether CERT is an allowed certificate.  This requires that
273    CERT matches all requirements for such a CA, i.e. the
274    BasicConstraints extension.  The function returns 0 on success and
275    the allowed length of the chain at CHAINLEN. */
276 static int
277 allowed_ca (ctrl_t ctrl,
278             ksba_cert_t cert, int *chainlen, int listmode, estream_t fp)
279 {
280   gpg_error_t err;
281   int flag;
282
283   err = ksba_cert_is_ca (cert, &flag, chainlen);
284   if (err)
285     return err;
286   if (!flag)
287     {
288       if (get_regtp_ca_info (ctrl, cert, chainlen))
289         {
290           /* Note that dirmngr takes a different way to cope with such
291              certs. */
292           return 0; /* RegTP issued certificate. */
293         }
294
295       do_list (1, listmode, fp,_("issuer certificate is not marked as a CA"));
296       return gpg_error (GPG_ERR_BAD_CA_CERT);
297     }
298   return 0;
299 }
300
301
302 static int
303 check_cert_policy (ksba_cert_t cert, int listmode, estream_t fplist)
304 {
305   gpg_error_t err;
306   char *policies;
307   FILE *fp;
308   int any_critical;
309
310   err = ksba_cert_get_cert_policies (cert, &policies);
311   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
312     return 0; /* No policy given. */
313   if (err)
314     return err;
315
316   /* STRING is a line delimited list of certificate policies as stored
317      in the certificate.  The line itself is colon delimited where the
318      first field is the OID of the policy and the second field either
319      N or C for normal or critical extension */
320
321   if (opt.verbose > 1 && !listmode)
322     log_info ("certificate's policy list: %s\n", policies);
323
324   /* The check is very minimal but won't give false positives */
325   any_critical = !!strstr (policies, ":C");
326
327   if (!opt.policy_file)
328     {
329       xfree (policies);
330       if (any_critical)
331         {
332           do_list (1, listmode, fplist,
333                    _("critical marked policy without configured policies"));
334           return gpg_error (GPG_ERR_NO_POLICY_MATCH);
335         }
336       return 0;
337     }
338
339   fp = fopen (opt.policy_file, "r");
340   if (!fp)
341     {
342       if (opt.verbose || errno != ENOENT)
343         log_info (_("failed to open '%s': %s\n"),
344                   opt.policy_file, strerror (errno));
345       xfree (policies);
346       /* With no critical policies this is only a warning */
347       if (!any_critical)
348         {
349           if (!opt.quiet)
350             do_list (0, listmode, fplist,
351                      _("Note: non-critical certificate policy not allowed"));
352           return 0;
353         }
354       do_list (1, listmode, fplist,
355                _("certificate policy not allowed"));
356       return gpg_error (GPG_ERR_NO_POLICY_MATCH);
357     }
358
359   for (;;)
360     {
361       int c;
362       char *p, line[256];
363       char *haystack, *allowed;
364
365       /* read line */
366       do
367         {
368           if (!fgets (line, DIM(line)-1, fp) )
369             {
370               gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
371
372               xfree (policies);
373               if (feof (fp))
374                 {
375                   fclose (fp);
376                   /* With no critical policies this is only a warning */
377                   if (!any_critical)
378                     {
379                       do_list (0, listmode, fplist,
380                      _("Note: non-critical certificate policy not allowed"));
381                       return 0;
382                     }
383                   do_list (1, listmode, fplist,
384                            _("certificate policy not allowed"));
385                   return gpg_error (GPG_ERR_NO_POLICY_MATCH);
386                 }
387               fclose (fp);
388               return tmperr;
389             }
390
391           if (!*line || line[strlen(line)-1] != '\n')
392             {
393               /* eat until end of line */
394               while ( (c=getc (fp)) != EOF && c != '\n')
395                 ;
396               fclose (fp);
397               xfree (policies);
398               return gpg_error (*line? GPG_ERR_LINE_TOO_LONG
399                                      : GPG_ERR_INCOMPLETE_LINE);
400             }
401
402           /* Allow for empty lines and spaces */
403           for (p=line; spacep (p); p++)
404             ;
405         }
406       while (!*p || *p == '\n' || *p == '#');
407
408       /* Parse line.  Note that the line has always a LF and spacep
409          does not consider a LF a space.  Thus strpbrk will always
410          succeed.  */
411       for (allowed=line; spacep (allowed); allowed++)
412         ;
413       p = strpbrk (allowed, " :\n");
414       if (!*p || p == allowed)
415         {
416           fclose (fp);
417           xfree (policies);
418           return gpg_error (GPG_ERR_CONFIGURATION);
419         }
420       *p = 0; /* strip the rest of the line */
421       /* See whether we find ALLOWED (which is an OID) in POLICIES */
422       for (haystack=policies; (p=strstr (haystack, allowed)); haystack = p+1)
423         {
424           if ( !(p == policies || p[-1] == '\n') )
425             continue; /* Does not match the begin of a line. */
426           if (p[strlen (allowed)] != ':')
427             continue; /* The length does not match. */
428           /* Yep - it does match so return okay. */
429           fclose (fp);
430           xfree (policies);
431           return 0;
432         }
433     }
434 }
435
436
437 /* Helper function for find_up.  This resets the key handle and search
438    for an issuer ISSUER with a subjectKeyIdentifier of KEYID.  Returns
439    0 on success or -1 when not found. */
440 static int
441 find_up_search_by_keyid (ctrl_t ctrl, KEYDB_HANDLE kh,
442                          const char *issuer, ksba_sexp_t keyid)
443 {
444   int rc;
445   ksba_cert_t cert = NULL;
446   ksba_sexp_t subj = NULL;
447   int anyfound = 0;
448   ksba_isotime_t not_before, last_not_before;
449
450   keydb_search_reset (kh);
451   while (!(rc = keydb_search_subject (ctrl, kh, issuer)))
452     {
453       ksba_cert_release (cert); cert = NULL;
454       rc = keydb_get_cert (kh, &cert);
455       if (rc)
456         {
457           log_error ("keydb_get_cert() failed: rc=%d\n", rc);
458           rc = -1;
459           break;
460         }
461       xfree (subj);
462       if (!ksba_cert_get_subj_key_id (cert, NULL, &subj))
463         {
464           if (!cmp_simple_canon_sexp (keyid, subj))
465             {
466               /* Found matching cert. */
467               rc = ksba_cert_get_validity (cert, 0, not_before);
468               if (rc)
469                 {
470                   log_error ("keydb_get_validity() failed: rc=%d\n", rc);
471                   rc = -1;
472                   break;
473                 }
474
475               if (!anyfound || strcmp (last_not_before, not_before) < 0)
476                 {
477                   /* This certificate is the first one found or newer
478                      than the previous one.  This copes with
479                      re-issuing CA certificates while keeping the same
480                      key information.  */
481                   anyfound = 1;
482                   gnupg_copy_time (last_not_before, not_before);
483                   keydb_push_found_state (kh);
484                 }
485             }
486         }
487     }
488
489   if (anyfound)
490     {
491       /* Take the last saved one.  */
492       keydb_pop_found_state (kh);
493       rc = 0;  /* Ignore EOF or other error after the first cert.  */
494     }
495
496   ksba_cert_release (cert);
497   xfree (subj);
498   return rc? -1:0;
499 }
500
501
502 struct find_up_store_certs_s
503 {
504   ctrl_t ctrl;
505   int count;
506 };
507
508 static void
509 find_up_store_certs_cb (void *cb_value, ksba_cert_t cert)
510 {
511   struct find_up_store_certs_s *parm = cb_value;
512
513   if (keydb_store_cert (parm->ctrl, cert, 1, NULL))
514     log_error ("error storing issuer certificate as ephemeral\n");
515   parm->count++;
516 }
517
518
519 /* Helper for find_up().  Locate the certificate for ISSUER using an
520    external lookup.  KH is the keydb context we are currently using.
521    On success 0 is returned and the certificate may be retrieved from
522    the keydb using keydb_get_cert().  KEYID is the keyIdentifier from
523    the AKI or NULL.  */
524 static int
525 find_up_external (ctrl_t ctrl, KEYDB_HANDLE kh,
526                   const char *issuer, ksba_sexp_t keyid)
527 {
528   int rc;
529   strlist_t names = NULL;
530   struct find_up_store_certs_s find_up_store_certs_parm;
531   char *pattern;
532   const char *s;
533
534   find_up_store_certs_parm.ctrl = ctrl;
535   find_up_store_certs_parm.count = 0;
536
537   if (opt.verbose)
538     log_info (_("looking up issuer at external location\n"));
539   /* The Dirmngr process is confused about unknown attributes.  As a
540      quick and ugly hack we locate the CN and use the issuer string
541      starting at this attribite.  Fixme: we should have far better
542      parsing for external lookups in the Dirmngr. */
543   s = strstr (issuer, "CN=");
544   if (!s || s == issuer || s[-1] != ',')
545     s = issuer;
546   pattern = xtrymalloc (strlen (s)+2);
547   if (!pattern)
548     return gpg_error_from_syserror ();
549   strcpy (stpcpy (pattern, "/"), s);
550   add_to_strlist (&names, pattern);
551   xfree (pattern);
552
553   rc = gpgsm_dirmngr_lookup (ctrl, names, 0, find_up_store_certs_cb,
554                              &find_up_store_certs_parm);
555   free_strlist (names);
556
557   if (opt.verbose)
558     log_info (_("number of issuers matching: %d\n"),
559               find_up_store_certs_parm.count);
560   if (rc)
561     {
562       log_error ("external key lookup failed: %s\n", gpg_strerror (rc));
563       rc = -1;
564     }
565   else if (!find_up_store_certs_parm.count)
566     rc = -1;
567   else
568     {
569       int old;
570       /* The issuers are currently stored in the ephemeral key DB, so
571          we temporary switch to ephemeral mode. */
572       old = keydb_set_ephemeral (kh, 1);
573       if (keyid)
574         rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
575       else
576         {
577           keydb_search_reset (kh);
578           rc = keydb_search_subject (ctrl, kh, issuer);
579         }
580       keydb_set_ephemeral (kh, old);
581     }
582   return rc;
583 }
584
585
586 /* Helper for find_up().  Ask the dirmngr for the certificate for
587    ISSUER with optional SERIALNO.  KH is the keydb context we are
588    currently using.  With SUBJECT_MODE set, ISSUER is searched as the
589    subject.  On success 0 is returned and the certificate is available
590    in the ephemeral DB.  */
591 static int
592 find_up_dirmngr (ctrl_t ctrl, KEYDB_HANDLE kh,
593                  ksba_sexp_t serialno, const char *issuer, int subject_mode)
594 {
595   int rc;
596   strlist_t names = NULL;
597   struct find_up_store_certs_s find_up_store_certs_parm;
598   char *pattern;
599
600   (void)kh;
601
602   find_up_store_certs_parm.ctrl = ctrl;
603   find_up_store_certs_parm.count = 0;
604
605   if (opt.verbose)
606     log_info (_("looking up issuer from the Dirmngr cache\n"));
607   if (subject_mode)
608     {
609       pattern = xtrymalloc (strlen (issuer)+2);
610       if (pattern)
611         strcpy (stpcpy (pattern, "/"), issuer);
612     }
613   else if (serialno)
614     pattern = gpgsm_format_sn_issuer (serialno, issuer);
615   else
616     {
617       pattern = xtrymalloc (strlen (issuer)+3);
618       if (pattern)
619         strcpy (stpcpy (pattern, "#/"), issuer);
620     }
621   if (!pattern)
622     return gpg_error_from_syserror ();
623   add_to_strlist (&names, pattern);
624   xfree (pattern);
625
626   rc = gpgsm_dirmngr_lookup (ctrl, names, 1, find_up_store_certs_cb,
627                              &find_up_store_certs_parm);
628   free_strlist (names);
629
630   if (opt.verbose)
631     log_info (_("number of matching certificates: %d\n"),
632               find_up_store_certs_parm.count);
633   if (rc && !opt.quiet)
634     log_info (_("dirmngr cache-only key lookup failed: %s\n"),
635               gpg_strerror (rc));
636   return (!rc && find_up_store_certs_parm.count)? 0 : -1;
637 }
638
639
640
641 /* Locate issuing certificate for CERT. ISSUER is the name of the
642    issuer used as a fallback if the other methods don't work.  If
643    FIND_NEXT is true, the function shall return the next possible
644    issuer.  The certificate itself is not directly returned but a
645    keydb_get_cert on the keyDb context KH will return it.  Returns 0
646    on success, -1 if not found or an error code.  */
647 static int
648 find_up (ctrl_t ctrl, KEYDB_HANDLE kh,
649          ksba_cert_t cert, const char *issuer, int find_next)
650 {
651   ksba_name_t authid;
652   ksba_sexp_t authidno;
653   ksba_sexp_t keyid;
654   int rc = -1;
655
656   if (DBG_X509)
657     log_debug ("looking for parent certificate\n");
658   if (!ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno))
659     {
660       const char *s = ksba_name_enum (authid, 0);
661       if (s && *authidno)
662         {
663           rc = keydb_search_issuer_sn (ctrl, kh, s, authidno);
664           if (rc)
665             keydb_search_reset (kh);
666
667           if (!rc && DBG_X509)
668             log_debug ("  found via authid and sn+issuer\n");
669
670           /* In case of an error, try to get the certificate from the
671              dirmngr.  That is done by trying to put that certifcate
672              into the ephemeral DB and let the code below do the
673              actual retrieve.  Thus there is no error checking.
674              Skipped in find_next mode as usual. */
675           if (rc == -1 && !find_next)
676             find_up_dirmngr (ctrl, kh, authidno, s, 0);
677
678           /* In case of an error try the ephemeral DB.  We can't do
679              that in find_next mode because we can't keep the search
680              state then. */
681           if (rc == -1 && !find_next)
682             {
683               int old = keydb_set_ephemeral (kh, 1);
684               if (!old)
685                 {
686                   rc = keydb_search_issuer_sn (ctrl, kh, s, authidno);
687                   if (rc)
688                     keydb_search_reset (kh);
689
690                   if (!rc && DBG_X509)
691                     log_debug ("  found via authid and sn+issuer (ephem)\n");
692                 }
693               keydb_set_ephemeral (kh, old);
694             }
695           if (rc)
696             rc = -1; /* Need to make sure to have this error code. */
697         }
698
699       if (rc == -1 && keyid && !find_next)
700         {
701           /* Not found by AIK.issuer_sn.  Lets try the AIK.ki
702              instead. Loop over all certificates with that issuer as
703              subject and stop for the one with a matching
704              subjectKeyIdentifier. */
705           /* Fixme: Should we also search in the dirmngr?  */
706           rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
707           if (!rc && DBG_X509)
708             log_debug ("  found via authid and keyid\n");
709           if (rc)
710             {
711               int old = keydb_set_ephemeral (kh, 1);
712               if (!old)
713                 rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
714               if (!rc && DBG_X509)
715                 log_debug ("  found via authid and keyid (ephem)\n");
716               keydb_set_ephemeral (kh, old);
717             }
718           if (rc)
719             rc = -1; /* Need to make sure to have this error code. */
720         }
721
722       /* If we still didn't found it, try to find it via the subject
723          from the dirmngr-cache.  */
724       if (rc == -1 && !find_next)
725         {
726           if (!find_up_dirmngr (ctrl, kh, NULL, issuer, 1))
727             {
728               int old = keydb_set_ephemeral (kh, 1);
729               if (keyid)
730                 rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
731               else
732                 {
733                   keydb_search_reset (kh);
734                   rc = keydb_search_subject (ctrl, kh, issuer);
735                 }
736               keydb_set_ephemeral (kh, old);
737             }
738           if (rc)
739             rc = -1; /* Need to make sure to have this error code. */
740
741           if (!rc && DBG_X509)
742             log_debug ("  found via authid and issuer from dirmngr cache\n");
743         }
744
745       /* If we still didn't found it, try an external lookup.  */
746       if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
747         {
748           rc = find_up_external (ctrl, kh, issuer, keyid);
749           if (!rc && DBG_X509)
750             log_debug ("  found via authid and external lookup\n");
751         }
752
753
754       /* Print a note so that the user does not feel too helpless when
755          an issuer certificate was found and gpgsm prints BAD
756          signature because it is not the correct one. */
757       if (rc == -1 && opt.quiet)
758         ;
759       else if (rc == -1)
760         {
761           log_info ("%sissuer certificate ", find_next?"next ":"");
762           if (keyid)
763             {
764               log_printf ("{");
765               gpgsm_dump_serial (keyid);
766               log_printf ("} ");
767             }
768           if (authidno)
769             {
770               log_printf ("(#");
771               gpgsm_dump_serial (authidno);
772               log_printf ("/");
773               gpgsm_dump_string (s);
774               log_printf (") ");
775             }
776           log_printf ("not found using authorityKeyIdentifier\n");
777         }
778       else if (rc)
779         log_error ("failed to find authorityKeyIdentifier: rc=%d\n", rc);
780       xfree (keyid);
781       ksba_name_release (authid);
782       xfree (authidno);
783     }
784
785   if (rc) /* Not found via authorithyKeyIdentifier, try regular issuer name. */
786     rc = keydb_search_subject (ctrl, kh, issuer);
787   if (rc == -1 && !find_next)
788     {
789       int old;
790
791       /* Also try to get it from the Dirmngr cache.  The function
792          merely puts it into the ephemeral database.  */
793       find_up_dirmngr (ctrl, kh, NULL, issuer, 0);
794
795       /* Not found, let us see whether we have one in the ephemeral key DB. */
796       old = keydb_set_ephemeral (kh, 1);
797       if (!old)
798         {
799           keydb_search_reset (kh);
800           rc = keydb_search_subject (ctrl, kh, issuer);
801         }
802       keydb_set_ephemeral (kh, old);
803
804       if (!rc && DBG_X509)
805         log_debug ("  found via issuer\n");
806     }
807
808   /* Still not found.  If enabled, try an external lookup.  */
809   if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
810     {
811       rc = find_up_external (ctrl, kh, issuer, NULL);
812       if (!rc && DBG_X509)
813         log_debug ("  found via issuer and external lookup\n");
814     }
815
816   return rc;
817 }
818
819
820 /* Return the next certificate up in the chain starting at START.
821    Returns -1 when there are no more certificates. */
822 int
823 gpgsm_walk_cert_chain (ctrl_t ctrl, ksba_cert_t start, ksba_cert_t *r_next)
824 {
825   int rc = 0;
826   char *issuer = NULL;
827   char *subject = NULL;
828   KEYDB_HANDLE kh = keydb_new ();
829
830   *r_next = NULL;
831   if (!kh)
832     {
833       log_error (_("failed to allocate keyDB handle\n"));
834       rc = gpg_error (GPG_ERR_GENERAL);
835       goto leave;
836     }
837
838   issuer = ksba_cert_get_issuer (start, 0);
839   subject = ksba_cert_get_subject (start, 0);
840   if (!issuer)
841     {
842       log_error ("no issuer found in certificate\n");
843       rc = gpg_error (GPG_ERR_BAD_CERT);
844       goto leave;
845     }
846   if (!subject)
847     {
848       log_error ("no subject found in certificate\n");
849       rc = gpg_error (GPG_ERR_BAD_CERT);
850       goto leave;
851     }
852
853   if (is_root_cert (start, issuer, subject))
854     {
855       rc = -1; /* we are at the root */
856       goto leave;
857     }
858
859   rc = find_up (ctrl, kh, start, issuer, 0);
860   if (rc)
861     {
862       /* It is quite common not to have a certificate, so better don't
863          print an error here.  */
864       if (rc != -1 && opt.verbose > 1)
865         log_error ("failed to find issuer's certificate: rc=%d\n", rc);
866       rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
867       goto leave;
868     }
869
870   rc = keydb_get_cert (kh, r_next);
871   if (rc)
872     {
873       log_error ("keydb_get_cert() failed: rc=%d\n", rc);
874       rc = gpg_error (GPG_ERR_GENERAL);
875     }
876
877  leave:
878   xfree (issuer);
879   xfree (subject);
880   keydb_release (kh);
881   return rc;
882 }
883
884
885 /* Helper for gpgsm_is_root_cert.  This one is used if the subject and
886    issuer DNs are already known.  */
887 static int
888 is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn)
889 {
890   gpg_error_t err;
891   int result = 0;
892   ksba_sexp_t serialno;
893   ksba_sexp_t ak_keyid;
894   ksba_name_t ak_name;
895   ksba_sexp_t ak_sn;
896   const char *ak_name_str;
897   ksba_sexp_t subj_keyid = NULL;
898
899   if (!issuerdn || !subjectdn)
900     return 0;  /* No.  */
901
902   if (strcmp (issuerdn, subjectdn))
903     return 0;  /* No.  */
904
905   err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn);
906   if (err)
907     {
908       if (gpg_err_code (err) == GPG_ERR_NO_DATA)
909         return 1; /* Yes. Without a authorityKeyIdentifier this needs
910                      to be the Root certifcate (our trust anchor).  */
911       log_error ("error getting authorityKeyIdentifier: %s\n",
912                  gpg_strerror (err));
913       return 0; /* Well, it is broken anyway.  Return No. */
914     }
915
916   serialno = ksba_cert_get_serial (cert);
917   if (!serialno)
918     {
919       log_error ("error getting serialno: %s\n", gpg_strerror (err));
920       goto leave;
921     }
922
923   /* Check whether the auth name's matches the issuer name+sn.  If
924      that is the case this is a root certificate.  */
925   ak_name_str = ksba_name_enum (ak_name, 0);
926   if (ak_name_str
927       && !strcmp (ak_name_str, issuerdn)
928       && !cmp_simple_canon_sexp (ak_sn, serialno))
929     {
930       result = 1;  /* Right, CERT is self-signed.  */
931       goto leave;
932     }
933
934   /* Similar for the ak_keyid. */
935   if (ak_keyid && !ksba_cert_get_subj_key_id (cert, NULL, &subj_keyid)
936       && !cmp_simple_canon_sexp (ak_keyid, subj_keyid))
937     {
938       result = 1;  /* Right, CERT is self-signed.  */
939       goto leave;
940     }
941
942
943  leave:
944   ksba_free (subj_keyid);
945   ksba_free (ak_keyid);
946   ksba_name_release (ak_name);
947   ksba_free (ak_sn);
948   ksba_free (serialno);
949   return result;
950 }
951
952
953
954 /* Check whether the CERT is a root certificate.  Returns True if this
955    is the case. */
956 int
957 gpgsm_is_root_cert (ksba_cert_t cert)
958 {
959   char *issuer;
960   char *subject;
961   int yes;
962
963   issuer = ksba_cert_get_issuer (cert, 0);
964   subject = ksba_cert_get_subject (cert, 0);
965   yes = is_root_cert (cert, issuer, subject);
966   xfree (issuer);
967   xfree (subject);
968   return yes;
969 }
970
971
972 /* This is a helper for gpgsm_validate_chain. */
973 static gpg_error_t
974 is_cert_still_valid (ctrl_t ctrl, int force_ocsp, int lm, estream_t fp,
975                      ksba_cert_t subject_cert, ksba_cert_t issuer_cert,
976                      int *any_revoked, int *any_no_crl, int *any_crl_too_old)
977 {
978   gpg_error_t err;
979
980   if (ctrl->offline || (opt.no_crl_check && !ctrl->use_ocsp))
981     {
982       audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK,
983                     gpg_error (GPG_ERR_NOT_ENABLED));
984       return 0;
985     }
986
987   err = gpgsm_dirmngr_isvalid (ctrl,
988                                subject_cert, issuer_cert,
989                                force_ocsp? 2 : !!ctrl->use_ocsp);
990   audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK, err);
991
992   if (err)
993     {
994       if (!lm)
995         gpgsm_cert_log_name (NULL, subject_cert);
996       switch (gpg_err_code (err))
997         {
998         case GPG_ERR_CERT_REVOKED:
999           do_list (1, lm, fp, _("certificate has been revoked"));
1000           *any_revoked = 1;
1001           /* Store that in the keybox so that key listings are able to
1002              return the revoked flag.  We don't care about error,
1003              though. */
1004           keydb_set_cert_flags (ctrl, subject_cert, 1, KEYBOX_FLAG_VALIDITY, 0,
1005                                 ~0, VALIDITY_REVOKED);
1006           break;
1007
1008         case GPG_ERR_NO_CRL_KNOWN:
1009           do_list (1, lm, fp, _("no CRL found for certificate"));
1010           *any_no_crl = 1;
1011           break;
1012
1013         case GPG_ERR_NO_DATA:
1014           do_list (1, lm, fp, _("the status of the certificate is unknown"));
1015           *any_no_crl = 1;
1016           break;
1017
1018         case GPG_ERR_CRL_TOO_OLD:
1019           do_list (1, lm, fp, _("the available CRL is too old"));
1020           if (!lm)
1021             log_info (_("please make sure that the "
1022                         "\"dirmngr\" is properly installed\n"));
1023           *any_crl_too_old = 1;
1024           break;
1025
1026         default:
1027           do_list (1, lm, fp, _("checking the CRL failed: %s"),
1028                    gpg_strerror (err));
1029           return err;
1030         }
1031     }
1032   return 0;
1033 }
1034
1035
1036 /* Helper for gpgsm_validate_chain to check the validity period of
1037    SUBJECT_CERT.  The caller needs to pass EXPTIME which will be
1038    updated to the nearest expiration time seen.  A DEPTH of 0 indicates
1039    the target certifciate, -1 the final root certificate and other
1040    values intermediate certificates. */
1041 static gpg_error_t
1042 check_validity_period (ksba_isotime_t current_time,
1043                        ksba_cert_t subject_cert,
1044                        ksba_isotime_t exptime,
1045                        int listmode, estream_t listfp, int depth)
1046 {
1047   gpg_error_t err;
1048   ksba_isotime_t not_before, not_after;
1049
1050   err = ksba_cert_get_validity (subject_cert, 0, not_before);
1051   if (!err)
1052     err = ksba_cert_get_validity (subject_cert, 1, not_after);
1053   if (err)
1054     {
1055       do_list (1, listmode, listfp,
1056                _("certificate with invalid validity: %s"), gpg_strerror (err));
1057       return gpg_error (GPG_ERR_BAD_CERT);
1058     }
1059
1060   if (*not_after)
1061     {
1062       if (!*exptime)
1063         gnupg_copy_time (exptime, not_after);
1064       else if (strcmp (not_after, exptime) < 0 )
1065         gnupg_copy_time (exptime, not_after);
1066     }
1067
1068   if (*not_before && strcmp (current_time, not_before) < 0 )
1069     {
1070       do_list (1, listmode, listfp,
1071                depth ==  0 ? _("certificate not yet valid") :
1072                depth == -1 ? _("root certificate not yet valid") :
1073                /* other */   _("intermediate certificate not yet valid"));
1074       if (!listmode)
1075         {
1076           log_info ("  (valid from ");
1077           dump_isotime (not_before);
1078           log_printf (")\n");
1079         }
1080       return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
1081     }
1082
1083   if (*not_after && strcmp (current_time, not_after) > 0 )
1084     {
1085       do_list (opt.ignore_expiration?0:1, listmode, listfp,
1086                depth == 0  ? _("certificate has expired") :
1087                depth == -1 ? _("root certificate has expired") :
1088                /* other  */  _("intermediate certificate has expired"));
1089       if (!listmode)
1090         {
1091           log_info ("  (expired at ");
1092           dump_isotime (not_after);
1093           log_printf (")\n");
1094         }
1095       if (opt.ignore_expiration)
1096         log_info ("WARNING: ignoring expiration\n");
1097       else
1098         return gpg_error (GPG_ERR_CERT_EXPIRED);
1099     }
1100
1101   return 0;
1102 }
1103
1104 /* This is a variant of check_validity_period used with the chain
1105    model.  The dextra contraint here is that notBefore and notAfter
1106    must exists and if the additional argument CHECK_TIME is given this
1107    time is used to check the validity period of SUBJECT_CERT.  */
1108 static gpg_error_t
1109 check_validity_period_cm (ksba_isotime_t current_time,
1110                           ksba_isotime_t check_time,
1111                           ksba_cert_t subject_cert,
1112                           ksba_isotime_t exptime,
1113                           int listmode, estream_t listfp, int depth)
1114 {
1115   gpg_error_t err;
1116   ksba_isotime_t not_before, not_after;
1117
1118   err = ksba_cert_get_validity (subject_cert, 0, not_before);
1119   if (!err)
1120     err = ksba_cert_get_validity (subject_cert, 1, not_after);
1121   if (err)
1122     {
1123       do_list (1, listmode, listfp,
1124                _("certificate with invalid validity: %s"), gpg_strerror (err));
1125       return gpg_error (GPG_ERR_BAD_CERT);
1126     }
1127   if (!*not_before || !*not_after)
1128     {
1129       do_list (1, listmode, listfp,
1130                _("required certificate attributes missing: %s%s%s"),
1131                !*not_before? "notBefore":"",
1132                (!*not_before && !*not_after)? ", ":"",
1133                !*not_before? "notAfter":"");
1134       return gpg_error (GPG_ERR_BAD_CERT);
1135     }
1136   if (strcmp (not_before, not_after) > 0 )
1137     {
1138       do_list (1, listmode, listfp,
1139                _("certificate with invalid validity"));
1140       log_info ("  (valid from ");
1141       dump_isotime (not_before);
1142       log_printf (" expired at ");
1143       dump_isotime (not_after);
1144       log_printf (")\n");
1145       return gpg_error (GPG_ERR_BAD_CERT);
1146     }
1147
1148   if (!*exptime)
1149     gnupg_copy_time (exptime, not_after);
1150   else if (strcmp (not_after, exptime) < 0 )
1151     gnupg_copy_time (exptime, not_after);
1152
1153   if (strcmp (current_time, not_before) < 0 )
1154     {
1155       do_list (1, listmode, listfp,
1156                depth ==  0 ? _("certificate not yet valid") :
1157                depth == -1 ? _("root certificate not yet valid") :
1158                /* other */   _("intermediate certificate not yet valid"));
1159       if (!listmode)
1160         {
1161           log_info ("  (valid from ");
1162           dump_isotime (not_before);
1163           log_printf (")\n");
1164         }
1165       return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
1166     }
1167
1168   if (*check_time
1169       && (strcmp (check_time, not_before) < 0
1170           || strcmp (check_time, not_after) > 0))
1171     {
1172       /* Note that we don't need a case for the root certificate
1173          because its own consitency has already been checked.  */
1174       do_list(opt.ignore_expiration?0:1, listmode, listfp,
1175               depth == 0 ?
1176               _("signature not created during lifetime of certificate") :
1177               depth == 1 ?
1178               _("certificate not created during lifetime of issuer") :
1179               _("intermediate certificate not created during lifetime "
1180                 "of issuer"));
1181       if (!listmode)
1182         {
1183           log_info (depth== 0? _("  (  signature created at ") :
1184                     /* */      _("  (certificate created at ") );
1185           dump_isotime (check_time);
1186           log_printf (")\n");
1187           log_info (depth==0? _("  (certificate valid from ") :
1188                     /* */     _("  (     issuer valid from ") );
1189           dump_isotime (not_before);
1190           log_info (" to ");
1191           dump_isotime (not_after);
1192           log_printf (")\n");
1193         }
1194       if (opt.ignore_expiration)
1195         log_info ("WARNING: ignoring expiration\n");
1196       else
1197         return gpg_error (GPG_ERR_CERT_EXPIRED);
1198     }
1199
1200   return 0;
1201 }
1202
1203
1204
1205 /* Ask the user whether he wants to mark the certificate CERT trusted.
1206    Returns true if the CERT is the trusted.  We also check whether the
1207    agent is at all enabled to allow marktrusted and don't call it in
1208    this session again if it is not.  */
1209 static int
1210 ask_marktrusted (ctrl_t ctrl, ksba_cert_t cert, int listmode)
1211 {
1212   static int no_more_questions;
1213   int rc;
1214   char *fpr;
1215   int success = 0;
1216
1217   fpr = gpgsm_get_fingerprint_string (cert, GCRY_MD_SHA1);
1218   log_info (_("fingerprint=%s\n"), fpr? fpr : "?");
1219   xfree (fpr);
1220
1221   if (no_more_questions)
1222     rc = gpg_error (GPG_ERR_NOT_SUPPORTED);
1223   else
1224     rc = gpgsm_agent_marktrusted (ctrl, cert);
1225   if (!rc)
1226     {
1227       log_info (_("root certificate has now been marked as trusted\n"));
1228       success = 1;
1229     }
1230   else if (!listmode)
1231     {
1232       gpgsm_dump_cert ("issuer", cert);
1233       log_info ("after checking the fingerprint, you may want "
1234                 "to add it manually to the list of trusted certificates.\n");
1235     }
1236
1237   if (gpg_err_code (rc) == GPG_ERR_NOT_SUPPORTED)
1238     {
1239       if (!no_more_questions)
1240         log_info (_("interactive marking as trusted "
1241                     "not enabled in gpg-agent\n"));
1242       no_more_questions = 1;
1243     }
1244   else if (gpg_err_code (rc) == GPG_ERR_CANCELED)
1245     {
1246       log_info (_("interactive marking as trusted "
1247                   "disabled for this session\n"));
1248       no_more_questions = 1;
1249     }
1250   else
1251     set_already_asked_marktrusted (cert);
1252
1253   return success;
1254 }
1255
1256
1257
1258 \f
1259 /* Validate a chain and optionally return the nearest expiration time
1260    in R_EXPTIME. With LISTMODE set to 1 a special listmode is
1261    activated where only information about the certificate is printed
1262    to LISTFP and no output is send to the usual log stream.  If
1263    CHECKTIME_ARG is set, it is used only in the chain model instead of the
1264    current time.
1265
1266    Defined flag bits
1267
1268    VALIDATE_FLAG_NO_DIRMNGR  - Do not do any dirmngr isvalid checks.
1269    VALIDATE_FLAG_CHAIN_MODEL - Check according to chain model.
1270    VALIDATE_FLAG_STEED       - Check according to the STEED model.
1271 */
1272 static int
1273 do_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime_arg,
1274                    ksba_isotime_t r_exptime,
1275                    int listmode, estream_t listfp, unsigned int flags,
1276                    struct rootca_flags_s *rootca_flags)
1277 {
1278   int rc = 0, depth, maxdepth;
1279   char *issuer = NULL;
1280   char *subject = NULL;
1281   KEYDB_HANDLE kh = NULL;
1282   ksba_cert_t subject_cert = NULL, issuer_cert = NULL;
1283   ksba_isotime_t current_time;
1284   ksba_isotime_t check_time;
1285   ksba_isotime_t exptime;
1286   int any_expired = 0;
1287   int any_revoked = 0;
1288   int any_no_crl = 0;
1289   int any_crl_too_old = 0;
1290   int any_no_policy_match = 0;
1291   int is_qualified = -1; /* Indicates whether the certificate stems
1292                             from a qualified root certificate.
1293                             -1 = unknown, 0 = no, 1 = yes. */
1294   chain_item_t chain = NULL; /* A list of all certificates in the chain.  */
1295
1296
1297   gnupg_get_isotime (current_time);
1298
1299   if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1300     {
1301       if (!strcmp (checktime_arg, "19700101T000000"))
1302         {
1303           do_list (1, listmode, listfp,
1304                    _("WARNING: creation time of signature not known - "
1305                      "assuming current time"));
1306           gnupg_copy_time (check_time, current_time);
1307         }
1308       else
1309         gnupg_copy_time (check_time, checktime_arg);
1310     }
1311   else
1312     *check_time = 0;
1313
1314   if (r_exptime)
1315     *r_exptime = 0;
1316   *exptime = 0;
1317
1318   if (opt.no_chain_validation && !listmode)
1319     {
1320       log_info ("WARNING: bypassing certificate chain validation\n");
1321       return 0;
1322     }
1323
1324   kh = keydb_new ();
1325   if (!kh)
1326     {
1327       log_error (_("failed to allocate keyDB handle\n"));
1328       rc = gpg_error (GPG_ERR_GENERAL);
1329       goto leave;
1330     }
1331
1332   if (DBG_X509 && !listmode)
1333     gpgsm_dump_cert ("target", cert);
1334
1335   subject_cert = cert;
1336   ksba_cert_ref (subject_cert);
1337   maxdepth = 50;
1338   depth = 0;
1339
1340   for (;;)
1341     {
1342       int is_root;
1343       gpg_error_t istrusted_rc = -1;
1344
1345       /* Put the certificate on our list.  */
1346       {
1347         chain_item_t ci;
1348
1349         ci = xtrycalloc (1, sizeof *ci);
1350         if (!ci)
1351           {
1352             rc = gpg_error_from_syserror ();
1353             goto leave;
1354           }
1355         ksba_cert_ref (subject_cert);
1356         ci->cert = subject_cert;
1357         ci->next = chain;
1358         chain = ci;
1359       }
1360
1361       xfree (issuer);
1362       xfree (subject);
1363       issuer = ksba_cert_get_issuer (subject_cert, 0);
1364       subject = ksba_cert_get_subject (subject_cert, 0);
1365
1366       if (!issuer)
1367         {
1368           do_list (1, listmode, listfp,  _("no issuer found in certificate"));
1369           rc = gpg_error (GPG_ERR_BAD_CERT);
1370           goto leave;
1371         }
1372
1373
1374       /* Is this a self-issued certificate (i.e. the root certificate)?  */
1375       is_root = is_root_cert (subject_cert, issuer, subject);
1376       if (is_root)
1377         {
1378           chain->is_root = 1;
1379           /* Check early whether the certificate is listed as trusted.
1380              We used to do this only later but changed it to call the
1381              check right here so that we can access special flags
1382              associated with that specific root certificate.  */
1383           if (gpgsm_cert_has_well_known_private_key (subject_cert))
1384             {
1385               memset (rootca_flags, 0, sizeof *rootca_flags);
1386               istrusted_rc = ((flags & VALIDATE_FLAG_STEED)
1387                               ? 0 : gpg_error (GPG_ERR_NOT_TRUSTED));
1388             }
1389           else
1390             istrusted_rc = gpgsm_agent_istrusted (ctrl, subject_cert, NULL,
1391                                                   rootca_flags);
1392           audit_log_cert (ctrl->audit, AUDIT_ROOT_TRUSTED,
1393                           subject_cert, istrusted_rc);
1394           /* If the chain model extended attribute is used, make sure
1395              that our chain model flag is set. */
1396           if (!(flags & VALIDATE_FLAG_STEED)
1397               && has_validation_model_chain (subject_cert, listmode, listfp))
1398             rootca_flags->chain_model = 1;
1399         }
1400
1401
1402       /* Check the validity period. */
1403       if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1404         rc = check_validity_period_cm (current_time, check_time, subject_cert,
1405                                        exptime, listmode, listfp,
1406                                        (depth && is_root)? -1: depth);
1407       else
1408         rc = check_validity_period (current_time, subject_cert,
1409                                     exptime, listmode, listfp,
1410                                     (depth && is_root)? -1: depth);
1411       if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED)
1412         any_expired = 1;
1413       else if (rc)
1414         goto leave;
1415
1416
1417       /* Assert that we understand all critical extensions. */
1418       rc = unknown_criticals (subject_cert, listmode, listfp);
1419       if (rc)
1420         goto leave;
1421
1422       /* Do a policy check. */
1423       if (!opt.no_policy_check)
1424         {
1425           rc = check_cert_policy (subject_cert, listmode, listfp);
1426           if (gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH)
1427             {
1428               any_no_policy_match = 1;
1429               rc = 1;  /* Be on the safe side and set RC.  */
1430             }
1431           else if (rc)
1432             goto leave;
1433         }
1434
1435
1436       /* If this is the root certificate we are at the end of the chain.  */
1437       if (is_root)
1438         {
1439           if (!istrusted_rc)
1440             ; /* No need to check the certificate for a trusted one. */
1441           else if (gpgsm_check_cert_sig (subject_cert, subject_cert) )
1442             {
1443               /* We only check the signature if the certificate is not
1444                  trusted for better diagnostics. */
1445               do_list (1, listmode, listfp,
1446                        _("self-signed certificate has a BAD signature"));
1447               if (DBG_X509)
1448                 {
1449                   gpgsm_dump_cert ("self-signing cert", subject_cert);
1450                 }
1451               rc = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN
1452                                    : GPG_ERR_BAD_CERT);
1453               goto leave;
1454             }
1455           if (!rootca_flags->relax)
1456             {
1457               rc = allowed_ca (ctrl, subject_cert, NULL, listmode, listfp);
1458               if (rc)
1459                 goto leave;
1460             }
1461
1462
1463           /* Set the flag for qualified signatures.  This flag is
1464              deduced from a list of root certificates allowed for
1465              qualified signatures. */
1466           if (is_qualified == -1 && !(flags & VALIDATE_FLAG_STEED))
1467             {
1468               gpg_error_t err;
1469               size_t buflen;
1470               char buf[1];
1471
1472               if (!ksba_cert_get_user_data (cert, "is_qualified",
1473                                             &buf, sizeof (buf),
1474                                             &buflen) && buflen)
1475                 {
1476                   /* We already checked this for this certificate,
1477                      thus we simply take it from the user data. */
1478                   is_qualified = !!*buf;
1479                 }
1480               else
1481                 {
1482                   /* Need to consult the list of root certificates for
1483                      qualified signatures. */
1484                   err = gpgsm_is_in_qualified_list (ctrl, subject_cert, NULL);
1485                   if (!err)
1486                     is_qualified = 1;
1487                   else if ( gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1488                     is_qualified = 0;
1489                   else
1490                     log_error ("checking the list of qualified "
1491                                "root certificates failed: %s\n",
1492                                gpg_strerror (err));
1493                   if ( is_qualified != -1 )
1494                     {
1495                       /* Cache the result but don't care too much
1496                          about an error. */
1497                       buf[0] = !!is_qualified;
1498                       err = ksba_cert_set_user_data (subject_cert,
1499                                                      "is_qualified", buf, 1);
1500                       if (err)
1501                         log_error ("set_user_data(is_qualified) failed: %s\n",
1502                                    gpg_strerror (err));
1503                     }
1504                 }
1505             }
1506
1507
1508           /* Act on the check for a trusted root certificates. */
1509           rc = istrusted_rc;
1510           if (!rc)
1511             ;
1512           else if (gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
1513             {
1514               do_list (0, listmode, listfp,
1515                        _("root certificate is not marked trusted"));
1516               /* If we already figured out that the certificate is
1517                  expired it does not make much sense to ask the user
1518                  whether we wants to trust the root certificate.  We
1519                  should do this only if the certificate under question
1520                  will then be usable.  If the certificate has a well
1521                  known private key asking the user does not make any
1522                  sense.  */
1523               if ( !any_expired
1524                    && !gpgsm_cert_has_well_known_private_key (subject_cert)
1525                    && (!listmode || !already_asked_marktrusted (subject_cert))
1526                    && ask_marktrusted (ctrl, subject_cert, listmode) )
1527                 rc = 0;
1528             }
1529           else
1530             {
1531               log_error (_("checking the trust list failed: %s\n"),
1532                          gpg_strerror (rc));
1533             }
1534
1535           if (rc)
1536             goto leave;
1537
1538           /* Check for revocations etc. */
1539           if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
1540             ;
1541           else if ((flags & VALIDATE_FLAG_STEED))
1542             ; /* Fixme: check revocations via DNS.  */
1543           else if (opt.no_trusted_cert_crl_check || rootca_flags->relax)
1544             ;
1545           else
1546             rc = is_cert_still_valid (ctrl,
1547                                       (flags & VALIDATE_FLAG_CHAIN_MODEL),
1548                                       listmode, listfp,
1549                                       subject_cert, subject_cert,
1550                                       &any_revoked, &any_no_crl,
1551                                       &any_crl_too_old);
1552           if (rc)
1553             goto leave;
1554
1555           break;  /* Okay: a self-signed certicate is an end-point. */
1556         } /* End is_root.  */
1557
1558
1559       /* Take care that the chain does not get too long. */
1560       if ((depth+1) > maxdepth)
1561         {
1562           do_list (1, listmode, listfp, _("certificate chain too long\n"));
1563           rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1564           goto leave;
1565         }
1566
1567       /* Find the next cert up the tree. */
1568       keydb_search_reset (kh);
1569       rc = find_up (ctrl, kh, subject_cert, issuer, 0);
1570       if (rc)
1571         {
1572           if (rc == -1)
1573             {
1574               do_list (0, listmode, listfp, _("issuer certificate not found"));
1575               if (!listmode)
1576                 {
1577                   log_info ("issuer certificate: #/");
1578                   gpgsm_dump_string (issuer);
1579                   log_printf ("\n");
1580                 }
1581             }
1582           else
1583             log_error ("failed to find issuer's certificate: rc=%d\n", rc);
1584           rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
1585           goto leave;
1586         }
1587
1588       ksba_cert_release (issuer_cert); issuer_cert = NULL;
1589       rc = keydb_get_cert (kh, &issuer_cert);
1590       if (rc)
1591         {
1592           log_error ("keydb_get_cert() failed: rc=%d\n", rc);
1593           rc = gpg_error (GPG_ERR_GENERAL);
1594           goto leave;
1595         }
1596
1597     try_another_cert:
1598       if (DBG_X509)
1599         {
1600           log_debug ("got issuer's certificate:\n");
1601           gpgsm_dump_cert ("issuer", issuer_cert);
1602         }
1603
1604       rc = gpgsm_check_cert_sig (issuer_cert, subject_cert);
1605       if (rc)
1606         {
1607           do_list (0, listmode, listfp, _("certificate has a BAD signature"));
1608           if (DBG_X509)
1609             {
1610               gpgsm_dump_cert ("signing issuer", issuer_cert);
1611               gpgsm_dump_cert ("signed subject", subject_cert);
1612             }
1613           if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
1614             {
1615               /* We now try to find other issuer certificates which
1616                  might have been used.  This is required because some
1617                  CAs are reusing the issuer and subject DN for new
1618                  root certificates. */
1619               /* FIXME: Do this only if we don't have an
1620                  AKI.keyIdentifier */
1621               rc = find_up (ctrl, kh, subject_cert, issuer, 1);
1622               if (!rc)
1623                 {
1624                   ksba_cert_t tmp_cert;
1625
1626                   rc = keydb_get_cert (kh, &tmp_cert);
1627                   if (rc || !compare_certs (issuer_cert, tmp_cert))
1628                     {
1629                       /* The find next did not work or returned an
1630                          identical certificate.  We better stop here
1631                          to avoid infinite checks. */
1632                       /* No need to set RC because it is not used:
1633                          rc = gpg_error (GPG_ERR_BAD_SIGNATURE);  */
1634                       ksba_cert_release (tmp_cert);
1635                     }
1636                   else
1637                     {
1638                       do_list (0, listmode, listfp,
1639                                _("found another possible matching "
1640                                  "CA certificate - trying again"));
1641                       ksba_cert_release (issuer_cert);
1642                       issuer_cert = tmp_cert;
1643                       goto try_another_cert;
1644                     }
1645                 }
1646             }
1647
1648           /* We give a more descriptive error code than the one
1649              returned from the signature checking. */
1650           rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1651           goto leave;
1652         }
1653
1654       is_root = gpgsm_is_root_cert (issuer_cert);
1655       istrusted_rc = -1;
1656
1657
1658       /* Check that a CA is allowed to issue certificates. */
1659       {
1660         int chainlen;
1661
1662         rc = allowed_ca (ctrl, issuer_cert, &chainlen, listmode, listfp);
1663         if (rc)
1664           {
1665             /* Not allowed.  Check whether this is a trusted root
1666                certificate and whether we allow special exceptions.
1667                We could carry the result of the test over to the
1668                regular root check at the top of the loop but for
1669                clarity we won't do that.  Given that the majority of
1670                certificates carry proper BasicContraints our way of
1671                overriding an error in the way is justified for
1672                performance reasons. */
1673             if (is_root)
1674               {
1675                 if (gpgsm_cert_has_well_known_private_key (issuer_cert))
1676                   {
1677                     memset (rootca_flags, 0, sizeof *rootca_flags);
1678                     istrusted_rc = ((flags & VALIDATE_FLAG_STEED)
1679                                     ? 0 : gpg_error (GPG_ERR_NOT_TRUSTED));
1680                   }
1681                 else
1682                   istrusted_rc = gpgsm_agent_istrusted
1683                     (ctrl, issuer_cert, NULL, rootca_flags);
1684
1685                 if (!istrusted_rc && rootca_flags->relax)
1686                   {
1687                     /* Ignore the error due to the relax flag.  */
1688                     rc = 0;
1689                     chainlen = -1;
1690                   }
1691               }
1692           }
1693         if (rc)
1694           goto leave;
1695         if (chainlen >= 0 && depth > chainlen)
1696           {
1697             do_list (1, listmode, listfp,
1698                      _("certificate chain longer than allowed by CA (%d)"),
1699                      chainlen);
1700             rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1701             goto leave;
1702           }
1703       }
1704
1705       /* Is the certificate allowed to sign other certificates. */
1706       if (!listmode)
1707         {
1708           rc = gpgsm_cert_use_cert_p (issuer_cert);
1709           if (rc)
1710             {
1711               char numbuf[50];
1712               sprintf (numbuf, "%d", rc);
1713               gpgsm_status2 (ctrl, STATUS_ERROR, "certcert.issuer.keyusage",
1714                              numbuf, NULL);
1715               goto leave;
1716             }
1717         }
1718
1719       /* Check for revocations etc.  Note that for a root certificate
1720          this test is done a second time later. This should eventually
1721          be fixed. */
1722       if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
1723         rc = 0;
1724       else if ((flags & VALIDATE_FLAG_STEED))
1725         rc = 0; /* Fixme: XXX */
1726       else if (is_root && (opt.no_trusted_cert_crl_check
1727                            || (!istrusted_rc && rootca_flags->relax)))
1728         rc = 0;
1729       else
1730         rc = is_cert_still_valid (ctrl,
1731                                   (flags & VALIDATE_FLAG_CHAIN_MODEL),
1732                                   listmode, listfp,
1733                                   subject_cert, issuer_cert,
1734                                   &any_revoked, &any_no_crl, &any_crl_too_old);
1735       if (rc)
1736         goto leave;
1737
1738
1739       if (opt.verbose && !listmode)
1740         log_info (depth == 0 ? _("certificate is good\n") :
1741                   !is_root   ? _("intermediate certificate is good\n") :
1742                   /* other */  _("root certificate is good\n"));
1743
1744       /* Under the chain model the next check time is the creation
1745          time of the subject certificate.  */
1746       if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1747         {
1748           rc = ksba_cert_get_validity (subject_cert, 0, check_time);
1749           if (rc)
1750             {
1751               /* That will never happen as we have already checked
1752                  this above.  */
1753               BUG ();
1754             }
1755         }
1756
1757       /* For the next round the current issuer becomes the new subject.  */
1758       keydb_search_reset (kh);
1759       ksba_cert_release (subject_cert);
1760       subject_cert = issuer_cert;
1761       issuer_cert = NULL;
1762       depth++;
1763     } /* End chain traversal. */
1764
1765   if (!listmode && !opt.quiet)
1766     {
1767       if (opt.no_policy_check)
1768         log_info ("policies not checked due to %s option\n",
1769                   "--disable-policy-checks");
1770       if (ctrl->offline || (opt.no_crl_check && !ctrl->use_ocsp))
1771         log_info ("CRLs not checked due to %s option\n",
1772                   ctrl->offline ? "offline" : "--disable-crl-checks");
1773     }
1774
1775   if (!rc)
1776     { /* If we encountered an error somewhere during the checks, set
1777          the error code to the most critical one */
1778       if (any_revoked)
1779         rc = gpg_error (GPG_ERR_CERT_REVOKED);
1780       else if (any_expired)
1781         rc = gpg_error (GPG_ERR_CERT_EXPIRED);
1782       else if (any_no_crl)
1783         rc = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1784       else if (any_crl_too_old)
1785         rc = gpg_error (GPG_ERR_CRL_TOO_OLD);
1786       else if (any_no_policy_match)
1787         rc = gpg_error (GPG_ERR_NO_POLICY_MATCH);
1788     }
1789
1790  leave:
1791   /* If we have traversed a complete chain up to the root we will
1792      reset the ephemeral flag for all these certificates.  This is done
1793      regardless of any error because those errors may only be
1794      transient. */
1795   if (chain && chain->is_root)
1796     {
1797       gpg_error_t err;
1798       chain_item_t ci;
1799
1800       for (ci = chain; ci; ci = ci->next)
1801         {
1802           /* Note that it is possible for the last certificate in the
1803              chain (i.e. our target certificate) that it has not yet
1804              been stored in the keybox and thus the flag can't be set.
1805              We ignore this error because it will later be stored
1806              anyway.  */
1807           err = keydb_set_cert_flags (ctrl, ci->cert, 1, KEYBOX_FLAG_BLOB, 0,
1808                                       KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
1809           if (!ci->next && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1810             ;
1811           else if (err)
1812             log_error ("clearing ephemeral flag failed: %s\n",
1813                        gpg_strerror (err));
1814         }
1815     }
1816
1817   /* If we have figured something about the qualified signature
1818      capability of the certificate under question, store the result as
1819      user data in all certificates of the chain.  We do this even if the
1820      validation itself failed.  */
1821   if (is_qualified != -1 && !(flags & VALIDATE_FLAG_STEED))
1822     {
1823       gpg_error_t err;
1824       chain_item_t ci;
1825       char buf[1];
1826
1827       buf[0] = !!is_qualified;
1828
1829       for (ci = chain; ci; ci = ci->next)
1830         {
1831           err = ksba_cert_set_user_data (ci->cert, "is_qualified", buf, 1);
1832           if (err)
1833             {
1834               log_error ("set_user_data(is_qualified) failed: %s\n",
1835                          gpg_strerror (err));
1836               if (!rc)
1837                 rc = err;
1838             }
1839         }
1840     }
1841
1842   /* If auditing has been enabled, record what is in the chain.  */
1843   if (ctrl->audit)
1844     {
1845       chain_item_t ci;
1846
1847       audit_log (ctrl->audit, AUDIT_CHAIN_BEGIN);
1848       for (ci = chain; ci; ci = ci->next)
1849         {
1850           audit_log_cert (ctrl->audit,
1851                           ci->is_root? AUDIT_CHAIN_ROOTCERT : AUDIT_CHAIN_CERT,
1852                           ci->cert, 0);
1853         }
1854       audit_log (ctrl->audit, AUDIT_CHAIN_END);
1855     }
1856
1857   if (r_exptime)
1858     gnupg_copy_time (r_exptime, exptime);
1859   xfree (issuer);
1860   xfree (subject);
1861   keydb_release (kh);
1862   while (chain)
1863     {
1864       chain_item_t ci_next = chain->next;
1865       ksba_cert_release (chain->cert);
1866       xfree (chain);
1867       chain = ci_next;
1868     }
1869   ksba_cert_release (issuer_cert);
1870   ksba_cert_release (subject_cert);
1871   return rc;
1872 }
1873
1874
1875 /* Validate a certificate chain.  For a description see
1876    do_validate_chain.  This function is a wrapper to handle a root
1877    certificate with the chain_model flag set.  If RETFLAGS is not
1878    NULL, flags indicating now the verification was done are stored
1879    there.  The only defined vits for RETFLAGS are
1880    VALIDATE_FLAG_CHAIN_MODEL and VALIDATE_FLAG_STEED.
1881
1882    If you are verifying a signature you should set CHECKTIME to the
1883    creation time of the signature.  If your are verifying a
1884    certificate, set it nil (i.e. the empty string).  If the creation
1885    date of the signature is not known use the special date
1886    "19700101T000000" which is treated in a special way here. */
1887 int
1888 gpgsm_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime,
1889                       ksba_isotime_t r_exptime,
1890                       int listmode, estream_t listfp, unsigned int flags,
1891                       unsigned int *retflags)
1892 {
1893   int rc;
1894   struct rootca_flags_s rootca_flags;
1895   unsigned int dummy_retflags;
1896
1897   if (!retflags)
1898     retflags = &dummy_retflags;
1899
1900   /* If the session requested a certain validation mode make sure the
1901      corresponding flags are set.  */
1902   if (ctrl->validation_model == 1)
1903     flags |= VALIDATE_FLAG_CHAIN_MODEL;
1904   else if (ctrl->validation_model == 2)
1905     flags |= VALIDATE_FLAG_STEED;
1906
1907   /* If the chain model was forced, set this immediately into
1908      RETFLAGS.  */
1909   *retflags = (flags & VALIDATE_FLAG_CHAIN_MODEL);
1910
1911   memset (&rootca_flags, 0, sizeof rootca_flags);
1912
1913   rc = do_validate_chain (ctrl, cert, checktime,
1914                           r_exptime, listmode, listfp, flags,
1915                           &rootca_flags);
1916   if (!rc && (flags & VALIDATE_FLAG_STEED))
1917     {
1918       *retflags |= VALIDATE_FLAG_STEED;
1919     }
1920   else if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED
1921       && !(flags & VALIDATE_FLAG_CHAIN_MODEL)
1922       && (rootca_flags.valid && rootca_flags.chain_model))
1923     {
1924       do_list (0, listmode, listfp, _("switching to chain model"));
1925       rc = do_validate_chain (ctrl, cert, checktime,
1926                               r_exptime, listmode, listfp,
1927                               (flags |= VALIDATE_FLAG_CHAIN_MODEL),
1928                               &rootca_flags);
1929       *retflags |= VALIDATE_FLAG_CHAIN_MODEL;
1930     }
1931
1932   if (opt.verbose)
1933     do_list (0, listmode, listfp, _("validation model used: %s"),
1934              (*retflags & VALIDATE_FLAG_STEED)?
1935              "steed" :
1936              (*retflags & VALIDATE_FLAG_CHAIN_MODEL)?
1937              _("chain"):_("shell"));
1938
1939   return rc;
1940 }
1941
1942
1943 /* Check that the given certificate is valid but DO NOT check any
1944    constraints.  We assume that the issuers certificate is already in
1945    the DB and that this one is valid; which it should be because it
1946    has been checked using this function. */
1947 int
1948 gpgsm_basic_cert_check (ctrl_t ctrl, ksba_cert_t cert)
1949 {
1950   int rc = 0;
1951   char *issuer = NULL;
1952   char *subject = NULL;
1953   KEYDB_HANDLE kh;
1954   ksba_cert_t issuer_cert = NULL;
1955
1956   if (opt.no_chain_validation)
1957     {
1958       log_info ("WARNING: bypassing basic certificate checks\n");
1959       return 0;
1960     }
1961
1962   kh = keydb_new ();
1963   if (!kh)
1964     {
1965       log_error (_("failed to allocate keyDB handle\n"));
1966       rc = gpg_error (GPG_ERR_GENERAL);
1967       goto leave;
1968     }
1969
1970   issuer = ksba_cert_get_issuer (cert, 0);
1971   subject = ksba_cert_get_subject (cert, 0);
1972   if (!issuer)
1973     {
1974       log_error ("no issuer found in certificate\n");
1975       rc = gpg_error (GPG_ERR_BAD_CERT);
1976       goto leave;
1977     }
1978
1979   if (is_root_cert (cert, issuer, subject))
1980     {
1981       rc = gpgsm_check_cert_sig (cert, cert);
1982       if (rc)
1983         {
1984           log_error ("self-signed certificate has a BAD signature: %s\n",
1985                      gpg_strerror (rc));
1986           if (DBG_X509)
1987             {
1988               gpgsm_dump_cert ("self-signing cert", cert);
1989             }
1990           rc = gpg_error (GPG_ERR_BAD_CERT);
1991           goto leave;
1992         }
1993     }
1994   else
1995     {
1996       /* Find the next cert up the tree. */
1997       keydb_search_reset (kh);
1998       rc = find_up (ctrl, kh, cert, issuer, 0);
1999       if (rc)
2000         {
2001           if (rc == -1)
2002             {
2003               log_info ("issuer certificate (#/");
2004               gpgsm_dump_string (issuer);
2005               log_printf (") not found\n");
2006             }
2007           else
2008             log_error ("failed to find issuer's certificate: rc=%d\n", rc);
2009           rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
2010           goto leave;
2011         }
2012
2013       ksba_cert_release (issuer_cert); issuer_cert = NULL;
2014       rc = keydb_get_cert (kh, &issuer_cert);
2015       if (rc)
2016         {
2017           log_error ("keydb_get_cert() failed: rc=%d\n", rc);
2018           rc = gpg_error (GPG_ERR_GENERAL);
2019           goto leave;
2020         }
2021
2022       rc = gpgsm_check_cert_sig (issuer_cert, cert);
2023       if (rc)
2024         {
2025           log_error ("certificate has a BAD signature: %s\n",
2026                      gpg_strerror (rc));
2027           if (DBG_X509)
2028             {
2029               gpgsm_dump_cert ("signing issuer", issuer_cert);
2030               gpgsm_dump_cert ("signed subject", cert);
2031             }
2032           rc = gpg_error (GPG_ERR_BAD_CERT);
2033           goto leave;
2034         }
2035       if (opt.verbose)
2036         log_info (_("certificate is good\n"));
2037     }
2038
2039  leave:
2040   xfree (issuer);
2041   xfree (subject);
2042   keydb_release (kh);
2043   ksba_cert_release (issuer_cert);
2044   return rc;
2045 }
2046
2047
2048
2049 /* Check whether the certificate CERT has been issued by the German
2050    authority for qualified signature.  They do not set the
2051    basicConstraints and thus we need this workaround.  It works by
2052    looking up the root certificate and checking whether that one is
2053    listed as a qualified certificate for Germany.
2054
2055    We also try to cache this data but as long as don't keep a
2056    reference to the certificate this won't be used.
2057
2058    Returns: True if CERT is a RegTP issued CA cert (i.e. the root
2059    certificate itself or one of the CAs).  In that case CHAINLEN will
2060    receive the length of the chain which is either 0 or 1.
2061 */
2062 static int
2063 get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen)
2064 {
2065   gpg_error_t err;
2066   ksba_cert_t next;
2067   int rc = 0;
2068   int i, depth;
2069   char country[3];
2070   ksba_cert_t array[4];
2071   char buf[2];
2072   size_t buflen;
2073   int dummy_chainlen;
2074
2075   if (!chainlen)
2076     chainlen = &dummy_chainlen;
2077
2078   *chainlen = 0;
2079   err = ksba_cert_get_user_data (cert, "regtp_ca_chainlen",
2080                                  &buf, sizeof (buf), &buflen);
2081   if (!err)
2082     {
2083       /* Got info. */
2084       if (buflen < 2 || !*buf)
2085         return 0; /* Nothing found. */
2086       *chainlen = buf[1];
2087       return 1; /* This is a regtp CA. */
2088     }
2089   else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
2090     {
2091       log_error ("ksba_cert_get_user_data(%s) failed: %s\n",
2092                  "regtp_ca_chainlen", gpg_strerror (err));
2093       return 0; /* Nothing found.  */
2094     }
2095
2096   /* Need to gather the info.  This requires to walk up the chain
2097      until we have found the root.  Because we are only interested in
2098      German Bundesnetzagentur (former RegTP) derived certificates 3
2099      levels are enough.  (The German signature law demands a 3 tier
2100      hierarchy; thus there is only one CA between the EE and the Root
2101      CA.)  */
2102   memset (&array, 0, sizeof array);
2103
2104   depth = 0;
2105   ksba_cert_ref (cert);
2106   array[depth++] = cert;
2107   ksba_cert_ref (cert);
2108   while (depth < DIM(array) && !(rc=gpgsm_walk_cert_chain (ctrl, cert, &next)))
2109     {
2110       ksba_cert_release (cert);
2111       ksba_cert_ref (next);
2112       array[depth++] = next;
2113       cert = next;
2114     }
2115   ksba_cert_release (cert);
2116   if (rc != -1 || !depth || depth == DIM(array) )
2117     {
2118       /* We did not reached the root. */
2119       goto leave;
2120     }
2121
2122   /* If this is a German signature law issued certificate, we store
2123      additional additional information. */
2124   if (!gpgsm_is_in_qualified_list (NULL, array[depth-1], country)
2125       && !strcmp (country, "de"))
2126     {
2127       /* Setting the pathlen for the root CA and the CA flag for the
2128          next one is all what we need to do. */
2129       err = ksba_cert_set_user_data (array[depth-1], "regtp_ca_chainlen",
2130                                      "\x01\x01", 2);
2131       if (!err && depth > 1)
2132         err = ksba_cert_set_user_data (array[depth-2], "regtp_ca_chainlen",
2133                                        "\x01\x00", 2);
2134       if (err)
2135         log_error ("ksba_set_user_data(%s) failed: %s\n",
2136                    "regtp_ca_chainlen", gpg_strerror (err));
2137       for (i=0; i < depth; i++)
2138         ksba_cert_release (array[i]);
2139       *chainlen = (depth>1? 0:1);
2140       return 1;
2141     }
2142
2143  leave:
2144   /* Nothing special with this certificate. Mark the target
2145      certificate anyway to avoid duplicate lookups. */
2146   err = ksba_cert_set_user_data (cert, "regtp_ca_chainlen", "", 1);
2147   if (err)
2148     log_error ("ksba_set_user_data(%s) failed: %s\n",
2149                "regtp_ca_chainlen", gpg_strerror (err));
2150   for (i=0; i < depth; i++)
2151     ksba_cert_release (array[i]);
2152   return 0;
2153 }