Reworked passing of envars to Pinentry.
[gnupg.git] / sm / certchain.c
blobddf4ece8fbfaf0c31d108654d8f9a8df96265651
1 /* certchain.c - certificate chain validation
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2008 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
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.
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.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
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>
31 #define JNLIB_NEED_LOG_LOGV /* We need log_logv. */
33 #include "gpgsm.h"
34 #include <gcrypt.h>
35 #include <ksba.h>
37 #include "keydb.h"
38 #include "../kbx/keybox.h" /* for KEYBOX_FLAG_* */
39 #include "i18n.h"
40 #include "tlv.h"
43 /* Object to keep track of certain root certificates. */
44 struct marktrusted_info_s
46 struct marktrusted_info_s *next;
47 unsigned char fpr[20];
49 static struct marktrusted_info_s *marktrusted_info;
52 /* While running the validation function we want to keep track of the
53 certificates in the chain. This type is used for that. */
54 struct chain_item_s
56 struct chain_item_s *next;
57 ksba_cert_t cert; /* The certificate. */
58 int is_root; /* The certificate is the root certificate. */
60 typedef struct chain_item_s *chain_item_t;
63 static int is_root_cert (ksba_cert_t cert,
64 const char *issuerdn, const char *subjectdn);
65 static int get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen);
68 /* This function returns true if we already asked during this session
69 whether the root certificate CERT shall be marked as trusted. */
70 static int
71 already_asked_marktrusted (ksba_cert_t cert)
73 unsigned char fpr[20];
74 struct marktrusted_info_s *r;
76 gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
77 /* No context switches in the loop! */
78 for (r=marktrusted_info; r; r= r->next)
79 if (!memcmp (r->fpr, fpr, 20))
80 return 1;
81 return 0;
84 /* Flag certificate CERT as already asked whether it shall be marked
85 as trusted. */
86 static void
87 set_already_asked_marktrusted (ksba_cert_t cert)
89 unsigned char fpr[20];
90 struct marktrusted_info_s *r;
92 gpgsm_get_fingerprint (cert, GCRY_MD_SHA1, fpr, NULL);
93 for (r=marktrusted_info; r; r= r->next)
94 if (!memcmp (r->fpr, fpr, 20))
95 return; /* Already marked. */
96 r = xtrycalloc (1, sizeof *r);
97 if (!r)
98 return;
99 memcpy (r->fpr, fpr, 20);
100 r->next = marktrusted_info;
101 marktrusted_info = r;
104 /* If LISTMODE is true, print FORMAT using LISTMODE to FP. If
105 LISTMODE is false, use the string to print an log_info or, if
106 IS_ERROR is true, and log_error. */
107 static void
108 do_list (int is_error, int listmode, estream_t fp, const char *format, ...)
110 va_list arg_ptr;
112 va_start (arg_ptr, format) ;
113 if (listmode)
115 if (fp)
117 es_fputs (" [", fp);
118 es_vfprintf (fp, format, arg_ptr);
119 es_fputs ("]\n", fp);
122 else
124 log_logv (is_error? JNLIB_LOG_ERROR: JNLIB_LOG_INFO, format, arg_ptr);
125 log_printf ("\n");
127 va_end (arg_ptr);
130 /* Return 0 if A and B are equal. */
131 static int
132 compare_certs (ksba_cert_t a, ksba_cert_t b)
134 const unsigned char *img_a, *img_b;
135 size_t len_a, len_b;
137 img_a = ksba_cert_get_image (a, &len_a);
138 if (!img_a)
139 return 1;
140 img_b = ksba_cert_get_image (b, &len_b);
141 if (!img_b)
142 return 1;
143 return !(len_a == len_b && !memcmp (img_a, img_b, len_a));
147 /* Return true if CERT has the validityModel extensions and defines
148 the use of the chain model. */
149 static int
150 has_validation_model_chain (ksba_cert_t cert, int listmode, estream_t listfp)
152 gpg_error_t err;
153 int idx, yes;
154 const char *oid;
155 size_t off, derlen, objlen, hdrlen;
156 const unsigned char *der;
157 int class, tag, constructed, ndef;
158 char *oidbuf;
160 for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
161 &oid, NULL, &off, &derlen));idx++)
162 if (!strcmp (oid, "1.3.6.1.4.1.8301.3.5") )
163 break;
164 if (err)
165 return 0; /* Not found. */
166 der = ksba_cert_get_image (cert, NULL);
167 if (!der)
169 err = gpg_error (GPG_ERR_INV_OBJ); /* Oops */
170 goto leave;
172 der += off;
174 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
175 &ndef, &objlen, &hdrlen);
176 if (!err && (objlen > derlen || tag != TAG_SEQUENCE))
177 err = gpg_error (GPG_ERR_INV_OBJ);
178 if (err)
179 goto leave;
180 derlen = objlen;
181 err = parse_ber_header (&der, &derlen, &class, &tag, &constructed,
182 &ndef, &objlen, &hdrlen);
183 if (!err && (objlen > derlen || tag != TAG_OBJECT_ID))
184 err = gpg_error (GPG_ERR_INV_OBJ);
185 if (err)
186 goto leave;
187 oidbuf = ksba_oid_to_str (der, objlen);
188 if (!oidbuf)
190 err = gpg_error_from_syserror ();
191 goto leave;
194 if (opt.verbose)
195 do_list (0, listmode, listfp,
196 _("validation model requested by certificate: %s"),
197 !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1")? _("chain") :
198 !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.2")? _("shell") :
199 /* */ oidbuf);
200 yes = !strcmp (oidbuf, "1.3.6.1.4.1.8301.3.5.1");
201 ksba_free (oidbuf);
202 return yes;
205 leave:
206 log_error ("error parsing validityModel: %s\n", gpg_strerror (err));
207 return 0;
212 static int
213 unknown_criticals (ksba_cert_t cert, int listmode, estream_t fp)
215 static const char *known[] = {
216 "2.5.29.15", /* keyUsage */
217 "2.5.29.17", /* subjectAltName
218 Japanese DoCoMo certs mark them as critical. PKIX
219 only requires them as critical if subjectName is
220 empty. I don't know whether our code gracefully
221 handles such empry subjectNames but that is
222 another story. */
223 "2.5.29.19", /* basic Constraints */
224 "2.5.29.32", /* certificatePolicies */
225 "2.5.29.37", /* extendedKeyUsage - handled by certlist.c */
226 "1.3.6.1.4.1.8301.3.5", /* validityModel - handled here. */
227 NULL
229 int rc = 0, i, idx, crit;
230 const char *oid;
231 gpg_error_t err;
233 for (idx=0; !(err=ksba_cert_get_extension (cert, idx,
234 &oid, &crit, NULL, NULL));idx++)
236 if (!crit)
237 continue;
238 for (i=0; known[i] && strcmp (known[i],oid); i++)
240 if (!known[i])
242 do_list (1, listmode, fp,
243 _("critical certificate extension %s is not supported"),
244 oid);
245 rc = gpg_error (GPG_ERR_UNSUPPORTED_CERT);
248 /* We ignore the error codes EOF as well as no-value. The later will
249 occur for certificates with no extensions at all. */
250 if (err
251 && gpg_err_code (err) != GPG_ERR_EOF
252 && gpg_err_code (err) != GPG_ERR_NO_VALUE)
253 rc = err;
255 return rc;
259 /* Check whether CERT is an allowed certificate. This requires that
260 CERT matches all requirements for such a CA, i.e. the
261 BasicConstraints extension. The function returns 0 on success and
262 the awlloed length of the chain at CHAINLEN. */
263 static int
264 allowed_ca (ctrl_t ctrl,
265 ksba_cert_t cert, int *chainlen, int listmode, estream_t fp)
267 gpg_error_t err;
268 int flag;
270 err = ksba_cert_is_ca (cert, &flag, chainlen);
271 if (err)
272 return err;
273 if (!flag)
275 if (get_regtp_ca_info (ctrl, cert, chainlen))
277 /* Note that dirmngr takes a different way to cope with such
278 certs. */
279 return 0; /* RegTP issued certificate. */
282 do_list (1, listmode, fp,_("issuer certificate is not marked as a CA"));
283 return gpg_error (GPG_ERR_BAD_CA_CERT);
285 return 0;
289 static int
290 check_cert_policy (ksba_cert_t cert, int listmode, estream_t fplist)
292 gpg_error_t err;
293 char *policies;
294 FILE *fp;
295 int any_critical;
297 err = ksba_cert_get_cert_policies (cert, &policies);
298 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
299 return 0; /* No policy given. */
300 if (err)
301 return err;
303 /* STRING is a line delimited list of certificate policies as stored
304 in the certificate. The line itself is colon delimited where the
305 first field is the OID of the policy and the second field either
306 N or C for normal or critical extension */
308 if (opt.verbose > 1 && !listmode)
309 log_info ("certificate's policy list: %s\n", policies);
311 /* The check is very minimal but won't give false positives */
312 any_critical = !!strstr (policies, ":C");
314 if (!opt.policy_file)
316 xfree (policies);
317 if (any_critical)
319 do_list (1, listmode, fplist,
320 _("critical marked policy without configured policies"));
321 return gpg_error (GPG_ERR_NO_POLICY_MATCH);
323 return 0;
326 fp = fopen (opt.policy_file, "r");
327 if (!fp)
329 if (opt.verbose || errno != ENOENT)
330 log_info (_("failed to open `%s': %s\n"),
331 opt.policy_file, strerror (errno));
332 xfree (policies);
333 /* With no critical policies this is only a warning */
334 if (!any_critical)
336 if (!opt.quiet)
337 do_list (0, listmode, fplist,
338 _("note: non-critical certificate policy not allowed"));
339 return 0;
341 do_list (1, listmode, fplist,
342 _("certificate policy not allowed"));
343 return gpg_error (GPG_ERR_NO_POLICY_MATCH);
346 for (;;)
348 int c;
349 char *p, line[256];
350 char *haystack, *allowed;
352 /* read line */
355 if (!fgets (line, DIM(line)-1, fp) )
357 gpg_error_t tmperr = gpg_error (gpg_err_code_from_errno (errno));
359 xfree (policies);
360 if (feof (fp))
362 fclose (fp);
363 /* With no critical policies this is only a warning */
364 if (!any_critical)
366 do_list (0, listmode, fplist,
367 _("note: non-critical certificate policy not allowed"));
368 return 0;
370 do_list (1, listmode, fplist,
371 _("certificate policy not allowed"));
372 return gpg_error (GPG_ERR_NO_POLICY_MATCH);
374 fclose (fp);
375 return tmperr;
378 if (!*line || line[strlen(line)-1] != '\n')
380 /* eat until end of line */
381 while ( (c=getc (fp)) != EOF && c != '\n')
383 fclose (fp);
384 xfree (policies);
385 return gpg_error (*line? GPG_ERR_LINE_TOO_LONG
386 : GPG_ERR_INCOMPLETE_LINE);
389 /* Allow for empty lines and spaces */
390 for (p=line; spacep (p); p++)
393 while (!*p || *p == '\n' || *p == '#');
395 /* parse line */
396 for (allowed=line; spacep (allowed); allowed++)
398 p = strpbrk (allowed, " :\n");
399 if (!*p || p == allowed)
401 fclose (fp);
402 xfree (policies);
403 return gpg_error (GPG_ERR_CONFIGURATION);
405 *p = 0; /* strip the rest of the line */
406 /* See whether we find ALLOWED (which is an OID) in POLICIES */
407 for (haystack=policies; (p=strstr (haystack, allowed)); haystack = p+1)
409 if ( !(p == policies || p[-1] == '\n') )
410 continue; /* Does not match the begin of a line. */
411 if (p[strlen (allowed)] != ':')
412 continue; /* The length does not match. */
413 /* Yep - it does match so return okay. */
414 fclose (fp);
415 xfree (policies);
416 return 0;
422 /* Helper function for find_up. This resets the key handle and search
423 for an issuer ISSUER with a subjectKeyIdentifier of KEYID. Returns
424 0 on success or -1 when not found. */
425 static int
426 find_up_search_by_keyid (KEYDB_HANDLE kh,
427 const char *issuer, ksba_sexp_t keyid)
429 int rc;
430 ksba_cert_t cert = NULL;
431 ksba_sexp_t subj = NULL;
433 keydb_search_reset (kh);
434 while (!(rc = keydb_search_subject (kh, issuer)))
436 ksba_cert_release (cert); cert = NULL;
437 rc = keydb_get_cert (kh, &cert);
438 if (rc)
440 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
441 rc = -1;
442 break;
444 xfree (subj);
445 if (!ksba_cert_get_subj_key_id (cert, NULL, &subj))
447 if (!cmp_simple_canon_sexp (keyid, subj))
448 break; /* Found matching cert. */
452 ksba_cert_release (cert);
453 xfree (subj);
454 return rc? -1:0;
458 static void
459 find_up_store_certs_cb (void *cb_value, ksba_cert_t cert)
461 if (keydb_store_cert (cert, 1, NULL))
462 log_error ("error storing issuer certificate as ephemeral\n");
463 ++*(int*)cb_value;
467 /* Helper for find_up(). Locate the certificate for ISSUER using an
468 external lookup. KH is the keydb context we are currently using.
469 On success 0 is returned and the certificate may be retrieved from
470 the keydb using keydb_get_cert(). KEYID is the keyIdentifier from
471 the AKI or NULL. */
472 static int
473 find_up_external (ctrl_t ctrl, KEYDB_HANDLE kh,
474 const char *issuer, ksba_sexp_t keyid)
476 int rc;
477 strlist_t names = NULL;
478 int count = 0;
479 char *pattern;
480 const char *s;
482 if (opt.verbose)
483 log_info (_("looking up issuer at external location\n"));
484 /* The Dirmngr process is confused about unknown attributes. As a
485 quick and ugly hack we locate the CN and use the issuer string
486 starting at this attribite. Fixme: we should have far better
487 parsing for external lookups in the Dirmngr. */
488 s = strstr (issuer, "CN=");
489 if (!s || s == issuer || s[-1] != ',')
490 s = issuer;
491 pattern = xtrymalloc (strlen (s)+2);
492 if (!pattern)
493 return gpg_error_from_syserror ();
494 strcpy (stpcpy (pattern, "/"), s);
495 add_to_strlist (&names, pattern);
496 xfree (pattern);
498 rc = gpgsm_dirmngr_lookup (ctrl, names, 0, find_up_store_certs_cb, &count);
499 free_strlist (names);
501 if (opt.verbose)
502 log_info (_("number of issuers matching: %d\n"), count);
503 if (rc)
505 log_error ("external key lookup failed: %s\n", gpg_strerror (rc));
506 rc = -1;
508 else if (!count)
509 rc = -1;
510 else
512 int old;
513 /* The issuers are currently stored in the ephemeral key DB, so
514 we temporary switch to ephemeral mode. */
515 old = keydb_set_ephemeral (kh, 1);
516 if (keyid)
517 rc = find_up_search_by_keyid (kh, issuer, keyid);
518 else
520 keydb_search_reset (kh);
521 rc = keydb_search_subject (kh, issuer);
523 keydb_set_ephemeral (kh, old);
525 return rc;
529 /* Helper for find_up(). Ask the dirmngr for the certificate for
530 ISSUER with optional SERIALNO. KH is the keydb context we are
531 currently using. With SUBJECT_MODE set, ISSUER is searched as the
532 subject. On success 0 is returned and the certificate is available
533 in the ephemeral DB. */
534 static int
535 find_up_dirmngr (ctrl_t ctrl, KEYDB_HANDLE kh,
536 ksba_sexp_t serialno, const char *issuer, int subject_mode)
538 int rc;
539 strlist_t names = NULL;
540 int count = 0;
541 char *pattern;
543 (void)kh;
545 if (opt.verbose)
546 log_info (_("looking up issuer from the Dirmngr cache\n"));
547 if (subject_mode)
549 pattern = xtrymalloc (strlen (issuer)+2);
550 if (pattern)
551 strcpy (stpcpy (pattern, "/"), issuer);
553 else if (serialno)
554 pattern = gpgsm_format_sn_issuer (serialno, issuer);
555 else
557 pattern = xtrymalloc (strlen (issuer)+3);
558 if (pattern)
559 strcpy (stpcpy (pattern, "#/"), issuer);
561 if (!pattern)
562 return gpg_error_from_syserror ();
563 add_to_strlist (&names, pattern);
564 xfree (pattern);
566 rc = gpgsm_dirmngr_lookup (ctrl, names, 1, find_up_store_certs_cb, &count);
567 free_strlist (names);
569 if (opt.verbose)
570 log_info (_("number of matching certificates: %d\n"), count);
571 if (rc && !opt.quiet)
572 log_info (_("dirmngr cache-only key lookup failed: %s\n"),
573 gpg_strerror (rc));
574 return (!rc && count)? 0 : -1;
579 /* Locate issuing certificate for CERT. ISSUER is the name of the
580 issuer used as a fallback if the other methods don't work. If
581 FIND_NEXT is true, the function shall return the next possible
582 issuer. The certificate itself is not directly returned but a
583 keydb_get_cert on the keyDb context KH will return it. Returns 0
584 on success, -1 if not found or an error code. */
585 static int
586 find_up (ctrl_t ctrl, KEYDB_HANDLE kh,
587 ksba_cert_t cert, const char *issuer, int find_next)
589 ksba_name_t authid;
590 ksba_sexp_t authidno;
591 ksba_sexp_t keyid;
592 int rc = -1;
594 if (!ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno))
596 const char *s = ksba_name_enum (authid, 0);
597 if (s && *authidno)
599 rc = keydb_search_issuer_sn (kh, s, authidno);
600 if (rc)
601 keydb_search_reset (kh);
603 /* In case of an error, try to get the certificate from the
604 dirmngr. That is done by trying to put that certifcate
605 into the ephemeral DB and let the code below do the
606 actual retrieve. Thus there is no error checking.
607 Skipped in find_next mode as usual. */
608 if (rc == -1 && !find_next)
609 find_up_dirmngr (ctrl, kh, authidno, s, 0);
611 /* In case of an error try the ephemeral DB. We can't do
612 that in find_next mode because we can't keep the search
613 state then. */
614 if (rc == -1 && !find_next)
616 int old = keydb_set_ephemeral (kh, 1);
617 if (!old)
619 rc = keydb_search_issuer_sn (kh, s, authidno);
620 if (rc)
621 keydb_search_reset (kh);
623 keydb_set_ephemeral (kh, old);
625 if (rc)
626 rc = -1; /* Need to make sure to have this error code. */
629 if (rc == -1 && keyid && !find_next)
631 /* Not found by AIK.issuer_sn. Lets try the AIK.ki
632 instead. Loop over all certificates with that issuer as
633 subject and stop for the one with a matching
634 subjectKeyIdentifier. */
635 /* Fixme: Should we also search in the dirmngr? */
636 rc = find_up_search_by_keyid (kh, issuer, keyid);
637 if (rc)
639 int old = keydb_set_ephemeral (kh, 1);
640 if (!old)
641 rc = find_up_search_by_keyid (kh, issuer, keyid);
642 keydb_set_ephemeral (kh, old);
644 if (rc)
645 rc = -1; /* Need to make sure to have this error code. */
648 /* If we still didn't found it, try to find it via the subject
649 from the dirmngr-cache. */
650 if (rc == -1 && !find_next)
652 if (!find_up_dirmngr (ctrl, kh, NULL, issuer, 1))
654 int old = keydb_set_ephemeral (kh, 1);
655 if (keyid)
656 rc = find_up_search_by_keyid (kh, issuer, keyid);
657 else
659 keydb_search_reset (kh);
660 rc = keydb_search_subject (kh, issuer);
662 keydb_set_ephemeral (kh, old);
664 if (rc)
665 rc = -1; /* Need to make sure to have this error code. */
668 /* If we still didn't found it, try an external lookup. */
669 if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
670 rc = find_up_external (ctrl, kh, issuer, keyid);
672 /* Print a note so that the user does not feel too helpless when
673 an issuer certificate was found and gpgsm prints BAD
674 signature because it is not the correct one. */
675 if (rc == -1 && opt.quiet)
677 else if (rc == -1)
679 log_info ("%sissuer certificate ", find_next?"next ":"");
680 if (keyid)
682 log_printf ("{");
683 gpgsm_dump_serial (keyid);
684 log_printf ("} ");
686 if (authidno)
688 log_printf ("(#");
689 gpgsm_dump_serial (authidno);
690 log_printf ("/");
691 gpgsm_dump_string (s);
692 log_printf (") ");
694 log_printf ("not found using authorityKeyIdentifier\n");
696 else if (rc)
697 log_error ("failed to find authorityKeyIdentifier: rc=%d\n", rc);
698 xfree (keyid);
699 ksba_name_release (authid);
700 xfree (authidno);
703 if (rc) /* Not found via authorithyKeyIdentifier, try regular issuer name. */
704 rc = keydb_search_subject (kh, issuer);
705 if (rc == -1 && !find_next)
707 int old;
709 /* Also try to get it from the Dirmngr cache. The function
710 merely puts it into the ephemeral database. */
711 find_up_dirmngr (ctrl, kh, NULL, issuer, 0);
713 /* Not found, let us see whether we have one in the ephemeral key DB. */
714 old = keydb_set_ephemeral (kh, 1);
715 if (!old)
717 keydb_search_reset (kh);
718 rc = keydb_search_subject (kh, issuer);
720 keydb_set_ephemeral (kh, old);
723 /* Still not found. If enabled, try an external lookup. */
724 if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
725 rc = find_up_external (ctrl, kh, issuer, NULL);
727 return rc;
731 /* Return the next certificate up in the chain starting at START.
732 Returns -1 when there are no more certificates. */
734 gpgsm_walk_cert_chain (ctrl_t ctrl, ksba_cert_t start, ksba_cert_t *r_next)
736 int rc = 0;
737 char *issuer = NULL;
738 char *subject = NULL;
739 KEYDB_HANDLE kh = keydb_new (0);
741 *r_next = NULL;
742 if (!kh)
744 log_error (_("failed to allocated keyDB handle\n"));
745 rc = gpg_error (GPG_ERR_GENERAL);
746 goto leave;
749 issuer = ksba_cert_get_issuer (start, 0);
750 subject = ksba_cert_get_subject (start, 0);
751 if (!issuer)
753 log_error ("no issuer found in certificate\n");
754 rc = gpg_error (GPG_ERR_BAD_CERT);
755 goto leave;
757 if (!subject)
759 log_error ("no subject found in certificate\n");
760 rc = gpg_error (GPG_ERR_BAD_CERT);
761 goto leave;
764 if (is_root_cert (start, issuer, subject))
766 rc = -1; /* we are at the root */
767 goto leave;
770 rc = find_up (ctrl, kh, start, issuer, 0);
771 if (rc)
773 /* It is quite common not to have a certificate, so better don't
774 print an error here. */
775 if (rc != -1 && opt.verbose > 1)
776 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
777 rc = gpg_error (GPG_ERR_MISSING_CERT);
778 goto leave;
781 rc = keydb_get_cert (kh, r_next);
782 if (rc)
784 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
785 rc = gpg_error (GPG_ERR_GENERAL);
788 leave:
789 xfree (issuer);
790 xfree (subject);
791 keydb_release (kh);
792 return rc;
796 /* Helper for gpgsm_is_root_cert. This one is used if the subject and
797 issuer DNs are already known. */
798 static int
799 is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn)
801 gpg_error_t err;
802 int result = 0;
803 ksba_sexp_t serialno;
804 ksba_sexp_t ak_keyid;
805 ksba_name_t ak_name;
806 ksba_sexp_t ak_sn;
807 const char *ak_name_str;
808 ksba_sexp_t subj_keyid = NULL;
810 if (!issuerdn || !subjectdn)
811 return 0; /* No. */
813 if (strcmp (issuerdn, subjectdn))
814 return 0; /* No. */
816 err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn);
817 if (err)
819 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
820 return 1; /* Yes. Without a authorityKeyIdentifier this needs
821 to be the Root certifcate (our trust anchor). */
822 log_error ("error getting authorityKeyIdentifier: %s\n",
823 gpg_strerror (err));
824 return 0; /* Well, it is broken anyway. Return No. */
827 serialno = ksba_cert_get_serial (cert);
828 if (!serialno)
830 log_error ("error getting serialno: %s\n", gpg_strerror (err));
831 goto leave;
834 /* Check whether the auth name's matches the issuer name+sn. If
835 that is the case this is a root certificate. */
836 ak_name_str = ksba_name_enum (ak_name, 0);
837 if (ak_name_str
838 && !strcmp (ak_name_str, issuerdn)
839 && !cmp_simple_canon_sexp (ak_sn, serialno))
841 result = 1; /* Right, CERT is self-signed. */
842 goto leave;
845 /* Similar for the ak_keyid. */
846 if (ak_keyid && !ksba_cert_get_subj_key_id (cert, NULL, &subj_keyid)
847 && !cmp_simple_canon_sexp (ak_keyid, subj_keyid))
849 result = 1; /* Right, CERT is self-signed. */
850 goto leave;
854 leave:
855 ksba_free (subj_keyid);
856 ksba_free (ak_keyid);
857 ksba_name_release (ak_name);
858 ksba_free (ak_sn);
859 ksba_free (serialno);
860 return result;
865 /* Check whether the CERT is a root certificate. Returns True if this
866 is the case. */
868 gpgsm_is_root_cert (ksba_cert_t cert)
870 char *issuer;
871 char *subject;
872 int yes;
874 issuer = ksba_cert_get_issuer (cert, 0);
875 subject = ksba_cert_get_subject (cert, 0);
876 yes = is_root_cert (cert, issuer, subject);
877 xfree (issuer);
878 xfree (subject);
879 return yes;
883 /* This is a helper for gpgsm_validate_chain. */
884 static gpg_error_t
885 is_cert_still_valid (ctrl_t ctrl, int force_ocsp, int lm, estream_t fp,
886 ksba_cert_t subject_cert, ksba_cert_t issuer_cert,
887 int *any_revoked, int *any_no_crl, int *any_crl_too_old)
889 gpg_error_t err;
891 if (opt.no_crl_check && !ctrl->use_ocsp)
892 return 0;
894 err = gpgsm_dirmngr_isvalid (ctrl,
895 subject_cert, issuer_cert,
896 force_ocsp? 2 : !!ctrl->use_ocsp);
897 if (err)
899 if (!lm)
900 gpgsm_cert_log_name (NULL, subject_cert);
901 switch (gpg_err_code (err))
903 case GPG_ERR_CERT_REVOKED:
904 do_list (1, lm, fp, _("certificate has been revoked"));
905 *any_revoked = 1;
906 /* Store that in the keybox so that key listings are able to
907 return the revoked flag. We don't care about error,
908 though. */
909 keydb_set_cert_flags (subject_cert, 1, KEYBOX_FLAG_VALIDITY, 0,
910 ~0, VALIDITY_REVOKED);
911 break;
913 case GPG_ERR_NO_CRL_KNOWN:
914 do_list (1, lm, fp, _("no CRL found for certificate"));
915 *any_no_crl = 1;
916 break;
918 case GPG_ERR_NO_DATA:
919 do_list (1, lm, fp, _("the status of the certificate is unknown"));
920 *any_no_crl = 1;
921 break;
923 case GPG_ERR_CRL_TOO_OLD:
924 do_list (1, lm, fp, _("the available CRL is too old"));
925 if (!lm)
926 log_info (_("please make sure that the "
927 "\"dirmngr\" is properly installed\n"));
928 *any_crl_too_old = 1;
929 break;
931 default:
932 do_list (1, lm, fp, _("checking the CRL failed: %s"),
933 gpg_strerror (err));
934 return err;
937 return 0;
941 /* Helper for gpgsm_validate_chain to check the validity period of
942 SUBJECT_CERT. The caller needs to pass EXPTIME which will be
943 updated to the nearest expiration time seen. A DEPTH of 0 indicates
944 the target certifciate, -1 the final root certificate and other
945 values intermediate certificates. */
946 static gpg_error_t
947 check_validity_period (ksba_isotime_t current_time,
948 ksba_cert_t subject_cert,
949 ksba_isotime_t exptime,
950 int listmode, estream_t listfp, int depth)
952 gpg_error_t err;
953 ksba_isotime_t not_before, not_after;
955 err = ksba_cert_get_validity (subject_cert, 0, not_before);
956 if (!err)
957 err = ksba_cert_get_validity (subject_cert, 1, not_after);
958 if (err)
960 do_list (1, listmode, listfp,
961 _("certificate with invalid validity: %s"), gpg_strerror (err));
962 return gpg_error (GPG_ERR_BAD_CERT);
965 if (*not_after)
967 if (!*exptime)
968 gnupg_copy_time (exptime, not_after);
969 else if (strcmp (not_after, exptime) < 0 )
970 gnupg_copy_time (exptime, not_after);
973 if (*not_before && strcmp (current_time, not_before) < 0 )
975 do_list (1, listmode, listfp,
976 depth == 0 ? _("certificate not yet valid") :
977 depth == -1 ? _("root certificate not yet valid") :
978 /* other */ _("intermediate certificate not yet valid"));
979 if (!listmode)
981 log_info (" (valid from ");
982 dump_isotime (not_before);
983 log_printf (")\n");
985 return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
988 if (*not_after && strcmp (current_time, not_after) > 0 )
990 do_list (opt.ignore_expiration?0:1, listmode, listfp,
991 depth == 0 ? _("certificate has expired") :
992 depth == -1 ? _("root certificate has expired") :
993 /* other */ _("intermediate certificate has expired"));
994 if (!listmode)
996 log_info (" (expired at ");
997 dump_isotime (not_after);
998 log_printf (")\n");
1000 if (opt.ignore_expiration)
1001 log_info ("WARNING: ignoring expiration\n");
1002 else
1003 return gpg_error (GPG_ERR_CERT_EXPIRED);
1006 return 0;
1009 /* This is a variant of check_validity_period used with the chain
1010 model. The dextra contraint here is that notBefore and notAfter
1011 must exists and if the additional argument CHECK_TIME is given this
1012 time is used to check the validity period of SUBJECT_CERT. */
1013 static gpg_error_t
1014 check_validity_period_cm (ksba_isotime_t current_time,
1015 ksba_isotime_t check_time,
1016 ksba_cert_t subject_cert,
1017 ksba_isotime_t exptime,
1018 int listmode, estream_t listfp, int depth)
1020 gpg_error_t err;
1021 ksba_isotime_t not_before, not_after;
1023 err = ksba_cert_get_validity (subject_cert, 0, not_before);
1024 if (!err)
1025 err = ksba_cert_get_validity (subject_cert, 1, not_after);
1026 if (err)
1028 do_list (1, listmode, listfp,
1029 _("certificate with invalid validity: %s"), gpg_strerror (err));
1030 return gpg_error (GPG_ERR_BAD_CERT);
1032 if (!*not_before || !*not_after)
1034 do_list (1, listmode, listfp,
1035 _("required certificate attributes missing: %s%s%s"),
1036 !*not_before? "notBefore":"",
1037 (!*not_before && !*not_after)? ", ":"",
1038 !*not_before? "notAfter":"");
1039 return gpg_error (GPG_ERR_BAD_CERT);
1041 if (strcmp (not_before, not_after) > 0 )
1043 do_list (1, listmode, listfp,
1044 _("certificate with invalid validity"));
1045 log_info (" (valid from ");
1046 dump_isotime (not_before);
1047 log_printf (" expired at ");
1048 dump_isotime (not_after);
1049 log_printf (")\n");
1050 return gpg_error (GPG_ERR_BAD_CERT);
1053 if (!*exptime)
1054 gnupg_copy_time (exptime, not_after);
1055 else if (strcmp (not_after, exptime) < 0 )
1056 gnupg_copy_time (exptime, not_after);
1058 if (strcmp (current_time, not_before) < 0 )
1060 do_list (1, listmode, listfp,
1061 depth == 0 ? _("certificate not yet valid") :
1062 depth == -1 ? _("root certificate not yet valid") :
1063 /* other */ _("intermediate certificate not yet valid"));
1064 if (!listmode)
1066 log_info (" (valid from ");
1067 dump_isotime (not_before);
1068 log_printf (")\n");
1070 return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
1073 if (*check_time
1074 && (strcmp (check_time, not_before) < 0
1075 || strcmp (check_time, not_after) > 0))
1077 /* Note that we don't need a case for the root certificate
1078 because its own consitency has already been checked. */
1079 do_list(opt.ignore_expiration?0:1, listmode, listfp,
1080 depth == 0 ?
1081 _("signature not created during lifetime of certificate") :
1082 depth == 1 ?
1083 _("certificate not created during lifetime of issuer") :
1084 _("intermediate certificate not created during lifetime "
1085 "of issuer"));
1086 if (!listmode)
1088 log_info (depth== 0? _(" ( signature created at ") :
1089 /* */ _(" (certificate created at ") );
1090 dump_isotime (check_time);
1091 log_printf (")\n");
1092 log_info (depth==0? _(" (certificate valid from ") :
1093 /* */ _(" ( issuer valid from ") );
1094 dump_isotime (not_before);
1095 log_info (" to ");
1096 dump_isotime (not_after);
1097 log_printf (")\n");
1099 if (opt.ignore_expiration)
1100 log_info ("WARNING: ignoring expiration\n");
1101 else
1102 return gpg_error (GPG_ERR_CERT_EXPIRED);
1105 return 0;
1110 /* Ask the user whether he wants to mark the certificate CERT trusted.
1111 Returns true if the CERT is the trusted. We also check whether the
1112 agent is at all enabled to allow marktrusted and don't call it in
1113 this session again if it is not. */
1114 static int
1115 ask_marktrusted (ctrl_t ctrl, ksba_cert_t cert, int listmode)
1117 static int no_more_questions;
1118 int rc;
1119 char *fpr;
1120 int success = 0;
1122 fpr = gpgsm_get_fingerprint_string (cert, GCRY_MD_SHA1);
1123 log_info (_("fingerprint=%s\n"), fpr? fpr : "?");
1124 xfree (fpr);
1126 if (no_more_questions)
1127 rc = gpg_error (GPG_ERR_NOT_SUPPORTED);
1128 else
1129 rc = gpgsm_agent_marktrusted (ctrl, cert);
1130 if (!rc)
1132 log_info (_("root certificate has now been marked as trusted\n"));
1133 success = 1;
1135 else if (!listmode)
1137 gpgsm_dump_cert ("issuer", cert);
1138 log_info ("after checking the fingerprint, you may want "
1139 "to add it manually to the list of trusted certificates.\n");
1142 if (gpg_err_code (rc) == GPG_ERR_NOT_SUPPORTED)
1144 if (!no_more_questions)
1145 log_info (_("interactive marking as trusted "
1146 "not enabled in gpg-agent\n"));
1147 no_more_questions = 1;
1149 else if (gpg_err_code (rc) == GPG_ERR_CANCELED)
1151 log_info (_("interactive marking as trusted "
1152 "disabled for this session\n"));
1153 no_more_questions = 1;
1155 else
1156 set_already_asked_marktrusted (cert);
1158 return success;
1164 /* Validate a chain and optionally return the nearest expiration time
1165 in R_EXPTIME. With LISTMODE set to 1 a special listmode is
1166 activated where only information about the certificate is printed
1167 to LISTFP and no output is send to the usual log stream. If
1168 CHECKTIME_ARG is set, it is used only in the chain model instead of the
1169 current time.
1171 Defined flag bits
1173 VALIDATE_FLAG_NO_DIRMNGR - Do not do any dirmngr isvalid checks.
1174 VALIDATE_FLAG_CHAIN_MODEL - Check according to chain model.
1176 static int
1177 do_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime_arg,
1178 ksba_isotime_t r_exptime,
1179 int listmode, estream_t listfp, unsigned int flags,
1180 struct rootca_flags_s *rootca_flags)
1182 int rc = 0, depth, maxdepth;
1183 char *issuer = NULL;
1184 char *subject = NULL;
1185 KEYDB_HANDLE kh = NULL;
1186 ksba_cert_t subject_cert = NULL, issuer_cert = NULL;
1187 ksba_isotime_t current_time;
1188 ksba_isotime_t check_time;
1189 ksba_isotime_t exptime;
1190 int any_expired = 0;
1191 int any_revoked = 0;
1192 int any_no_crl = 0;
1193 int any_crl_too_old = 0;
1194 int any_no_policy_match = 0;
1195 int is_qualified = -1; /* Indicates whether the certificate stems
1196 from a qualified root certificate.
1197 -1 = unknown, 0 = no, 1 = yes. */
1198 chain_item_t chain = NULL; /* A list of all certificates in the chain. */
1201 gnupg_get_isotime (current_time);
1203 if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1205 if (!strcmp (checktime_arg, "19700101T000000"))
1207 do_list (1, listmode, listfp,
1208 _("WARNING: creation time of signature not known - "
1209 "assuming current time"));
1210 gnupg_copy_time (check_time, current_time);
1212 else
1213 gnupg_copy_time (check_time, checktime_arg);
1215 else
1216 *check_time = 0;
1218 if (r_exptime)
1219 *r_exptime = 0;
1220 *exptime = 0;
1222 if (opt.no_chain_validation && !listmode)
1224 log_info ("WARNING: bypassing certificate chain validation\n");
1225 return 0;
1228 kh = keydb_new (0);
1229 if (!kh)
1231 log_error (_("failed to allocated keyDB handle\n"));
1232 rc = gpg_error (GPG_ERR_GENERAL);
1233 goto leave;
1236 if (DBG_X509 && !listmode)
1237 gpgsm_dump_cert ("target", cert);
1239 subject_cert = cert;
1240 ksba_cert_ref (subject_cert);
1241 maxdepth = 50;
1242 depth = 0;
1244 for (;;)
1246 int is_root;
1247 gpg_error_t istrusted_rc = -1;
1249 /* Put the certificate on our list. */
1251 chain_item_t ci;
1253 ci = xtrycalloc (1, sizeof *ci);
1254 if (!ci)
1256 rc = gpg_error_from_syserror ();
1257 goto leave;
1259 ksba_cert_ref (subject_cert);
1260 ci->cert = subject_cert;
1261 ci->next = chain;
1262 chain = ci;
1265 xfree (issuer);
1266 xfree (subject);
1267 issuer = ksba_cert_get_issuer (subject_cert, 0);
1268 subject = ksba_cert_get_subject (subject_cert, 0);
1270 if (!issuer)
1272 do_list (1, listmode, listfp, _("no issuer found in certificate"));
1273 rc = gpg_error (GPG_ERR_BAD_CERT);
1274 goto leave;
1278 /* Is this a self-issued certificate (i.e. the root certificate)? */
1279 is_root = is_root_cert (subject_cert, issuer, subject);
1280 if (is_root)
1282 chain->is_root = 1;
1283 /* Check early whether the certificate is listed as trusted.
1284 We used to do this only later but changed it to call the
1285 check right here so that we can access special flags
1286 associated with that specific root certificate. */
1287 istrusted_rc = gpgsm_agent_istrusted (ctrl, subject_cert, NULL,
1288 rootca_flags);
1289 audit_log_cert (ctrl->audit, AUDIT_ROOT_TRUSTED,
1290 subject_cert, istrusted_rc);
1291 /* If the chain model extended attribute is used, make sure
1292 that our chain model flag is set. */
1293 if (has_validation_model_chain (subject_cert, listmode, listfp))
1294 rootca_flags->chain_model = 1;
1298 /* Check the validity period. */
1299 if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1300 rc = check_validity_period_cm (current_time, check_time, subject_cert,
1301 exptime, listmode, listfp,
1302 (depth && is_root)? -1: depth);
1303 else
1304 rc = check_validity_period (current_time, subject_cert,
1305 exptime, listmode, listfp,
1306 (depth && is_root)? -1: depth);
1307 if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED)
1309 any_expired = 1;
1310 rc = 0;
1312 else if (rc)
1313 goto leave;
1316 /* Assert that we understand all critical extensions. */
1317 rc = unknown_criticals (subject_cert, listmode, listfp);
1318 if (rc)
1319 goto leave;
1321 /* Do a policy check. */
1322 if (!opt.no_policy_check)
1324 rc = check_cert_policy (subject_cert, listmode, listfp);
1325 if (gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH)
1327 any_no_policy_match = 1;
1328 rc = 1;
1330 else if (rc)
1331 goto leave;
1335 /* If this is the root certificate we are at the end of the chain. */
1336 if (is_root)
1338 if (!istrusted_rc)
1339 ; /* No need to check the certificate for a trusted one. */
1340 else if (gpgsm_check_cert_sig (subject_cert, subject_cert) )
1342 /* We only check the signature if the certificate is not
1343 trusted for better diagnostics. */
1344 do_list (1, listmode, listfp,
1345 _("self-signed certificate has a BAD signature"));
1346 if (DBG_X509)
1348 gpgsm_dump_cert ("self-signing cert", subject_cert);
1350 rc = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN
1351 : GPG_ERR_BAD_CERT);
1352 goto leave;
1354 if (!rootca_flags->relax)
1356 rc = allowed_ca (ctrl, subject_cert, NULL, listmode, listfp);
1357 if (rc)
1358 goto leave;
1362 /* Set the flag for qualified signatures. This flag is
1363 deduced from a list of root certificates allowed for
1364 qualified signatures. */
1365 if (is_qualified == -1)
1367 gpg_error_t err;
1368 size_t buflen;
1369 char buf[1];
1371 if (!ksba_cert_get_user_data (cert, "is_qualified",
1372 &buf, sizeof (buf),
1373 &buflen) && buflen)
1375 /* We already checked this for this certificate,
1376 thus we simply take it from the user data. */
1377 is_qualified = !!*buf;
1379 else
1381 /* Need to consult the list of root certificates for
1382 qualified signatures. */
1383 err = gpgsm_is_in_qualified_list (ctrl, subject_cert, NULL);
1384 if (!err)
1385 is_qualified = 1;
1386 else if ( gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1387 is_qualified = 0;
1388 else
1389 log_error ("checking the list of qualified "
1390 "root certificates failed: %s\n",
1391 gpg_strerror (err));
1392 if ( is_qualified != -1 )
1394 /* Cache the result but don't care too much
1395 about an error. */
1396 buf[0] = !!is_qualified;
1397 err = ksba_cert_set_user_data (subject_cert,
1398 "is_qualified", buf, 1);
1399 if (err)
1400 log_error ("set_user_data(is_qualified) failed: %s\n",
1401 gpg_strerror (err));
1407 /* Act on the check for a trusted root certificates. */
1408 rc = istrusted_rc;
1409 if (!rc)
1411 else if (gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
1413 do_list (0, listmode, listfp,
1414 _("root certificate is not marked trusted"));
1415 /* If we already figured out that the certificate is
1416 expired it does not make much sense to ask the user
1417 whether we wants to trust the root certificate. We
1418 should do this only if the certificate under question
1419 will then be usable. */
1420 if ( !any_expired
1421 && (!listmode || !already_asked_marktrusted (subject_cert))
1422 && ask_marktrusted (ctrl, subject_cert, listmode) )
1423 rc = 0;
1425 else
1427 log_error (_("checking the trust list failed: %s\n"),
1428 gpg_strerror (rc));
1431 if (rc)
1432 goto leave;
1434 /* Check for revocations etc. */
1435 if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
1437 else if (opt.no_trusted_cert_crl_check || rootca_flags->relax)
1439 else
1440 rc = is_cert_still_valid (ctrl,
1441 (flags & VALIDATE_FLAG_CHAIN_MODEL),
1442 listmode, listfp,
1443 subject_cert, subject_cert,
1444 &any_revoked, &any_no_crl,
1445 &any_crl_too_old);
1446 if (rc)
1447 goto leave;
1449 break; /* Okay: a self-signed certicate is an end-point. */
1450 } /* End is_root. */
1453 /* Take care that the chain does not get too long. */
1454 if ((depth+1) > maxdepth)
1456 do_list (1, listmode, listfp, _("certificate chain too long\n"));
1457 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1458 goto leave;
1461 /* Find the next cert up the tree. */
1462 keydb_search_reset (kh);
1463 rc = find_up (ctrl, kh, subject_cert, issuer, 0);
1464 if (rc)
1466 if (rc == -1)
1468 do_list (0, listmode, listfp, _("issuer certificate not found"));
1469 if (!listmode)
1471 log_info ("issuer certificate: #/");
1472 gpgsm_dump_string (issuer);
1473 log_printf ("\n");
1476 else
1477 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
1478 rc = gpg_error (GPG_ERR_MISSING_CERT);
1479 goto leave;
1482 ksba_cert_release (issuer_cert); issuer_cert = NULL;
1483 rc = keydb_get_cert (kh, &issuer_cert);
1484 if (rc)
1486 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
1487 rc = gpg_error (GPG_ERR_GENERAL);
1488 goto leave;
1491 try_another_cert:
1492 if (DBG_X509)
1494 log_debug ("got issuer's certificate:\n");
1495 gpgsm_dump_cert ("issuer", issuer_cert);
1498 rc = gpgsm_check_cert_sig (issuer_cert, subject_cert);
1499 if (rc)
1501 do_list (0, listmode, listfp, _("certificate has a BAD signature"));
1502 if (DBG_X509)
1504 gpgsm_dump_cert ("signing issuer", issuer_cert);
1505 gpgsm_dump_cert ("signed subject", subject_cert);
1507 if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
1509 /* We now try to find other issuer certificates which
1510 might have been used. This is required because some
1511 CAs are reusing the issuer and subject DN for new
1512 root certificates. */
1513 /* FIXME: Do this only if we don't have an
1514 AKI.keyIdentifier */
1515 rc = find_up (ctrl, kh, subject_cert, issuer, 1);
1516 if (!rc)
1518 ksba_cert_t tmp_cert;
1520 rc = keydb_get_cert (kh, &tmp_cert);
1521 if (rc || !compare_certs (issuer_cert, tmp_cert))
1523 /* The find next did not work or returned an
1524 identical certificate. We better stop here
1525 to avoid infinite checks. */
1526 rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
1527 ksba_cert_release (tmp_cert);
1529 else
1531 do_list (0, listmode, listfp,
1532 _("found another possible matching "
1533 "CA certificate - trying again"));
1534 ksba_cert_release (issuer_cert);
1535 issuer_cert = tmp_cert;
1536 goto try_another_cert;
1541 /* We give a more descriptive error code than the one
1542 returned from the signature checking. */
1543 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1544 goto leave;
1547 is_root = gpgsm_is_root_cert (issuer_cert);
1548 istrusted_rc = -1;
1551 /* Check that a CA is allowed to issue certificates. */
1553 int chainlen;
1555 rc = allowed_ca (ctrl, issuer_cert, &chainlen, listmode, listfp);
1556 if (rc)
1558 /* Not allowed. Check whether this is a trusted root
1559 certificate and whether we allow special exceptions.
1560 We could carry the result of the test over to the
1561 regular root check at the top of the loop but for
1562 clarity we won't do that. Given that the majority of
1563 certificates carry proper BasicContraints our way of
1564 overriding an error in the way is justified for
1565 performance reasons. */
1566 if (is_root)
1568 istrusted_rc = gpgsm_agent_istrusted (ctrl, issuer_cert, NULL,
1569 rootca_flags);
1570 if (!istrusted_rc && rootca_flags->relax)
1572 /* Ignore the error due to the relax flag. */
1573 rc = 0;
1574 chainlen = -1;
1578 if (rc)
1579 goto leave;
1580 if (chainlen >= 0 && depth > chainlen)
1582 do_list (1, listmode, listfp,
1583 _("certificate chain longer than allowed by CA (%d)"),
1584 chainlen);
1585 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1586 goto leave;
1590 /* Is the certificate allowed to sign other certificates. */
1591 if (!listmode)
1593 rc = gpgsm_cert_use_cert_p (issuer_cert);
1594 if (rc)
1596 char numbuf[50];
1597 sprintf (numbuf, "%d", rc);
1598 gpgsm_status2 (ctrl, STATUS_ERROR, "certcert.issuer.keyusage",
1599 numbuf, NULL);
1600 goto leave;
1604 /* Check for revocations etc. Note that for a root certificate
1605 this test is done a second time later. This should eventually
1606 be fixed. */
1607 if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
1608 rc = 0;
1609 else if (is_root && (opt.no_trusted_cert_crl_check
1610 || (!istrusted_rc && rootca_flags->relax)))
1611 rc = 0;
1612 else
1613 rc = is_cert_still_valid (ctrl,
1614 (flags & VALIDATE_FLAG_CHAIN_MODEL),
1615 listmode, listfp,
1616 subject_cert, issuer_cert,
1617 &any_revoked, &any_no_crl, &any_crl_too_old);
1618 if (rc)
1619 goto leave;
1622 if (opt.verbose && !listmode)
1623 log_info (depth == 0 ? _("certificate is good\n") :
1624 !is_root ? _("intermediate certificate is good\n") :
1625 /* other */ _("root certificate is good\n"));
1627 /* Under the chain model the next check time is the creation
1628 time of the subject certificate. */
1629 if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1631 rc = ksba_cert_get_validity (subject_cert, 0, check_time);
1632 if (rc)
1634 /* That will never happen as we have already checked
1635 this above. */
1636 BUG ();
1640 /* For the next round the current issuer becomes the new subject. */
1641 keydb_search_reset (kh);
1642 ksba_cert_release (subject_cert);
1643 subject_cert = issuer_cert;
1644 issuer_cert = NULL;
1645 depth++;
1646 } /* End chain traversal. */
1648 if (!listmode && !opt.quiet)
1650 if (opt.no_policy_check)
1651 log_info ("policies not checked due to %s option\n",
1652 "--disable-policy-checks");
1653 if (opt.no_crl_check && !ctrl->use_ocsp)
1654 log_info ("CRLs not checked due to %s option\n",
1655 "--disable-crl-checks");
1658 if (!rc)
1659 { /* If we encountered an error somewhere during the checks, set
1660 the error code to the most critical one */
1661 if (any_revoked)
1662 rc = gpg_error (GPG_ERR_CERT_REVOKED);
1663 else if (any_expired)
1664 rc = gpg_error (GPG_ERR_CERT_EXPIRED);
1665 else if (any_no_crl)
1666 rc = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1667 else if (any_crl_too_old)
1668 rc = gpg_error (GPG_ERR_CRL_TOO_OLD);
1669 else if (any_no_policy_match)
1670 rc = gpg_error (GPG_ERR_NO_POLICY_MATCH);
1673 leave:
1674 /* If we have traversed a complete chain up to the root we will
1675 reset the ephemeral flag for all these certificates. This is done
1676 regardless of any error because those errors may only be
1677 transient. */
1678 if (chain && chain->is_root)
1680 gpg_error_t err;
1681 chain_item_t ci;
1683 for (ci = chain; ci; ci = ci->next)
1685 /* Note that it is possible for the last certificate in the
1686 chain (i.e. our target certificate) that it has not yet
1687 been stored in the keybox and thus the flag can't be set.
1688 We ignore this error becuase it will later be stored
1689 anyway. */
1690 err = keydb_set_cert_flags (ci->cert, 1, KEYBOX_FLAG_BLOB, 0,
1691 KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
1692 if (!ci->next && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1694 else if (err)
1695 log_error ("clearing ephemeral flag failed: %s\n",
1696 gpg_strerror (err));
1700 /* If we have figured something about the qualified signature
1701 capability of the certificate under question, store the result as
1702 user data in all certificates of the chain. We do this even if the
1703 validation itself failed. */
1704 if (is_qualified != -1)
1706 gpg_error_t err;
1707 chain_item_t ci;
1708 char buf[1];
1710 buf[0] = !!is_qualified;
1712 for (ci = chain; ci; ci = ci->next)
1714 err = ksba_cert_set_user_data (ci->cert, "is_qualified", buf, 1);
1715 if (err)
1717 log_error ("set_user_data(is_qualified) failed: %s\n",
1718 gpg_strerror (err));
1719 if (!rc)
1720 rc = err;
1725 /* If auditing has been enabled, record what is in the chain. */
1726 if (ctrl->audit)
1728 chain_item_t ci;
1730 audit_log (ctrl->audit, AUDIT_CHAIN_BEGIN);
1731 for (ci = chain; ci; ci = ci->next)
1733 audit_log_cert (ctrl->audit,
1734 ci->is_root? AUDIT_CHAIN_ROOTCERT : AUDIT_CHAIN_CERT,
1735 ci->cert, 0);
1737 audit_log (ctrl->audit, AUDIT_CHAIN_END);
1740 if (r_exptime)
1741 gnupg_copy_time (r_exptime, exptime);
1742 xfree (issuer);
1743 xfree (subject);
1744 keydb_release (kh);
1745 while (chain)
1747 chain_item_t ci_next = chain->next;
1748 ksba_cert_release (chain->cert);
1749 xfree (chain);
1750 chain = ci_next;
1752 ksba_cert_release (issuer_cert);
1753 ksba_cert_release (subject_cert);
1754 return rc;
1758 /* Validate a certificate chain. For a description see
1759 do_validate_chain. This function is a wrapper to handle a root
1760 certificate with the chain_model flag set. If RETFLAGS is not
1761 NULL, flags indicating now the verification was done are stored
1762 there. The only defined flag for RETFLAGS is
1763 VALIDATE_FLAG_CHAIN_MODEL.
1765 If you are verifying a signature you should set CHECKTIME to the
1766 creation time of the signature. If your are verifying a
1767 certificate, set it nil (i.e. the empty string). If the creation
1768 date of the signature is not known use the special date
1769 "19700101T000000" which is treated in a special way here. */
1771 gpgsm_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime,
1772 ksba_isotime_t r_exptime,
1773 int listmode, estream_t listfp, unsigned int flags,
1774 unsigned int *retflags)
1776 int rc;
1777 struct rootca_flags_s rootca_flags;
1778 unsigned int dummy_retflags;
1780 if (!retflags)
1781 retflags = &dummy_retflags;
1783 if (ctrl->validation_model == 1)
1784 flags |= VALIDATE_FLAG_CHAIN_MODEL;
1786 *retflags = (flags & VALIDATE_FLAG_CHAIN_MODEL);
1787 memset (&rootca_flags, 0, sizeof rootca_flags);
1789 rc = do_validate_chain (ctrl, cert, checktime,
1790 r_exptime, listmode, listfp, flags,
1791 &rootca_flags);
1792 if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED
1793 && !(flags & VALIDATE_FLAG_CHAIN_MODEL)
1794 && (rootca_flags.valid && rootca_flags.chain_model))
1796 do_list (0, listmode, listfp, _("switching to chain model"));
1797 rc = do_validate_chain (ctrl, cert, checktime,
1798 r_exptime, listmode, listfp,
1799 (flags |= VALIDATE_FLAG_CHAIN_MODEL),
1800 &rootca_flags);
1801 *retflags |= VALIDATE_FLAG_CHAIN_MODEL;
1804 if (opt.verbose)
1805 do_list (0, listmode, listfp, _("validation model used: %s"),
1806 (*retflags & VALIDATE_FLAG_CHAIN_MODEL)?
1807 _("chain"):_("shell"));
1809 return rc;
1813 /* Check that the given certificate is valid but DO NOT check any
1814 constraints. We assume that the issuers certificate is already in
1815 the DB and that this one is valid; which it should be because it
1816 has been checked using this function. */
1818 gpgsm_basic_cert_check (ctrl_t ctrl, ksba_cert_t cert)
1820 int rc = 0;
1821 char *issuer = NULL;
1822 char *subject = NULL;
1823 KEYDB_HANDLE kh;
1824 ksba_cert_t issuer_cert = NULL;
1826 if (opt.no_chain_validation)
1828 log_info ("WARNING: bypassing basic certificate checks\n");
1829 return 0;
1832 kh = keydb_new (0);
1833 if (!kh)
1835 log_error (_("failed to allocated keyDB handle\n"));
1836 rc = gpg_error (GPG_ERR_GENERAL);
1837 goto leave;
1840 issuer = ksba_cert_get_issuer (cert, 0);
1841 subject = ksba_cert_get_subject (cert, 0);
1842 if (!issuer)
1844 log_error ("no issuer found in certificate\n");
1845 rc = gpg_error (GPG_ERR_BAD_CERT);
1846 goto leave;
1849 if (is_root_cert (cert, issuer, subject))
1851 rc = gpgsm_check_cert_sig (cert, cert);
1852 if (rc)
1854 log_error ("self-signed certificate has a BAD signature: %s\n",
1855 gpg_strerror (rc));
1856 if (DBG_X509)
1858 gpgsm_dump_cert ("self-signing cert", cert);
1860 rc = gpg_error (GPG_ERR_BAD_CERT);
1861 goto leave;
1864 else
1866 /* Find the next cert up the tree. */
1867 keydb_search_reset (kh);
1868 rc = find_up (ctrl, kh, cert, issuer, 0);
1869 if (rc)
1871 if (rc == -1)
1873 log_info ("issuer certificate (#/");
1874 gpgsm_dump_string (issuer);
1875 log_printf (") not found\n");
1877 else
1878 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
1879 rc = gpg_error (GPG_ERR_MISSING_CERT);
1880 goto leave;
1883 ksba_cert_release (issuer_cert); issuer_cert = NULL;
1884 rc = keydb_get_cert (kh, &issuer_cert);
1885 if (rc)
1887 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
1888 rc = gpg_error (GPG_ERR_GENERAL);
1889 goto leave;
1892 rc = gpgsm_check_cert_sig (issuer_cert, cert);
1893 if (rc)
1895 log_error ("certificate has a BAD signature: %s\n",
1896 gpg_strerror (rc));
1897 if (DBG_X509)
1899 gpgsm_dump_cert ("signing issuer", issuer_cert);
1900 gpgsm_dump_cert ("signed subject", cert);
1902 rc = gpg_error (GPG_ERR_BAD_CERT);
1903 goto leave;
1905 if (opt.verbose)
1906 log_info (_("certificate is good\n"));
1909 leave:
1910 xfree (issuer);
1911 xfree (subject);
1912 keydb_release (kh);
1913 ksba_cert_release (issuer_cert);
1914 return rc;
1919 /* Check whether the certificate CERT has been issued by the German
1920 authority for qualified signature. They do not set the
1921 basicConstraints and thus we need this workaround. It works by
1922 looking up the root certificate and checking whether that one is
1923 listed as a qualified certificate for Germany.
1925 We also try to cache this data but as long as don't keep a
1926 reference to the certificate this won't be used.
1928 Returns: True if CERT is a RegTP issued CA cert (i.e. the root
1929 certificate itself or one of the CAs). In that case CHAINLEN will
1930 receive the length of the chain which is either 0 or 1.
1932 static int
1933 get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen)
1935 gpg_error_t err;
1936 ksba_cert_t next;
1937 int rc = 0;
1938 int i, depth;
1939 char country[3];
1940 ksba_cert_t array[4];
1941 char buf[2];
1942 size_t buflen;
1943 int dummy_chainlen;
1945 if (!chainlen)
1946 chainlen = &dummy_chainlen;
1948 *chainlen = 0;
1949 err = ksba_cert_get_user_data (cert, "regtp_ca_chainlen",
1950 &buf, sizeof (buf), &buflen);
1951 if (!err)
1953 /* Got info. */
1954 if (buflen < 2 || !*buf)
1955 return 0; /* Nothing found. */
1956 *chainlen = buf[1];
1957 return 1; /* This is a regtp CA. */
1959 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1961 log_error ("ksba_cert_get_user_data(%s) failed: %s\n",
1962 "regtp_ca_chainlen", gpg_strerror (err));
1963 return 0; /* Nothing found. */
1966 /* Need to gather the info. This requires to walk up the chain
1967 until we have found the root. Because we are only interested in
1968 German Bundesnetzagentur (former RegTP) derived certificates 3
1969 levels are enough. (The German signature law demands a 3 tier
1970 hierachy; thus there is only one CA between the EE and the Root
1971 CA.) */
1972 memset (&array, 0, sizeof array);
1974 depth = 0;
1975 ksba_cert_ref (cert);
1976 array[depth++] = cert;
1977 ksba_cert_ref (cert);
1978 while (depth < DIM(array) && !(rc=gpgsm_walk_cert_chain (ctrl, cert, &next)))
1980 ksba_cert_release (cert);
1981 ksba_cert_ref (next);
1982 array[depth++] = next;
1983 cert = next;
1985 ksba_cert_release (cert);
1986 if (rc != -1 || !depth || depth == DIM(array) )
1988 /* We did not reached the root. */
1989 goto leave;
1992 /* If this is a German signature law issued certificate, we store
1993 additional additional information. */
1994 if (!gpgsm_is_in_qualified_list (NULL, array[depth-1], country)
1995 && !strcmp (country, "de"))
1997 /* Setting the pathlen for the root CA and the CA flag for the
1998 next one is all what we need to do. */
1999 err = ksba_cert_set_user_data (array[depth-1], "regtp_ca_chainlen",
2000 "\x01\x01", 2);
2001 if (!err && depth > 1)
2002 err = ksba_cert_set_user_data (array[depth-2], "regtp_ca_chainlen",
2003 "\x01\x00", 2);
2004 if (err)
2005 log_error ("ksba_set_user_data(%s) failed: %s\n",
2006 "regtp_ca_chainlen", gpg_strerror (err));
2007 for (i=0; i < depth; i++)
2008 ksba_cert_release (array[i]);
2009 *chainlen = (depth>1? 0:1);
2010 return 1;
2013 leave:
2014 /* Nothing special with this certificate. Mark the target
2015 certificate anyway to avoid duplicate lookups. */
2016 err = ksba_cert_set_user_data (cert, "regtp_ca_chainlen", "", 1);
2017 if (err)
2018 log_error ("ksba_set_user_data(%s) failed: %s\n",
2019 "regtp_ca_chainlen", gpg_strerror (err));
2020 for (i=0; i < depth; i++)
2021 ksba_cert_release (array[i]);
2022 return 0;