LCOV - code coverage report
Current view: top level - sm - certchain.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 58 966 6.0 %
Date: 2016-12-01 18:37:21 Functions: 3 24 12.5 %

          Line data    Source code
       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           0 : already_asked_marktrusted (ksba_cert_t cert)
      70             : {
      71             :   unsigned char fpr[20];
      72             :   struct marktrusted_info_s *r;
      73             : 
      74           0 :   gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
      75             :   /* No context switches in the loop! */
      76           0 :   for (r=marktrusted_info; r; r= r->next)
      77           0 :     if (!memcmp (r->fpr, fpr, 20))
      78           0 :       return 1;
      79           0 :   return 0;
      80             : }
      81             : 
      82             : /* Flag certificate CERT as already asked whether it shall be marked
      83             :    as trusted.  */
      84             : static void
      85           0 : set_already_asked_marktrusted (ksba_cert_t cert)
      86             : {
      87             :  unsigned char fpr[20];
      88             :  struct marktrusted_info_s *r;
      89             : 
      90           0 :  gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
      91           0 :  for (r=marktrusted_info; r; r= r->next)
      92           0 :    if (!memcmp (r->fpr, fpr, 20))
      93           0 :      return; /* Already marked. */
      94           0 :  r = xtrycalloc (1, sizeof *r);
      95           0 :  if (!r)
      96           0 :    return;
      97           0 :  memcpy (r->fpr, fpr, 20);
      98           0 :  r->next = marktrusted_info;
      99           0 :  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           0 : do_list (int is_error, int listmode, estream_t fp, const char *format, ...)
     107             : {
     108             :   va_list arg_ptr;
     109             : 
     110           0 :   va_start (arg_ptr, format) ;
     111           0 :   if (listmode)
     112             :     {
     113           0 :       if (fp)
     114             :         {
     115           0 :           es_fputs ("  [", fp);
     116           0 :           es_vfprintf (fp, format, arg_ptr);
     117           0 :           es_fputs ("]\n", fp);
     118             :         }
     119             :     }
     120             :   else
     121             :     {
     122           0 :       log_logv (is_error? GPGRT_LOG_ERROR: GPGRT_LOG_INFO, format, arg_ptr);
     123           0 :       log_printf ("\n");
     124             :     }
     125           0 :   va_end (arg_ptr);
     126           0 : }
     127             : 
     128             : /* Return 0 if A and B are equal. */
     129             : static int
     130           0 : 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           0 :   img_a = ksba_cert_get_image (a, &len_a);
     136           0 :   if (!img_a)
     137           0 :     return 1;
     138           0 :   img_b = ksba_cert_get_image (b, &len_b);
     139           0 :   if (!img_b)
     140           0 :     return 1;
     141           0 :   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           0 : 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           0 :   for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
     159           0 :                                              &oid, NULL, &off, &derlen));idx++)
     160           0 :     if (!strcmp (oid, "1.3.6.1.4.1.8301.3.5") )
     161           0 :       break;
     162           0 :   if (err)
     163           0 :     return 0; /* Not found.  */
     164           0 :   der = ksba_cert_get_image (cert, NULL);
     165           0 :   if (!der)
     166             :     {
     167           0 :       err = gpg_error (GPG_ERR_INV_OBJ); /* Oops  */
     168           0 :       goto leave;
     169             :     }
     170           0 :   der += off;
     171             : 
     172           0 :   err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
     173             :                           &ndef, &objlen, &hdrlen);
     174           0 :   if (!err && (objlen > derlen || tag != TAG_SEQUENCE))
     175           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     176           0 :   if (err)
     177           0 :     goto leave;
     178           0 :   derlen = objlen;
     179           0 :   err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
     180             :                           &ndef, &objlen, &hdrlen);
     181           0 :   if (!err && (objlen > derlen || tag != TAG_OBJECT_ID))
     182           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     183           0 :   if (err)
     184           0 :     goto leave;
     185           0 :   oidbuf = ksba_oid_to_str (der, objlen);
     186           0 :   if (!oidbuf)
     187             :     {
     188           0 :       err = gpg_error_from_syserror ();
     189           0 :       goto leave;
     190             :     }
     191             : 
     192           0 :   if (opt.verbose)
     193           0 :     do_list (0, listmode, listfp,
     194           0 :              _("validation model requested by certificate: %s"),
     195           0 :               !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1")? _("chain") :
     196           0 :               !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.2")? _("shell") :
     197             :               /* */                                       oidbuf);
     198           0 :   yes = !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1");
     199           0 :   ksba_free (oidbuf);
     200           0 :   return yes;
     201             : 
     202             : 
     203             :  leave:
     204           0 :   log_error ("error parsing validityModel: %s\n", gpg_strerror (err));
     205           0 :   return 0;
     206             : }
     207             : 
     208             : 
     209             : 
     210             : static int
     211           0 : 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           0 :   int rc = 0, i, idx, crit;
     228             :   const char *oid;
     229             :   gpg_error_t err;
     230             :   int unsupported;
     231             :   strlist_t sl;
     232             : 
     233           0 :   for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
     234           0 :                                              &oid, &crit, NULL, NULL));idx++)
     235             :     {
     236           0 :       if (!crit)
     237           0 :         continue;
     238           0 :       for (i=0; known[i] && strcmp (known[i],oid); i++)
     239             :         ;
     240           0 :       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           0 :       if (unsupported && opt.ignored_cert_extensions)
     246             :         {
     247           0 :           for (sl=opt.ignored_cert_extensions;
     248           0 :                sl && strcmp (sl->d, oid); sl = sl->next)
     249             :             ;
     250           0 :           if (sl)
     251           0 :             unsupported = 0;
     252             :         }
     253           0 :       if (unsupported)
     254             :         {
     255           0 :           do_list (1, listmode, fp,
     256           0 :                    _("critical certificate extension %s is not supported"),
     257             :                    oid);
     258           0 :           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           0 :   if (err
     264           0 :       && gpg_err_code (err) != GPG_ERR_EOF
     265           0 :       && gpg_err_code (err) != GPG_ERR_NO_VALUE)
     266           0 :     rc = err;
     267             : 
     268           0 :   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           0 : 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           0 :   err = ksba_cert_is_ca (cert, &flag, chainlen);
     284           0 :   if (err)
     285           0 :     return err;
     286           0 :   if (!flag)
     287             :     {
     288           0 :       if (get_regtp_ca_info (ctrl, cert, chainlen))
     289             :         {
     290             :           /* Note that dirmngr takes a different way to cope with such
     291             :              certs. */
     292           0 :           return 0; /* RegTP issued certificate. */
     293             :         }
     294             : 
     295           0 :       do_list (1, listmode, fp,_("issuer certificate is not marked as a CA"));
     296           0 :       return gpg_error (GPG_ERR_BAD_CA_CERT);
     297             :     }
     298           0 :   return 0;
     299             : }
     300             : 
     301             : 
     302             : static int
     303           0 : 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           0 :   err = ksba_cert_get_cert_policies (cert, &policies);
     311           0 :   if (gpg_err_code (err) == GPG_ERR_NO_DATA)
     312           0 :     return 0; /* No policy given. */
     313           0 :   if (err)
     314           0 :     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           0 :   if (opt.verbose > 1 && !listmode)
     322           0 :     log_info ("certificate's policy list: %s\n", policies);
     323             : 
     324             :   /* The check is very minimal but won't give false positives */
     325           0 :   any_critical = !!strstr (policies, ":C");
     326             : 
     327           0 :   if (!opt.policy_file)
     328             :     {
     329           0 :       xfree (policies);
     330           0 :       if (any_critical)
     331             :         {
     332           0 :           do_list (1, listmode, fplist,
     333           0 :                    _("critical marked policy without configured policies"));
     334           0 :           return gpg_error (GPG_ERR_NO_POLICY_MATCH);
     335             :         }
     336           0 :       return 0;
     337             :     }
     338             : 
     339           0 :   fp = fopen (opt.policy_file, "r");
     340           0 :   if (!fp)
     341             :     {
     342           0 :       if (opt.verbose || errno != ENOENT)
     343           0 :         log_info (_("failed to open '%s': %s\n"),
     344           0 :                   opt.policy_file, strerror (errno));
     345           0 :       xfree (policies);
     346             :       /* With no critical policies this is only a warning */
     347           0 :       if (!any_critical)
     348             :         {
     349           0 :           if (!opt.quiet)
     350           0 :             do_list (0, listmode, fplist,
     351           0 :                      _("Note: non-critical certificate policy not allowed"));
     352           0 :           return 0;
     353             :         }
     354           0 :       do_list (1, listmode, fplist,
     355           0 :                _("certificate policy not allowed"));
     356           0 :       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           0 :           if (!fgets (line, DIM(line)-1, fp) )
     369             :             {
     370           0 :               gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
     371             : 
     372           0 :               xfree (policies);
     373           0 :               if (feof (fp))
     374             :                 {
     375           0 :                   fclose (fp);
     376             :                   /* With no critical policies this is only a warning */
     377           0 :                   if (!any_critical)
     378             :                     {
     379           0 :                       do_list (0, listmode, fplist,
     380           0 :                      _("Note: non-critical certificate policy not allowed"));
     381           0 :                       return 0;
     382             :                     }
     383           0 :                   do_list (1, listmode, fplist,
     384           0 :                            _("certificate policy not allowed"));
     385           0 :                   return gpg_error (GPG_ERR_NO_POLICY_MATCH);
     386             :                 }
     387           0 :               fclose (fp);
     388           0 :               return tmperr;
     389             :             }
     390             : 
     391           0 :           if (!*line || line[strlen(line)-1] != '\n')
     392             :             {
     393             :               /* eat until end of line */
     394           0 :               while ( (c=getc (fp)) != EOF && c != '\n')
     395             :                 ;
     396           0 :               fclose (fp);
     397           0 :               xfree (policies);
     398           0 :               return gpg_error (*line? GPG_ERR_LINE_TOO_LONG
     399             :                                      : GPG_ERR_INCOMPLETE_LINE);
     400             :             }
     401             : 
     402             :           /* Allow for empty lines and spaces */
     403           0 :           for (p=line; spacep (p); p++)
     404             :             ;
     405             :         }
     406           0 :       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           0 :       for (allowed=line; spacep (allowed); allowed++)
     412             :         ;
     413           0 :       p = strpbrk (allowed, " :\n");
     414           0 :       if (!*p || p == allowed)
     415             :         {
     416           0 :           fclose (fp);
     417           0 :           xfree (policies);
     418           0 :           return gpg_error (GPG_ERR_CONFIGURATION);
     419             :         }
     420           0 :       *p = 0; /* strip the rest of the line */
     421             :       /* See whether we find ALLOWED (which is an OID) in POLICIES */
     422           0 :       for (haystack=policies; (p=strstr (haystack, allowed)); haystack = p+1)
     423             :         {
     424           0 :           if ( !(p == policies || p[-1] == '\n') )
     425           0 :             continue; /* Does not match the begin of a line. */
     426           0 :           if (p[strlen (allowed)] != ':')
     427           0 :             continue; /* The length does not match. */
     428             :           /* Yep - it does match so return okay. */
     429           0 :           fclose (fp);
     430           0 :           xfree (policies);
     431           0 :           return 0;
     432             :         }
     433           0 :     }
     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           0 : find_up_search_by_keyid (ctrl_t ctrl, KEYDB_HANDLE kh,
     442             :                          const char *issuer, ksba_sexp_t keyid)
     443             : {
     444             :   int rc;
     445           0 :   ksba_cert_t cert = NULL;
     446           0 :   ksba_sexp_t subj = NULL;
     447           0 :   int anyfound = 0;
     448             :   ksba_isotime_t not_before, last_not_before;
     449             : 
     450           0 :   keydb_search_reset (kh);
     451           0 :   while (!(rc = keydb_search_subject (ctrl, kh, issuer)))
     452             :     {
     453           0 :       ksba_cert_release (cert); cert = NULL;
     454           0 :       rc = keydb_get_cert (kh, &cert);
     455           0 :       if (rc)
     456             :         {
     457           0 :           log_error ("keydb_get_cert() failed: rc=%d\n", rc);
     458           0 :           rc = -1;
     459           0 :           break;
     460             :         }
     461           0 :       xfree (subj);
     462           0 :       if (!ksba_cert_get_subj_key_id (cert, NULL, &subj))
     463             :         {
     464           0 :           if (!cmp_simple_canon_sexp (keyid, subj))
     465             :             {
     466             :               /* Found matching cert. */
     467           0 :               rc = ksba_cert_get_validity (cert, 0, not_before);
     468           0 :               if (rc)
     469             :                 {
     470           0 :                   log_error ("keydb_get_validity() failed: rc=%d\n", rc);
     471           0 :                   rc = -1;
     472           0 :                   break;
     473             :                 }
     474             : 
     475           0 :               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           0 :                   anyfound = 1;
     482           0 :                   gnupg_copy_time (last_not_before, not_before);
     483           0 :                   keydb_push_found_state (kh);
     484             :                 }
     485             :             }
     486             :         }
     487             :     }
     488             : 
     489           0 :   if (anyfound)
     490             :     {
     491             :       /* Take the last saved one.  */
     492           0 :       keydb_pop_found_state (kh);
     493           0 :       rc = 0;  /* Ignore EOF or other error after the first cert.  */
     494             :     }
     495             : 
     496           0 :   ksba_cert_release (cert);
     497           0 :   xfree (subj);
     498           0 :   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           0 : find_up_store_certs_cb (void *cb_value, ksba_cert_t cert)
     510             : {
     511           0 :   struct find_up_store_certs_s *parm = cb_value;
     512             : 
     513           0 :   if (keydb_store_cert (parm->ctrl, cert, 1, NULL))
     514           0 :     log_error ("error storing issuer certificate as ephemeral\n");
     515           0 :   parm->count++;
     516           0 : }
     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           0 : find_up_external (ctrl_t ctrl, KEYDB_HANDLE kh,
     526             :                   const char *issuer, ksba_sexp_t keyid)
     527             : {
     528             :   int rc;
     529           0 :   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           0 :   find_up_store_certs_parm.ctrl = ctrl;
     535           0 :   find_up_store_certs_parm.count = 0;
     536             : 
     537           0 :   if (opt.verbose)
     538           0 :     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           0 :   s = strstr (issuer, "CN=");
     544           0 :   if (!s || s == issuer || s[-1] != ',')
     545           0 :     s = issuer;
     546           0 :   pattern = xtrymalloc (strlen (s)+2);
     547           0 :   if (!pattern)
     548           0 :     return gpg_error_from_syserror ();
     549           0 :   strcpy (stpcpy (pattern, "/"), s);
     550           0 :   add_to_strlist (&names, pattern);
     551           0 :   xfree (pattern);
     552             : 
     553           0 :   rc = gpgsm_dirmngr_lookup (ctrl, names, 0, find_up_store_certs_cb,
     554             :                              &find_up_store_certs_parm);
     555           0 :   free_strlist (names);
     556             : 
     557           0 :   if (opt.verbose)
     558           0 :     log_info (_("number of issuers matching: %d\n"),
     559             :               find_up_store_certs_parm.count);
     560           0 :   if (rc)
     561             :     {
     562           0 :       log_error ("external key lookup failed: %s\n", gpg_strerror (rc));
     563           0 :       rc = -1;
     564             :     }
     565           0 :   else if (!find_up_store_certs_parm.count)
     566           0 :     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           0 :       old = keydb_set_ephemeral (kh, 1);
     573           0 :       if (keyid)
     574           0 :         rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
     575             :       else
     576             :         {
     577           0 :           keydb_search_reset (kh);
     578           0 :           rc = keydb_search_subject (ctrl, kh, issuer);
     579             :         }
     580           0 :       keydb_set_ephemeral (kh, old);
     581             :     }
     582           0 :   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           0 : 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           0 :   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           0 :   find_up_store_certs_parm.ctrl = ctrl;
     603           0 :   find_up_store_certs_parm.count = 0;
     604             : 
     605           0 :   if (opt.verbose)
     606           0 :     log_info (_("looking up issuer from the Dirmngr cache\n"));
     607           0 :   if (subject_mode)
     608             :     {
     609           0 :       pattern = xtrymalloc (strlen (issuer)+2);
     610           0 :       if (pattern)
     611           0 :         strcpy (stpcpy (pattern, "/"), issuer);
     612             :     }
     613           0 :   else if (serialno)
     614           0 :     pattern = gpgsm_format_sn_issuer (serialno, issuer);
     615             :   else
     616             :     {
     617           0 :       pattern = xtrymalloc (strlen (issuer)+3);
     618           0 :       if (pattern)
     619           0 :         strcpy (stpcpy (pattern, "#/"), issuer);
     620             :     }
     621           0 :   if (!pattern)
     622           0 :     return gpg_error_from_syserror ();
     623           0 :   add_to_strlist (&names, pattern);
     624           0 :   xfree (pattern);
     625             : 
     626           0 :   rc = gpgsm_dirmngr_lookup (ctrl, names, 1, find_up_store_certs_cb,
     627             :                              &find_up_store_certs_parm);
     628           0 :   free_strlist (names);
     629             : 
     630           0 :   if (opt.verbose)
     631           0 :     log_info (_("number of matching certificates: %d\n"),
     632             :               find_up_store_certs_parm.count);
     633           0 :   if (rc && !opt.quiet)
     634           0 :     log_info (_("dirmngr cache-only key lookup failed: %s\n"),
     635             :               gpg_strerror (rc));
     636           0 :   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           0 : 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           0 :   int rc = -1;
     655             : 
     656           0 :   if (DBG_X509)
     657           0 :     log_debug ("looking for parent certificate\n");
     658           0 :   if (!ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno))
     659             :     {
     660           0 :       const char *s = ksba_name_enum (authid, 0);
     661           0 :       if (s && *authidno)
     662             :         {
     663           0 :           rc = keydb_search_issuer_sn (ctrl, kh, s, authidno);
     664           0 :           if (rc)
     665           0 :             keydb_search_reset (kh);
     666             : 
     667           0 :           if (!rc && DBG_X509)
     668           0 :             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           0 :           if (rc == -1 && !find_next)
     676           0 :             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           0 :           if (rc == -1 && !find_next)
     682             :             {
     683           0 :               int old = keydb_set_ephemeral (kh, 1);
     684           0 :               if (!old)
     685             :                 {
     686           0 :                   rc = keydb_search_issuer_sn (ctrl, kh, s, authidno);
     687           0 :                   if (rc)
     688           0 :                     keydb_search_reset (kh);
     689             : 
     690           0 :                   if (!rc && DBG_X509)
     691           0 :                     log_debug ("  found via authid and sn+issuer (ephem)\n");
     692             :                 }
     693           0 :               keydb_set_ephemeral (kh, old);
     694             :             }
     695           0 :           if (rc)
     696           0 :             rc = -1; /* Need to make sure to have this error code. */
     697             :         }
     698             : 
     699           0 :       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           0 :           rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
     707           0 :           if (!rc && DBG_X509)
     708           0 :             log_debug ("  found via authid and keyid\n");
     709           0 :           if (rc)
     710             :             {
     711           0 :               int old = keydb_set_ephemeral (kh, 1);
     712           0 :               if (!old)
     713           0 :                 rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
     714           0 :               if (!rc && DBG_X509)
     715           0 :                 log_debug ("  found via authid and keyid (ephem)\n");
     716           0 :               keydb_set_ephemeral (kh, old);
     717             :             }
     718           0 :           if (rc)
     719           0 :             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           0 :       if (rc == -1 && !find_next)
     725             :         {
     726           0 :           if (!find_up_dirmngr (ctrl, kh, NULL, issuer, 1))
     727             :             {
     728           0 :               int old = keydb_set_ephemeral (kh, 1);
     729           0 :               if (keyid)
     730           0 :                 rc = find_up_search_by_keyid (ctrl, kh, issuer, keyid);
     731             :               else
     732             :                 {
     733           0 :                   keydb_search_reset (kh);
     734           0 :                   rc = keydb_search_subject (ctrl, kh, issuer);
     735             :                 }
     736           0 :               keydb_set_ephemeral (kh, old);
     737             :             }
     738           0 :           if (rc)
     739           0 :             rc = -1; /* Need to make sure to have this error code. */
     740             : 
     741           0 :           if (!rc && DBG_X509)
     742           0 :             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           0 :       if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
     747             :         {
     748           0 :           rc = find_up_external (ctrl, kh, issuer, keyid);
     749           0 :           if (!rc && DBG_X509)
     750           0 :             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           0 :       if (rc == -1 && opt.quiet)
     758             :         ;
     759           0 :       else if (rc == -1)
     760             :         {
     761           0 :           log_info ("%sissuer certificate ", find_next?"next ":"");
     762           0 :           if (keyid)
     763             :             {
     764           0 :               log_printf ("{");
     765           0 :               gpgsm_dump_serial (keyid);
     766           0 :               log_printf ("} ");
     767             :             }
     768           0 :           if (authidno)
     769             :             {
     770           0 :               log_printf ("(#");
     771           0 :               gpgsm_dump_serial (authidno);
     772           0 :               log_printf ("/");
     773           0 :               gpgsm_dump_string (s);
     774           0 :               log_printf (") ");
     775             :             }
     776           0 :           log_printf ("not found using authorityKeyIdentifier\n");
     777             :         }
     778           0 :       else if (rc)
     779           0 :         log_error ("failed to find authorityKeyIdentifier: rc=%d\n", rc);
     780           0 :       xfree (keyid);
     781           0 :       ksba_name_release (authid);
     782           0 :       xfree (authidno);
     783             :     }
     784             : 
     785           0 :   if (rc) /* Not found via authorithyKeyIdentifier, try regular issuer name. */
     786           0 :     rc = keydb_search_subject (ctrl, kh, issuer);
     787           0 :   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           0 :       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           0 :       old = keydb_set_ephemeral (kh, 1);
     797           0 :       if (!old)
     798             :         {
     799           0 :           keydb_search_reset (kh);
     800           0 :           rc = keydb_search_subject (ctrl, kh, issuer);
     801             :         }
     802           0 :       keydb_set_ephemeral (kh, old);
     803             : 
     804           0 :       if (!rc && DBG_X509)
     805           0 :         log_debug ("  found via issuer\n");
     806             :     }
     807             : 
     808             :   /* Still not found.  If enabled, try an external lookup.  */
     809           0 :   if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
     810             :     {
     811           0 :       rc = find_up_external (ctrl, kh, issuer, NULL);
     812           0 :       if (!rc && DBG_X509)
     813           0 :         log_debug ("  found via issuer and external lookup\n");
     814             :     }
     815             : 
     816           0 :   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           3 : gpgsm_walk_cert_chain (ctrl_t ctrl, ksba_cert_t start, ksba_cert_t *r_next)
     824             : {
     825           3 :   int rc = 0;
     826           3 :   char *issuer = NULL;
     827           3 :   char *subject = NULL;
     828           3 :   KEYDB_HANDLE kh = keydb_new ();
     829             : 
     830           3 :   *r_next = NULL;
     831           3 :   if (!kh)
     832             :     {
     833           0 :       log_error (_("failed to allocate keyDB handle\n"));
     834           0 :       rc = gpg_error (GPG_ERR_GENERAL);
     835           0 :       goto leave;
     836             :     }
     837             : 
     838           3 :   issuer = ksba_cert_get_issuer (start, 0);
     839           3 :   subject = ksba_cert_get_subject (start, 0);
     840           3 :   if (!issuer)
     841             :     {
     842           0 :       log_error ("no issuer found in certificate\n");
     843           0 :       rc = gpg_error (GPG_ERR_BAD_CERT);
     844           0 :       goto leave;
     845             :     }
     846           3 :   if (!subject)
     847             :     {
     848           0 :       log_error ("no subject found in certificate\n");
     849           0 :       rc = gpg_error (GPG_ERR_BAD_CERT);
     850           0 :       goto leave;
     851             :     }
     852             : 
     853           3 :   if (is_root_cert (start, issuer, subject))
     854             :     {
     855           3 :       rc = -1; /* we are at the root */
     856           3 :       goto leave;
     857             :     }
     858             : 
     859           0 :   rc = find_up (ctrl, kh, start, issuer, 0);
     860           0 :   if (rc)
     861             :     {
     862             :       /* It is quite common not to have a certificate, so better don't
     863             :          print an error here.  */
     864           0 :       if (rc != -1 && opt.verbose > 1)
     865           0 :         log_error ("failed to find issuer's certificate: rc=%d\n", rc);
     866           0 :       rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
     867           0 :       goto leave;
     868             :     }
     869             : 
     870           0 :   rc = keydb_get_cert (kh, r_next);
     871           0 :   if (rc)
     872             :     {
     873           0 :       log_error ("keydb_get_cert() failed: rc=%d\n", rc);
     874           0 :       rc = gpg_error (GPG_ERR_GENERAL);
     875             :     }
     876             : 
     877             :  leave:
     878           3 :   xfree (issuer);
     879           3 :   xfree (subject);
     880           3 :   keydb_release (kh);
     881           3 :   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           6 : is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn)
     889             : {
     890             :   gpg_error_t err;
     891           6 :   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           6 :   ksba_sexp_t subj_keyid = NULL;
     898             : 
     899           6 :   if (!issuerdn || !subjectdn)
     900           0 :     return 0;  /* No.  */
     901             : 
     902           6 :   if (strcmp (issuerdn, subjectdn))
     903           0 :     return 0;  /* No.  */
     904             : 
     905           6 :   err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn);
     906           6 :   if (err)
     907             :     {
     908           0 :       if (gpg_err_code (err) == GPG_ERR_NO_DATA)
     909           0 :         return 1; /* Yes. Without a authorityKeyIdentifier this needs
     910             :                      to be the Root certifcate (our trust anchor).  */
     911           0 :       log_error ("error getting authorityKeyIdentifier: %s\n",
     912             :                  gpg_strerror (err));
     913           0 :       return 0; /* Well, it is broken anyway.  Return No. */
     914             :     }
     915             : 
     916           6 :   serialno = ksba_cert_get_serial (cert);
     917           6 :   if (!serialno)
     918             :     {
     919           0 :       log_error ("error getting serialno: %s\n", gpg_strerror (err));
     920           0 :       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           6 :   ak_name_str = ksba_name_enum (ak_name, 0);
     926           6 :   if (ak_name_str
     927           6 :       && !strcmp (ak_name_str, issuerdn)
     928           6 :       && !cmp_simple_canon_sexp (ak_sn, serialno))
     929             :     {
     930           6 :       result = 1;  /* Right, CERT is self-signed.  */
     931           6 :       goto leave;
     932             :     }
     933             : 
     934             :   /* Similar for the ak_keyid. */
     935           0 :   if (ak_keyid && !ksba_cert_get_subj_key_id (cert, NULL, &subj_keyid)
     936           0 :       && !cmp_simple_canon_sexp (ak_keyid, subj_keyid))
     937             :     {
     938           0 :       result = 1;  /* Right, CERT is self-signed.  */
     939           0 :       goto leave;
     940             :     }
     941             : 
     942             : 
     943             :  leave:
     944           6 :   ksba_free (subj_keyid);
     945           6 :   ksba_free (ak_keyid);
     946           6 :   ksba_name_release (ak_name);
     947           6 :   ksba_free (ak_sn);
     948           6 :   ksba_free (serialno);
     949           6 :   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           0 : gpgsm_is_root_cert (ksba_cert_t cert)
     958             : {
     959             :   char *issuer;
     960             :   char *subject;
     961             :   int yes;
     962             : 
     963           0 :   issuer = ksba_cert_get_issuer (cert, 0);
     964           0 :   subject = ksba_cert_get_subject (cert, 0);
     965           0 :   yes = is_root_cert (cert, issuer, subject);
     966           0 :   xfree (issuer);
     967           0 :   xfree (subject);
     968           0 :   return yes;
     969             : }
     970             : 
     971             : 
     972             : /* This is a helper for gpgsm_validate_chain. */
     973             : static gpg_error_t
     974           0 : 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           0 :   if (ctrl->offline || (opt.no_crl_check && !ctrl->use_ocsp))
     981             :     {
     982           0 :       audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK,
     983             :                     gpg_error (GPG_ERR_NOT_ENABLED));
     984           0 :       return 0;
     985             :     }
     986             : 
     987           0 :   err = gpgsm_dirmngr_isvalid (ctrl,
     988             :                                subject_cert, issuer_cert,
     989           0 :                                force_ocsp? 2 : !!ctrl->use_ocsp);
     990           0 :   audit_log_ok (ctrl->audit, AUDIT_CRL_CHECK, err);
     991             : 
     992           0 :   if (err)
     993             :     {
     994           0 :       if (!lm)
     995           0 :         gpgsm_cert_log_name (NULL, subject_cert);
     996           0 :       switch (gpg_err_code (err))
     997             :         {
     998             :         case GPG_ERR_CERT_REVOKED:
     999           0 :           do_list (1, lm, fp, _("certificate has been revoked"));
    1000           0 :           *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           0 :           keydb_set_cert_flags (ctrl, subject_cert, 1, KEYBOX_FLAG_VALIDITY, 0,
    1005             :                                 ~0, VALIDITY_REVOKED);
    1006           0 :           break;
    1007             : 
    1008             :         case GPG_ERR_NO_CRL_KNOWN:
    1009           0 :           do_list (1, lm, fp, _("no CRL found for certificate"));
    1010           0 :           *any_no_crl = 1;
    1011           0 :           break;
    1012             : 
    1013             :         case GPG_ERR_NO_DATA:
    1014           0 :           do_list (1, lm, fp, _("the status of the certificate is unknown"));
    1015           0 :           *any_no_crl = 1;
    1016           0 :           break;
    1017             : 
    1018             :         case GPG_ERR_CRL_TOO_OLD:
    1019           0 :           do_list (1, lm, fp, _("the available CRL is too old"));
    1020           0 :           if (!lm)
    1021           0 :             log_info (_("please make sure that the "
    1022             :                         "\"dirmngr\" is properly installed\n"));
    1023           0 :           *any_crl_too_old = 1;
    1024           0 :           break;
    1025             : 
    1026             :         default:
    1027           0 :           do_list (1, lm, fp, _("checking the CRL failed: %s"),
    1028             :                    gpg_strerror (err));
    1029           0 :           return err;
    1030             :         }
    1031             :     }
    1032           0 :   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           0 : 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           0 :   err = ksba_cert_get_validity (subject_cert, 0, not_before);
    1051           0 :   if (!err)
    1052           0 :     err = ksba_cert_get_validity (subject_cert, 1, not_after);
    1053           0 :   if (err)
    1054             :     {
    1055           0 :       do_list (1, listmode, listfp,
    1056           0 :                _("certificate with invalid validity: %s"), gpg_strerror (err));
    1057           0 :       return gpg_error (GPG_ERR_BAD_CERT);
    1058             :     }
    1059             : 
    1060           0 :   if (*not_after)
    1061             :     {
    1062           0 :       if (!*exptime)
    1063           0 :         gnupg_copy_time (exptime, not_after);
    1064           0 :       else if (strcmp (not_after, exptime) < 0 )
    1065           0 :         gnupg_copy_time (exptime, not_after);
    1066             :     }
    1067             : 
    1068           0 :   if (*not_before && strcmp (current_time, not_before) < 0 )
    1069             :     {
    1070           0 :       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           0 :       if (!listmode)
    1075             :         {
    1076           0 :           log_info ("  (valid from ");
    1077           0 :           dump_isotime (not_before);
    1078           0 :           log_printf (")\n");
    1079             :         }
    1080           0 :       return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
    1081             :     }
    1082             : 
    1083           0 :   if (*not_after && strcmp (current_time, not_after) > 0 )
    1084             :     {
    1085           0 :       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           0 :       if (!listmode)
    1090             :         {
    1091           0 :           log_info ("  (expired at ");
    1092           0 :           dump_isotime (not_after);
    1093           0 :           log_printf (")\n");
    1094             :         }
    1095           0 :       if (opt.ignore_expiration)
    1096           0 :         log_info ("WARNING: ignoring expiration\n");
    1097             :       else
    1098           0 :         return gpg_error (GPG_ERR_CERT_EXPIRED);
    1099             :     }
    1100             : 
    1101           0 :   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           0 : 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           0 :   err = ksba_cert_get_validity (subject_cert, 0, not_before);
    1119           0 :   if (!err)
    1120           0 :     err = ksba_cert_get_validity (subject_cert, 1, not_after);
    1121           0 :   if (err)
    1122             :     {
    1123           0 :       do_list (1, listmode, listfp,
    1124           0 :                _("certificate with invalid validity: %s"), gpg_strerror (err));
    1125           0 :       return gpg_error (GPG_ERR_BAD_CERT);
    1126             :     }
    1127           0 :   if (!*not_before || !*not_after)
    1128             :     {
    1129           0 :       do_list (1, listmode, listfp,
    1130           0 :                _("required certificate attributes missing: %s%s%s"),
    1131           0 :                !*not_before? "notBefore":"",
    1132           0 :                (!*not_before && !*not_after)? ", ":"",
    1133           0 :                !*not_before? "notAfter":"");
    1134           0 :       return gpg_error (GPG_ERR_BAD_CERT);
    1135             :     }
    1136           0 :   if (strcmp (not_before, not_after) > 0 )
    1137             :     {
    1138           0 :       do_list (1, listmode, listfp,
    1139           0 :                _("certificate with invalid validity"));
    1140           0 :       log_info ("  (valid from ");
    1141           0 :       dump_isotime (not_before);
    1142           0 :       log_printf (" expired at ");
    1143           0 :       dump_isotime (not_after);
    1144           0 :       log_printf (")\n");
    1145           0 :       return gpg_error (GPG_ERR_BAD_CERT);
    1146             :     }
    1147             : 
    1148           0 :   if (!*exptime)
    1149           0 :     gnupg_copy_time (exptime, not_after);
    1150           0 :   else if (strcmp (not_after, exptime) < 0 )
    1151           0 :     gnupg_copy_time (exptime, not_after);
    1152             : 
    1153           0 :   if (strcmp (current_time, not_before) < 0 )
    1154             :     {
    1155           0 :       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           0 :       if (!listmode)
    1160             :         {
    1161           0 :           log_info ("  (valid from ");
    1162           0 :           dump_isotime (not_before);
    1163           0 :           log_printf (")\n");
    1164             :         }
    1165           0 :       return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
    1166             :     }
    1167             : 
    1168           0 :   if (*check_time
    1169           0 :       && (strcmp (check_time, not_before) < 0
    1170           0 :           || 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           0 :       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           0 :       if (!listmode)
    1182             :         {
    1183           0 :           log_info (depth== 0? _("  (  signature created at ") :
    1184             :                     /* */      _("  (certificate created at ") );
    1185           0 :           dump_isotime (check_time);
    1186           0 :           log_printf (")\n");
    1187           0 :           log_info (depth==0? _("  (certificate valid from ") :
    1188             :                     /* */     _("  (     issuer valid from ") );
    1189           0 :           dump_isotime (not_before);
    1190           0 :           log_info (" to ");
    1191           0 :           dump_isotime (not_after);
    1192           0 :           log_printf (")\n");
    1193             :         }
    1194           0 :       if (opt.ignore_expiration)
    1195           0 :         log_info ("WARNING: ignoring expiration\n");
    1196             :       else
    1197           0 :         return gpg_error (GPG_ERR_CERT_EXPIRED);
    1198             :     }
    1199             : 
    1200           0 :   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           0 : 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           0 :   int success = 0;
    1216             : 
    1217           0 :   fpr = gpgsm_get_fingerprint_string (cert, GCRY_MD_SHA1);
    1218           0 :   log_info (_("fingerprint=%s\n"), fpr? fpr : "?");
    1219           0 :   xfree (fpr);
    1220             : 
    1221           0 :   if (no_more_questions)
    1222           0 :     rc = gpg_error (GPG_ERR_NOT_SUPPORTED);
    1223             :   else
    1224           0 :     rc = gpgsm_agent_marktrusted (ctrl, cert);
    1225           0 :   if (!rc)
    1226             :     {
    1227           0 :       log_info (_("root certificate has now been marked as trusted\n"));
    1228           0 :       success = 1;
    1229             :     }
    1230           0 :   else if (!listmode)
    1231             :     {
    1232           0 :       gpgsm_dump_cert ("issuer", cert);
    1233           0 :       log_info ("after checking the fingerprint, you may want "
    1234             :                 "to add it manually to the list of trusted certificates.\n");
    1235             :     }
    1236             : 
    1237           0 :   if (gpg_err_code (rc) == GPG_ERR_NOT_SUPPORTED)
    1238             :     {
    1239           0 :       if (!no_more_questions)
    1240           0 :         log_info (_("interactive marking as trusted "
    1241             :                     "not enabled in gpg-agent\n"));
    1242           0 :       no_more_questions = 1;
    1243             :     }
    1244           0 :   else if (gpg_err_code (rc) == GPG_ERR_CANCELED)
    1245             :     {
    1246           0 :       log_info (_("interactive marking as trusted "
    1247             :                   "disabled for this session\n"));
    1248           0 :       no_more_questions = 1;
    1249             :     }
    1250             :   else
    1251           0 :     set_already_asked_marktrusted (cert);
    1252             : 
    1253           0 :   return success;
    1254             : }
    1255             : 
    1256             : 
    1257             : 
    1258             : 
    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           0 : 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           0 :   int rc = 0, depth, maxdepth;
    1279           0 :   char *issuer = NULL;
    1280           0 :   char *subject = NULL;
    1281           0 :   KEYDB_HANDLE kh = NULL;
    1282           0 :   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           0 :   int any_expired = 0;
    1287           0 :   int any_revoked = 0;
    1288           0 :   int any_no_crl = 0;
    1289           0 :   int any_crl_too_old = 0;
    1290           0 :   int any_no_policy_match = 0;
    1291           0 :   int is_qualified = -1; /* Indicates whether the certificate stems
    1292             :                             from a qualified root certificate.
    1293             :                             -1 = unknown, 0 = no, 1 = yes. */
    1294           0 :   chain_item_t chain = NULL; /* A list of all certificates in the chain.  */
    1295             : 
    1296             : 
    1297           0 :   gnupg_get_isotime (current_time);
    1298             : 
    1299           0 :   if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
    1300             :     {
    1301           0 :       if (!strcmp (checktime_arg, "19700101T000000"))
    1302             :         {
    1303           0 :           do_list (1, listmode, listfp,
    1304           0 :                    _("WARNING: creation time of signature not known - "
    1305             :                      "assuming current time"));
    1306           0 :           gnupg_copy_time (check_time, current_time);
    1307             :         }
    1308             :       else
    1309           0 :         gnupg_copy_time (check_time, checktime_arg);
    1310             :     }
    1311             :   else
    1312           0 :     *check_time = 0;
    1313             : 
    1314           0 :   if (r_exptime)
    1315           0 :     *r_exptime = 0;
    1316           0 :   *exptime = 0;
    1317             : 
    1318           0 :   if (opt.no_chain_validation && !listmode)
    1319             :     {
    1320           0 :       log_info ("WARNING: bypassing certificate chain validation\n");
    1321           0 :       return 0;
    1322             :     }
    1323             : 
    1324           0 :   kh = keydb_new ();
    1325           0 :   if (!kh)
    1326             :     {
    1327           0 :       log_error (_("failed to allocate keyDB handle\n"));
    1328           0 :       rc = gpg_error (GPG_ERR_GENERAL);
    1329           0 :       goto leave;
    1330             :     }
    1331             : 
    1332           0 :   if (DBG_X509 && !listmode)
    1333           0 :     gpgsm_dump_cert ("target", cert);
    1334             : 
    1335           0 :   subject_cert = cert;
    1336           0 :   ksba_cert_ref (subject_cert);
    1337           0 :   maxdepth = 50;
    1338           0 :   depth = 0;
    1339             : 
    1340             :   for (;;)
    1341             :     {
    1342             :       int is_root;
    1343           0 :       gpg_error_t istrusted_rc = -1;
    1344             : 
    1345             :       /* Put the certificate on our list.  */
    1346             :       {
    1347             :         chain_item_t ci;
    1348             : 
    1349           0 :         ci = xtrycalloc (1, sizeof *ci);
    1350           0 :         if (!ci)
    1351             :           {
    1352           0 :             rc = gpg_error_from_syserror ();
    1353           0 :             goto leave;
    1354             :           }
    1355           0 :         ksba_cert_ref (subject_cert);
    1356           0 :         ci->cert = subject_cert;
    1357           0 :         ci->next = chain;
    1358           0 :         chain = ci;
    1359             :       }
    1360             : 
    1361           0 :       xfree (issuer);
    1362           0 :       xfree (subject);
    1363           0 :       issuer = ksba_cert_get_issuer (subject_cert, 0);
    1364           0 :       subject = ksba_cert_get_subject (subject_cert, 0);
    1365             : 
    1366           0 :       if (!issuer)
    1367             :         {
    1368           0 :           do_list (1, listmode, listfp,  _("no issuer found in certificate"));
    1369           0 :           rc = gpg_error (GPG_ERR_BAD_CERT);
    1370           0 :           goto leave;
    1371             :         }
    1372             : 
    1373             : 
    1374             :       /* Is this a self-issued certificate (i.e. the root certificate)?  */
    1375           0 :       is_root = is_root_cert (subject_cert, issuer, subject);
    1376           0 :       if (is_root)
    1377             :         {
    1378           0 :           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           0 :           if (gpgsm_cert_has_well_known_private_key (subject_cert))
    1384             :             {
    1385           0 :               memset (rootca_flags, 0, sizeof *rootca_flags);
    1386           0 :               istrusted_rc = ((flags & VALIDATE_FLAG_STEED)
    1387           0 :                               ? 0 : gpg_error (GPG_ERR_NOT_TRUSTED));
    1388             :             }
    1389             :           else
    1390           0 :             istrusted_rc = gpgsm_agent_istrusted (ctrl, subject_cert, NULL,
    1391             :                                                   rootca_flags);
    1392           0 :           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           0 :           if (!(flags & VALIDATE_FLAG_STEED)
    1397           0 :               && has_validation_model_chain (subject_cert, listmode, listfp))
    1398           0 :             rootca_flags->chain_model = 1;
    1399             :         }
    1400             : 
    1401             : 
    1402             :       /* Check the validity period. */
    1403           0 :       if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
    1404           0 :         rc = check_validity_period_cm (current_time, check_time, subject_cert,
    1405             :                                        exptime, listmode, listfp,
    1406           0 :                                        (depth && is_root)? -1: depth);
    1407             :       else
    1408           0 :         rc = check_validity_period (current_time, subject_cert,
    1409             :                                     exptime, listmode, listfp,
    1410           0 :                                     (depth && is_root)? -1: depth);
    1411           0 :       if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED)
    1412           0 :         any_expired = 1;
    1413           0 :       else if (rc)
    1414           0 :         goto leave;
    1415             : 
    1416             : 
    1417             :       /* Assert that we understand all critical extensions. */
    1418           0 :       rc = unknown_criticals (subject_cert, listmode, listfp);
    1419           0 :       if (rc)
    1420           0 :         goto leave;
    1421             : 
    1422             :       /* Do a policy check. */
    1423           0 :       if (!opt.no_policy_check)
    1424             :         {
    1425           0 :           rc = check_cert_policy (subject_cert, listmode, listfp);
    1426           0 :           if (gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH)
    1427             :             {
    1428           0 :               any_no_policy_match = 1;
    1429           0 :               rc = 1;  /* Be on the safe side and set RC.  */
    1430             :             }
    1431           0 :           else if (rc)
    1432           0 :             goto leave;
    1433             :         }
    1434             : 
    1435             : 
    1436             :       /* If this is the root certificate we are at the end of the chain.  */
    1437           0 :       if (is_root)
    1438             :         {
    1439           0 :           if (!istrusted_rc)
    1440             :             ; /* No need to check the certificate for a trusted one. */
    1441           0 :           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           0 :               do_list (1, listmode, listfp,
    1446           0 :                        _("self-signed certificate has a BAD signature"));
    1447           0 :               if (DBG_X509)
    1448             :                 {
    1449           0 :                   gpgsm_dump_cert ("self-signing cert", subject_cert);
    1450             :                 }
    1451           0 :               rc = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN
    1452             :                                    : GPG_ERR_BAD_CERT);
    1453           0 :               goto leave;
    1454             :             }
    1455           0 :           if (!rootca_flags->relax)
    1456             :             {
    1457           0 :               rc = allowed_ca (ctrl, subject_cert, NULL, listmode, listfp);
    1458           0 :               if (rc)
    1459           0 :                 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           0 :           if (is_qualified == -1 && !(flags & VALIDATE_FLAG_STEED))
    1467             :             {
    1468             :               gpg_error_t err;
    1469             :               size_t buflen;
    1470             :               char buf[1];
    1471             : 
    1472           0 :               if (!ksba_cert_get_user_data (cert, "is_qualified",
    1473             :                                             &buf, sizeof (buf),
    1474           0 :                                             &buflen) && buflen)
    1475             :                 {
    1476             :                   /* We already checked this for this certificate,
    1477             :                      thus we simply take it from the user data. */
    1478           0 :                   is_qualified = !!*buf;
    1479             :                 }
    1480             :               else
    1481             :                 {
    1482             :                   /* Need to consult the list of root certificates for
    1483             :                      qualified signatures. */
    1484           0 :                   err = gpgsm_is_in_qualified_list (ctrl, subject_cert, NULL);
    1485           0 :                   if (!err)
    1486           0 :                     is_qualified = 1;
    1487           0 :                   else if ( gpg_err_code (err) == GPG_ERR_NOT_FOUND)
    1488           0 :                     is_qualified = 0;
    1489             :                   else
    1490           0 :                     log_error ("checking the list of qualified "
    1491             :                                "root certificates failed: %s\n",
    1492             :                                gpg_strerror (err));
    1493           0 :                   if ( is_qualified != -1 )
    1494             :                     {
    1495             :                       /* Cache the result but don't care too much
    1496             :                          about an error. */
    1497           0 :                       buf[0] = !!is_qualified;
    1498           0 :                       err = ksba_cert_set_user_data (subject_cert,
    1499             :                                                      "is_qualified", buf, 1);
    1500           0 :                       if (err)
    1501           0 :                         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           0 :           rc = istrusted_rc;
    1510           0 :           if (!rc)
    1511             :             ;
    1512           0 :           else if (gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
    1513             :             {
    1514           0 :               do_list (0, listmode, listfp,
    1515           0 :                        _("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           0 :               if ( !any_expired
    1524           0 :                    && !gpgsm_cert_has_well_known_private_key (subject_cert)
    1525           0 :                    && (!listmode || !already_asked_marktrusted (subject_cert))
    1526           0 :                    && ask_marktrusted (ctrl, subject_cert, listmode) )
    1527           0 :                 rc = 0;
    1528             :             }
    1529             :           else
    1530             :             {
    1531           0 :               log_error (_("checking the trust list failed: %s\n"),
    1532             :                          gpg_strerror (rc));
    1533             :             }
    1534             : 
    1535           0 :           if (rc)
    1536           0 :             goto leave;
    1537             : 
    1538             :           /* Check for revocations etc. */
    1539           0 :           if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
    1540             :             ;
    1541           0 :           else if ((flags & VALIDATE_FLAG_STEED))
    1542             :             ; /* Fixme: check revocations via DNS.  */
    1543           0 :           else if (opt.no_trusted_cert_crl_check || rootca_flags->relax)
    1544             :             ;
    1545             :           else
    1546           0 :             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           0 :           if (rc)
    1553           0 :             goto leave;
    1554             : 
    1555           0 :           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           0 :       if ((depth+1) > maxdepth)
    1561             :         {
    1562           0 :           do_list (1, listmode, listfp, _("certificate chain too long\n"));
    1563           0 :           rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
    1564           0 :           goto leave;
    1565             :         }
    1566             : 
    1567             :       /* Find the next cert up the tree. */
    1568           0 :       keydb_search_reset (kh);
    1569           0 :       rc = find_up (ctrl, kh, subject_cert, issuer, 0);
    1570           0 :       if (rc)
    1571             :         {
    1572           0 :           if (rc == -1)
    1573             :             {
    1574           0 :               do_list (0, listmode, listfp, _("issuer certificate not found"));
    1575           0 :               if (!listmode)
    1576             :                 {
    1577           0 :                   log_info ("issuer certificate: #/");
    1578           0 :                   gpgsm_dump_string (issuer);
    1579           0 :                   log_printf ("\n");
    1580             :                 }
    1581             :             }
    1582             :           else
    1583           0 :             log_error ("failed to find issuer's certificate: rc=%d\n", rc);
    1584           0 :           rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
    1585           0 :           goto leave;
    1586             :         }
    1587             : 
    1588           0 :       ksba_cert_release (issuer_cert); issuer_cert = NULL;
    1589           0 :       rc = keydb_get_cert (kh, &issuer_cert);
    1590           0 :       if (rc)
    1591             :         {
    1592           0 :           log_error ("keydb_get_cert() failed: rc=%d\n", rc);
    1593           0 :           rc = gpg_error (GPG_ERR_GENERAL);
    1594           0 :           goto leave;
    1595             :         }
    1596             : 
    1597             :     try_another_cert:
    1598           0 :       if (DBG_X509)
    1599             :         {
    1600           0 :           log_debug ("got issuer's certificate:\n");
    1601           0 :           gpgsm_dump_cert ("issuer", issuer_cert);
    1602             :         }
    1603             : 
    1604           0 :       rc = gpgsm_check_cert_sig (issuer_cert, subject_cert);
    1605           0 :       if (rc)
    1606             :         {
    1607           0 :           do_list (0, listmode, listfp, _("certificate has a BAD signature"));
    1608           0 :           if (DBG_X509)
    1609             :             {
    1610           0 :               gpgsm_dump_cert ("signing issuer", issuer_cert);
    1611           0 :               gpgsm_dump_cert ("signed subject", subject_cert);
    1612             :             }
    1613           0 :           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           0 :               rc = find_up (ctrl, kh, subject_cert, issuer, 1);
    1622           0 :               if (!rc)
    1623             :                 {
    1624             :                   ksba_cert_t tmp_cert;
    1625             : 
    1626           0 :                   rc = keydb_get_cert (kh, &tmp_cert);
    1627           0 :                   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           0 :                       ksba_cert_release (tmp_cert);
    1635             :                     }
    1636             :                   else
    1637             :                     {
    1638           0 :                       do_list (0, listmode, listfp,
    1639           0 :                                _("found another possible matching "
    1640             :                                  "CA certificate - trying again"));
    1641           0 :                       ksba_cert_release (issuer_cert);
    1642           0 :                       issuer_cert = tmp_cert;
    1643           0 :                       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           0 :           rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
    1651           0 :           goto leave;
    1652             :         }
    1653             : 
    1654           0 :       is_root = gpgsm_is_root_cert (issuer_cert);
    1655           0 :       istrusted_rc = -1;
    1656             : 
    1657             : 
    1658             :       /* Check that a CA is allowed to issue certificates. */
    1659             :       {
    1660             :         int chainlen;
    1661             : 
    1662           0 :         rc = allowed_ca (ctrl, issuer_cert, &chainlen, listmode, listfp);
    1663           0 :         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           0 :             if (is_root)
    1674             :               {
    1675           0 :                 if (gpgsm_cert_has_well_known_private_key (issuer_cert))
    1676             :                   {
    1677           0 :                     memset (rootca_flags, 0, sizeof *rootca_flags);
    1678           0 :                     istrusted_rc = ((flags & VALIDATE_FLAG_STEED)
    1679           0 :                                     ? 0 : gpg_error (GPG_ERR_NOT_TRUSTED));
    1680             :                   }
    1681             :                 else
    1682           0 :                   istrusted_rc = gpgsm_agent_istrusted
    1683             :                     (ctrl, issuer_cert, NULL, rootca_flags);
    1684             : 
    1685           0 :                 if (!istrusted_rc && rootca_flags->relax)
    1686             :                   {
    1687             :                     /* Ignore the error due to the relax flag.  */
    1688           0 :                     rc = 0;
    1689           0 :                     chainlen = -1;
    1690             :                   }
    1691             :               }
    1692             :           }
    1693           0 :         if (rc)
    1694           0 :           goto leave;
    1695           0 :         if (chainlen >= 0 && depth > chainlen)
    1696             :           {
    1697           0 :             do_list (1, listmode, listfp,
    1698           0 :                      _("certificate chain longer than allowed by CA (%d)"),
    1699             :                      chainlen);
    1700           0 :             rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
    1701           0 :             goto leave;
    1702             :           }
    1703             :       }
    1704             : 
    1705             :       /* Is the certificate allowed to sign other certificates. */
    1706           0 :       if (!listmode)
    1707             :         {
    1708           0 :           rc = gpgsm_cert_use_cert_p (issuer_cert);
    1709           0 :           if (rc)
    1710             :             {
    1711             :               char numbuf[50];
    1712           0 :               sprintf (numbuf, "%d", rc);
    1713           0 :               gpgsm_status2 (ctrl, STATUS_ERROR, "certcert.issuer.keyusage",
    1714             :                              numbuf, NULL);
    1715           0 :               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           0 :       if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
    1723           0 :         rc = 0;
    1724           0 :       else if ((flags & VALIDATE_FLAG_STEED))
    1725           0 :         rc = 0; /* Fixme: XXX */
    1726           0 :       else if (is_root && (opt.no_trusted_cert_crl_check
    1727           0 :                            || (!istrusted_rc && rootca_flags->relax)))
    1728           0 :         rc = 0;
    1729             :       else
    1730           0 :         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           0 :       if (rc)
    1736           0 :         goto leave;
    1737             : 
    1738             : 
    1739           0 :       if (opt.verbose && !listmode)
    1740           0 :         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           0 :       if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
    1747             :         {
    1748           0 :           rc = ksba_cert_get_validity (subject_cert, 0, check_time);
    1749           0 :           if (rc)
    1750             :             {
    1751             :               /* That will never happen as we have already checked
    1752             :                  this above.  */
    1753           0 :               BUG ();
    1754             :             }
    1755             :         }
    1756             : 
    1757             :       /* For the next round the current issuer becomes the new subject.  */
    1758           0 :       keydb_search_reset (kh);
    1759           0 :       ksba_cert_release (subject_cert);
    1760           0 :       subject_cert = issuer_cert;
    1761           0 :       issuer_cert = NULL;
    1762           0 :       depth++;
    1763           0 :     } /* End chain traversal. */
    1764             : 
    1765           0 :   if (!listmode && !opt.quiet)
    1766             :     {
    1767           0 :       if (opt.no_policy_check)
    1768           0 :         log_info ("policies not checked due to %s option\n",
    1769             :                   "--disable-policy-checks");
    1770           0 :       if (ctrl->offline || (opt.no_crl_check && !ctrl->use_ocsp))
    1771           0 :         log_info ("CRLs not checked due to %s option\n",
    1772           0 :                   ctrl->offline ? "offline" : "--disable-crl-checks");
    1773             :     }
    1774             : 
    1775           0 :   if (!rc)
    1776             :     { /* If we encountered an error somewhere during the checks, set
    1777             :          the error code to the most critical one */
    1778           0 :       if (any_revoked)
    1779           0 :         rc = gpg_error (GPG_ERR_CERT_REVOKED);
    1780           0 :       else if (any_expired)
    1781           0 :         rc = gpg_error (GPG_ERR_CERT_EXPIRED);
    1782           0 :       else if (any_no_crl)
    1783           0 :         rc = gpg_error (GPG_ERR_NO_CRL_KNOWN);
    1784           0 :       else if (any_crl_too_old)
    1785           0 :         rc = gpg_error (GPG_ERR_CRL_TOO_OLD);
    1786           0 :       else if (any_no_policy_match)
    1787           0 :         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           0 :   if (chain && chain->is_root)
    1796             :     {
    1797             :       gpg_error_t err;
    1798             :       chain_item_t ci;
    1799             : 
    1800           0 :       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           0 :           err = keydb_set_cert_flags (ctrl, ci->cert, 1, KEYBOX_FLAG_BLOB, 0,
    1808             :                                       KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
    1809           0 :           if (!ci->next && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
    1810             :             ;
    1811           0 :           else if (err)
    1812           0 :             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           0 :   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           0 :       buf[0] = !!is_qualified;
    1828             : 
    1829           0 :       for (ci = chain; ci; ci = ci->next)
    1830             :         {
    1831           0 :           err = ksba_cert_set_user_data (ci->cert, "is_qualified", buf, 1);
    1832           0 :           if (err)
    1833             :             {
    1834           0 :               log_error ("set_user_data(is_qualified) failed: %s\n",
    1835             :                          gpg_strerror (err));
    1836           0 :               if (!rc)
    1837           0 :                 rc = err;
    1838             :             }
    1839             :         }
    1840             :     }
    1841             : 
    1842             :   /* If auditing has been enabled, record what is in the chain.  */
    1843           0 :   if (ctrl->audit)
    1844             :     {
    1845             :       chain_item_t ci;
    1846             : 
    1847           0 :       audit_log (ctrl->audit, AUDIT_CHAIN_BEGIN);
    1848           0 :       for (ci = chain; ci; ci = ci->next)
    1849             :         {
    1850           0 :           audit_log_cert (ctrl->audit,
    1851           0 :                           ci->is_root? AUDIT_CHAIN_ROOTCERT : AUDIT_CHAIN_CERT,
    1852             :                           ci->cert, 0);
    1853             :         }
    1854           0 :       audit_log (ctrl->audit, AUDIT_CHAIN_END);
    1855             :     }
    1856             : 
    1857           0 :   if (r_exptime)
    1858           0 :     gnupg_copy_time (r_exptime, exptime);
    1859           0 :   xfree (issuer);
    1860           0 :   xfree (subject);
    1861           0 :   keydb_release (kh);
    1862           0 :   while (chain)
    1863             :     {
    1864           0 :       chain_item_t ci_next = chain->next;
    1865           0 :       ksba_cert_release (chain->cert);
    1866           0 :       xfree (chain);
    1867           0 :       chain = ci_next;
    1868             :     }
    1869           0 :   ksba_cert_release (issuer_cert);
    1870           0 :   ksba_cert_release (subject_cert);
    1871           0 :   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           0 : 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           0 :   if (!retflags)
    1898           0 :     retflags = &dummy_retflags;
    1899             : 
    1900             :   /* If the session requested a certain validation mode make sure the
    1901             :      corresponding flags are set.  */
    1902           0 :   if (ctrl->validation_model == 1)
    1903           0 :     flags |= VALIDATE_FLAG_CHAIN_MODEL;
    1904           0 :   else if (ctrl->validation_model == 2)
    1905           0 :     flags |= VALIDATE_FLAG_STEED;
    1906             : 
    1907             :   /* If the chain model was forced, set this immediately into
    1908             :      RETFLAGS.  */
    1909           0 :   *retflags = (flags & VALIDATE_FLAG_CHAIN_MODEL);
    1910             : 
    1911           0 :   memset (&rootca_flags, 0, sizeof rootca_flags);
    1912             : 
    1913           0 :   rc = do_validate_chain (ctrl, cert, checktime,
    1914             :                           r_exptime, listmode, listfp, flags,
    1915             :                           &rootca_flags);
    1916           0 :   if (!rc && (flags & VALIDATE_FLAG_STEED))
    1917             :     {
    1918           0 :       *retflags |= VALIDATE_FLAG_STEED;
    1919             :     }
    1920           0 :   else if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED
    1921           0 :       && !(flags & VALIDATE_FLAG_CHAIN_MODEL)
    1922           0 :       && (rootca_flags.valid && rootca_flags.chain_model))
    1923             :     {
    1924           0 :       do_list (0, listmode, listfp, _("switching to chain model"));
    1925           0 :       rc = do_validate_chain (ctrl, cert, checktime,
    1926             :                               r_exptime, listmode, listfp,
    1927             :                               (flags |= VALIDATE_FLAG_CHAIN_MODEL),
    1928             :                               &rootca_flags);
    1929           0 :       *retflags |= VALIDATE_FLAG_CHAIN_MODEL;
    1930             :     }
    1931             : 
    1932           0 :   if (opt.verbose)
    1933           0 :     do_list (0, listmode, listfp, _("validation model used: %s"),
    1934           0 :              (*retflags & VALIDATE_FLAG_STEED)?
    1935             :              "steed" :
    1936           0 :              (*retflags & VALIDATE_FLAG_CHAIN_MODEL)?
    1937           0 :              _("chain"):_("shell"));
    1938             : 
    1939           0 :   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           3 : gpgsm_basic_cert_check (ctrl_t ctrl, ksba_cert_t cert)
    1949             : {
    1950           3 :   int rc = 0;
    1951           3 :   char *issuer = NULL;
    1952           3 :   char *subject = NULL;
    1953             :   KEYDB_HANDLE kh;
    1954           3 :   ksba_cert_t issuer_cert = NULL;
    1955             : 
    1956           3 :   if (opt.no_chain_validation)
    1957             :     {
    1958           0 :       log_info ("WARNING: bypassing basic certificate checks\n");
    1959           0 :       return 0;
    1960             :     }
    1961             : 
    1962           3 :   kh = keydb_new ();
    1963           3 :   if (!kh)
    1964             :     {
    1965           0 :       log_error (_("failed to allocate keyDB handle\n"));
    1966           0 :       rc = gpg_error (GPG_ERR_GENERAL);
    1967           0 :       goto leave;
    1968             :     }
    1969             : 
    1970           3 :   issuer = ksba_cert_get_issuer (cert, 0);
    1971           3 :   subject = ksba_cert_get_subject (cert, 0);
    1972           3 :   if (!issuer)
    1973             :     {
    1974           0 :       log_error ("no issuer found in certificate\n");
    1975           0 :       rc = gpg_error (GPG_ERR_BAD_CERT);
    1976           0 :       goto leave;
    1977             :     }
    1978             : 
    1979           3 :   if (is_root_cert (cert, issuer, subject))
    1980             :     {
    1981           3 :       rc = gpgsm_check_cert_sig (cert, cert);
    1982           3 :       if (rc)
    1983             :         {
    1984           0 :           log_error ("self-signed certificate has a BAD signature: %s\n",
    1985             :                      gpg_strerror (rc));
    1986           0 :           if (DBG_X509)
    1987             :             {
    1988           0 :               gpgsm_dump_cert ("self-signing cert", cert);
    1989             :             }
    1990           0 :           rc = gpg_error (GPG_ERR_BAD_CERT);
    1991           0 :           goto leave;
    1992             :         }
    1993             :     }
    1994             :   else
    1995             :     {
    1996             :       /* Find the next cert up the tree. */
    1997           0 :       keydb_search_reset (kh);
    1998           0 :       rc = find_up (ctrl, kh, cert, issuer, 0);
    1999           0 :       if (rc)
    2000             :         {
    2001           0 :           if (rc == -1)
    2002             :             {
    2003           0 :               log_info ("issuer certificate (#/");
    2004           0 :               gpgsm_dump_string (issuer);
    2005           0 :               log_printf (") not found\n");
    2006             :             }
    2007             :           else
    2008           0 :             log_error ("failed to find issuer's certificate: rc=%d\n", rc);
    2009           0 :           rc = gpg_error (GPG_ERR_MISSING_ISSUER_CERT);
    2010           0 :           goto leave;
    2011             :         }
    2012             : 
    2013           0 :       ksba_cert_release (issuer_cert); issuer_cert = NULL;
    2014           0 :       rc = keydb_get_cert (kh, &issuer_cert);
    2015           0 :       if (rc)
    2016             :         {
    2017           0 :           log_error ("keydb_get_cert() failed: rc=%d\n", rc);
    2018           0 :           rc = gpg_error (GPG_ERR_GENERAL);
    2019           0 :           goto leave;
    2020             :         }
    2021             : 
    2022           0 :       rc = gpgsm_check_cert_sig (issuer_cert, cert);
    2023           0 :       if (rc)
    2024             :         {
    2025           0 :           log_error ("certificate has a BAD signature: %s\n",
    2026             :                      gpg_strerror (rc));
    2027           0 :           if (DBG_X509)
    2028             :             {
    2029           0 :               gpgsm_dump_cert ("signing issuer", issuer_cert);
    2030           0 :               gpgsm_dump_cert ("signed subject", cert);
    2031             :             }
    2032           0 :           rc = gpg_error (GPG_ERR_BAD_CERT);
    2033           0 :           goto leave;
    2034             :         }
    2035           0 :       if (opt.verbose)
    2036           0 :         log_info (_("certificate is good\n"));
    2037             :     }
    2038             : 
    2039             :  leave:
    2040           3 :   xfree (issuer);
    2041           3 :   xfree (subject);
    2042           3 :   keydb_release (kh);
    2043           3 :   ksba_cert_release (issuer_cert);
    2044           3 :   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           0 : 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           0 :   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           0 :   if (!chainlen)
    2076           0 :     chainlen = &dummy_chainlen;
    2077             : 
    2078           0 :   *chainlen = 0;
    2079           0 :   err = ksba_cert_get_user_data (cert, "regtp_ca_chainlen",
    2080             :                                  &buf, sizeof (buf), &buflen);
    2081           0 :   if (!err)
    2082             :     {
    2083             :       /* Got info. */
    2084           0 :       if (buflen < 2 || !*buf)
    2085           0 :         return 0; /* Nothing found. */
    2086           0 :       *chainlen = buf[1];
    2087           0 :       return 1; /* This is a regtp CA. */
    2088             :     }
    2089           0 :   else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
    2090             :     {
    2091           0 :       log_error ("ksba_cert_get_user_data(%s) failed: %s\n",
    2092             :                  "regtp_ca_chainlen", gpg_strerror (err));
    2093           0 :       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           0 :   memset (&array, 0, sizeof array);
    2103             : 
    2104           0 :   depth = 0;
    2105           0 :   ksba_cert_ref (cert);
    2106           0 :   array[depth++] = cert;
    2107           0 :   ksba_cert_ref (cert);
    2108           0 :   while (depth < DIM(array) && !(rc=gpgsm_walk_cert_chain (ctrl, cert, &next)))
    2109             :     {
    2110           0 :       ksba_cert_release (cert);
    2111           0 :       ksba_cert_ref (next);
    2112           0 :       array[depth++] = next;
    2113           0 :       cert = next;
    2114             :     }
    2115           0 :   ksba_cert_release (cert);
    2116           0 :   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           0 :   if (!gpgsm_is_in_qualified_list (NULL, array[depth-1], country)
    2125           0 :       && !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           0 :       err = ksba_cert_set_user_data (array[depth-1], "regtp_ca_chainlen",
    2130             :                                      "\x01\x01", 2);
    2131           0 :       if (!err && depth > 1)
    2132           0 :         err = ksba_cert_set_user_data (array[depth-2], "regtp_ca_chainlen",
    2133             :                                        "\x01\x00", 2);
    2134           0 :       if (err)
    2135           0 :         log_error ("ksba_set_user_data(%s) failed: %s\n",
    2136             :                    "regtp_ca_chainlen", gpg_strerror (err));
    2137           0 :       for (i=0; i < depth; i++)
    2138           0 :         ksba_cert_release (array[i]);
    2139           0 :       *chainlen = (depth>1? 0:1);
    2140           0 :       return 1;
    2141             :     }
    2142             : 
    2143             :  leave:
    2144             :   /* Nothing special with this certificate. Mark the target
    2145             :      certificate anyway to avoid duplicate lookups. */
    2146           0 :   err = ksba_cert_set_user_data (cert, "regtp_ca_chainlen", "", 1);
    2147           0 :   if (err)
    2148           0 :     log_error ("ksba_set_user_data(%s) failed: %s\n",
    2149             :                "regtp_ca_chainlen", gpg_strerror (err));
    2150           0 :   for (i=0; i < depth; i++)
    2151           0 :     ksba_cert_release (array[i]);
    2152           0 :   return 0;
    2153             : }

Generated by: LCOV version 1.11