2008-05-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / sm / certchain.c
blob03b020e33ad3440a34a00ca556ea0a347af4107a
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 if (opt.verbose)
544 log_info (_("looking up issuer from the Dirmngr cache\n"));
545 if (subject_mode)
547 pattern = xtrymalloc (strlen (issuer)+2);
548 if (pattern)
549 strcpy (stpcpy (pattern, "/"), issuer);
551 else if (serialno)
552 pattern = gpgsm_format_sn_issuer (serialno, issuer);
553 else
555 pattern = xtrymalloc (strlen (issuer)+3);
556 if (pattern)
557 strcpy (stpcpy (pattern, "#/"), issuer);
559 if (!pattern)
560 return gpg_error_from_syserror ();
561 add_to_strlist (&names, pattern);
562 xfree (pattern);
564 rc = gpgsm_dirmngr_lookup (ctrl, names, 1, find_up_store_certs_cb, &count);
565 free_strlist (names);
567 if (opt.verbose)
568 log_info (_("number of matching certificates: %d\n"), count);
569 if (rc && !opt.quiet)
570 log_info (_("dirmngr cache-only key lookup failed: %s\n"),
571 gpg_strerror (rc));
572 return (!rc && count)? 0 : -1;
577 /* Locate issuing certificate for CERT. ISSUER is the name of the
578 issuer used as a fallback if the other methods don't work. If
579 FIND_NEXT is true, the function shall return the next possible
580 issuer. The certificate itself is not directly returned but a
581 keydb_get_cert on the keyDb context KH will return it. Returns 0
582 on success, -1 if not found or an error code. */
583 static int
584 find_up (ctrl_t ctrl, KEYDB_HANDLE kh,
585 ksba_cert_t cert, const char *issuer, int find_next)
587 ksba_name_t authid;
588 ksba_sexp_t authidno;
589 ksba_sexp_t keyid;
590 int rc = -1;
592 if (!ksba_cert_get_auth_key_id (cert, &keyid, &authid, &authidno))
594 const char *s = ksba_name_enum (authid, 0);
595 if (s && *authidno)
597 rc = keydb_search_issuer_sn (kh, s, authidno);
598 if (rc)
599 keydb_search_reset (kh);
601 /* In case of an error, try to get the certificate from the
602 dirmngr. That is done by trying to put that certifcate
603 into the ephemeral DB and let the code below do the
604 actual retrieve. Thus there is no error checking.
605 Skipped in find_next mode as usual. */
606 if (rc == -1 && !find_next)
607 find_up_dirmngr (ctrl, kh, authidno, s, 0);
609 /* In case of an error try the ephemeral DB. We can't do
610 that in find_next mode because we can't keep the search
611 state then. */
612 if (rc == -1 && !find_next)
614 int old = keydb_set_ephemeral (kh, 1);
615 if (!old)
617 rc = keydb_search_issuer_sn (kh, s, authidno);
618 if (rc)
619 keydb_search_reset (kh);
621 keydb_set_ephemeral (kh, old);
623 if (rc)
624 rc = -1; /* Need to make sure to have this error code. */
627 if (rc == -1 && keyid && !find_next)
629 /* Not found by AIK.issuer_sn. Lets try the AIK.ki
630 instead. Loop over all certificates with that issuer as
631 subject and stop for the one with a matching
632 subjectKeyIdentifier. */
633 /* Fixme: Should we also search in the dirmngr? */
634 rc = find_up_search_by_keyid (kh, issuer, keyid);
635 if (rc)
637 int old = keydb_set_ephemeral (kh, 1);
638 if (!old)
639 rc = find_up_search_by_keyid (kh, issuer, keyid);
640 keydb_set_ephemeral (kh, old);
642 if (rc)
643 rc = -1; /* Need to make sure to have this error code. */
646 /* If we still didn't found it, try to find it via the subject
647 from the dirmngr-cache. */
648 if (rc == -1 && !find_next)
650 if (!find_up_dirmngr (ctrl, kh, NULL, issuer, 1))
652 int old = keydb_set_ephemeral (kh, 1);
653 if (keyid)
654 rc = find_up_search_by_keyid (kh, issuer, keyid);
655 else
657 keydb_search_reset (kh);
658 rc = keydb_search_subject (kh, issuer);
660 keydb_set_ephemeral (kh, old);
662 if (rc)
663 rc = -1; /* Need to make sure to have this error code. */
666 /* If we still didn't found it, try an external lookup. */
667 if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
668 rc = find_up_external (ctrl, kh, issuer, keyid);
670 /* Print a note so that the user does not feel too helpless when
671 an issuer certificate was found and gpgsm prints BAD
672 signature because it is not the correct one. */
673 if (rc == -1 && opt.quiet)
675 else if (rc == -1)
677 log_info ("%sissuer certificate ", find_next?"next ":"");
678 if (keyid)
680 log_printf ("{");
681 gpgsm_dump_serial (keyid);
682 log_printf ("} ");
684 if (authidno)
686 log_printf ("(#");
687 gpgsm_dump_serial (authidno);
688 log_printf ("/");
689 gpgsm_dump_string (s);
690 log_printf (") ");
692 log_printf ("not found using authorityKeyIdentifier\n");
694 else if (rc)
695 log_error ("failed to find authorityKeyIdentifier: rc=%d\n", rc);
696 xfree (keyid);
697 ksba_name_release (authid);
698 xfree (authidno);
701 if (rc) /* Not found via authorithyKeyIdentifier, try regular issuer name. */
702 rc = keydb_search_subject (kh, issuer);
703 if (rc == -1 && !find_next)
705 int old;
707 /* Also try to get it from the Dirmngr cache. The function
708 merely puts it into the ephemeral database. */
709 find_up_dirmngr (ctrl, kh, NULL, issuer, 0);
711 /* Not found, let us see whether we have one in the ephemeral key DB. */
712 old = keydb_set_ephemeral (kh, 1);
713 if (!old)
715 keydb_search_reset (kh);
716 rc = keydb_search_subject (kh, issuer);
718 keydb_set_ephemeral (kh, old);
721 /* Still not found. If enabled, try an external lookup. */
722 if (rc == -1 && opt.auto_issuer_key_retrieve && !find_next)
723 rc = find_up_external (ctrl, kh, issuer, NULL);
725 return rc;
729 /* Return the next certificate up in the chain starting at START.
730 Returns -1 when there are no more certificates. */
732 gpgsm_walk_cert_chain (ctrl_t ctrl, ksba_cert_t start, ksba_cert_t *r_next)
734 int rc = 0;
735 char *issuer = NULL;
736 char *subject = NULL;
737 KEYDB_HANDLE kh = keydb_new (0);
739 *r_next = NULL;
740 if (!kh)
742 log_error (_("failed to allocated keyDB handle\n"));
743 rc = gpg_error (GPG_ERR_GENERAL);
744 goto leave;
747 issuer = ksba_cert_get_issuer (start, 0);
748 subject = ksba_cert_get_subject (start, 0);
749 if (!issuer)
751 log_error ("no issuer found in certificate\n");
752 rc = gpg_error (GPG_ERR_BAD_CERT);
753 goto leave;
755 if (!subject)
757 log_error ("no subject found in certificate\n");
758 rc = gpg_error (GPG_ERR_BAD_CERT);
759 goto leave;
762 if (is_root_cert (start, issuer, subject))
764 rc = -1; /* we are at the root */
765 goto leave;
768 rc = find_up (ctrl, kh, start, issuer, 0);
769 if (rc)
771 /* It is quite common not to have a certificate, so better don't
772 print an error here. */
773 if (rc != -1 && opt.verbose > 1)
774 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
775 rc = gpg_error (GPG_ERR_MISSING_CERT);
776 goto leave;
779 rc = keydb_get_cert (kh, r_next);
780 if (rc)
782 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
783 rc = gpg_error (GPG_ERR_GENERAL);
786 leave:
787 xfree (issuer);
788 xfree (subject);
789 keydb_release (kh);
790 return rc;
794 /* Helper for gpgsm_is_root_cert. This one is used if the subject and
795 issuer DNs are already known. */
796 static int
797 is_root_cert (ksba_cert_t cert, const char *issuerdn, const char *subjectdn)
799 gpg_error_t err;
800 int result = 0;
801 ksba_sexp_t serialno;
802 ksba_sexp_t ak_keyid;
803 ksba_name_t ak_name;
804 ksba_sexp_t ak_sn;
805 const char *ak_name_str;
806 ksba_sexp_t subj_keyid = NULL;
808 if (!issuerdn || !subjectdn)
809 return 0; /* No. */
811 if (strcmp (issuerdn, subjectdn))
812 return 0; /* No. */
814 err = ksba_cert_get_auth_key_id (cert, &ak_keyid, &ak_name, &ak_sn);
815 if (err)
817 if (gpg_err_code (err) == GPG_ERR_NO_DATA)
818 return 1; /* Yes. Without a authorityKeyIdentifier this needs
819 to be the Root certifcate (our trust anchor). */
820 log_error ("error getting authorityKeyIdentifier: %s\n",
821 gpg_strerror (err));
822 return 0; /* Well, it is broken anyway. Return No. */
825 serialno = ksba_cert_get_serial (cert);
826 if (!serialno)
828 log_error ("error getting serialno: %s\n", gpg_strerror (err));
829 goto leave;
832 /* Check whether the auth name's matches the issuer name+sn. If
833 that is the case this is a root certificate. */
834 ak_name_str = ksba_name_enum (ak_name, 0);
835 if (ak_name_str
836 && !strcmp (ak_name_str, issuerdn)
837 && !cmp_simple_canon_sexp (ak_sn, serialno))
839 result = 1; /* Right, CERT is self-signed. */
840 goto leave;
843 /* Similar for the ak_keyid. */
844 if (ak_keyid && !ksba_cert_get_subj_key_id (cert, NULL, &subj_keyid)
845 && !cmp_simple_canon_sexp (ak_keyid, subj_keyid))
847 result = 1; /* Right, CERT is self-signed. */
848 goto leave;
852 leave:
853 ksba_free (subj_keyid);
854 ksba_free (ak_keyid);
855 ksba_name_release (ak_name);
856 ksba_free (ak_sn);
857 ksba_free (serialno);
858 return result;
863 /* Check whether the CERT is a root certificate. Returns True if this
864 is the case. */
866 gpgsm_is_root_cert (ksba_cert_t cert)
868 char *issuer;
869 char *subject;
870 int yes;
872 issuer = ksba_cert_get_issuer (cert, 0);
873 subject = ksba_cert_get_subject (cert, 0);
874 yes = is_root_cert (cert, issuer, subject);
875 xfree (issuer);
876 xfree (subject);
877 return yes;
881 /* This is a helper for gpgsm_validate_chain. */
882 static gpg_error_t
883 is_cert_still_valid (ctrl_t ctrl, int force_ocsp, int lm, estream_t fp,
884 ksba_cert_t subject_cert, ksba_cert_t issuer_cert,
885 int *any_revoked, int *any_no_crl, int *any_crl_too_old)
887 gpg_error_t err;
889 if (opt.no_crl_check && !ctrl->use_ocsp)
890 return 0;
892 err = gpgsm_dirmngr_isvalid (ctrl,
893 subject_cert, issuer_cert,
894 force_ocsp? 2 : !!ctrl->use_ocsp);
895 if (err)
897 if (!lm)
898 gpgsm_cert_log_name (NULL, subject_cert);
899 switch (gpg_err_code (err))
901 case GPG_ERR_CERT_REVOKED:
902 do_list (1, lm, fp, _("certificate has been revoked"));
903 *any_revoked = 1;
904 /* Store that in the keybox so that key listings are able to
905 return the revoked flag. We don't care about error,
906 though. */
907 keydb_set_cert_flags (subject_cert, 1, KEYBOX_FLAG_VALIDITY, 0,
908 ~0, VALIDITY_REVOKED);
909 break;
911 case GPG_ERR_NO_CRL_KNOWN:
912 do_list (1, lm, fp, _("no CRL found for certificate"));
913 *any_no_crl = 1;
914 break;
916 case GPG_ERR_NO_DATA:
917 do_list (1, lm, fp, _("the status of the certificate is unknown"));
918 *any_no_crl = 1;
919 break;
921 case GPG_ERR_CRL_TOO_OLD:
922 do_list (1, lm, fp, _("the available CRL is too old"));
923 if (!lm)
924 log_info (_("please make sure that the "
925 "\"dirmngr\" is properly installed\n"));
926 *any_crl_too_old = 1;
927 break;
929 default:
930 do_list (1, lm, fp, _("checking the CRL failed: %s"),
931 gpg_strerror (err));
932 return err;
935 return 0;
939 /* Helper for gpgsm_validate_chain to check the validity period of
940 SUBJECT_CERT. The caller needs to pass EXPTIME which will be
941 updated to the nearest expiration time seen. A DEPTH of 0 indicates
942 the target certifciate, -1 the final root certificate and other
943 values intermediate certificates. */
944 static gpg_error_t
945 check_validity_period (ksba_isotime_t current_time,
946 ksba_cert_t subject_cert,
947 ksba_isotime_t exptime,
948 int listmode, estream_t listfp, int depth)
950 gpg_error_t err;
951 ksba_isotime_t not_before, not_after;
953 err = ksba_cert_get_validity (subject_cert, 0, not_before);
954 if (!err)
955 err = ksba_cert_get_validity (subject_cert, 1, not_after);
956 if (err)
958 do_list (1, listmode, listfp,
959 _("certificate with invalid validity: %s"), gpg_strerror (err));
960 return gpg_error (GPG_ERR_BAD_CERT);
963 if (*not_after)
965 if (!*exptime)
966 gnupg_copy_time (exptime, not_after);
967 else if (strcmp (not_after, exptime) < 0 )
968 gnupg_copy_time (exptime, not_after);
971 if (*not_before && strcmp (current_time, not_before) < 0 )
973 do_list (1, listmode, listfp,
974 depth == 0 ? _("certificate not yet valid") :
975 depth == -1 ? _("root certificate not yet valid") :
976 /* other */ _("intermediate certificate not yet valid"));
977 if (!listmode)
979 log_info (" (valid from ");
980 gpgsm_dump_time (not_before);
981 log_printf (")\n");
983 return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
986 if (*not_after && strcmp (current_time, not_after) > 0 )
988 do_list (opt.ignore_expiration?0:1, listmode, listfp,
989 depth == 0 ? _("certificate has expired") :
990 depth == -1 ? _("root certificate has expired") :
991 /* other */ _("intermediate certificate has expired"));
992 if (!listmode)
994 log_info (" (expired at ");
995 gpgsm_dump_time (not_after);
996 log_printf (")\n");
998 if (opt.ignore_expiration)
999 log_info ("WARNING: ignoring expiration\n");
1000 else
1001 return gpg_error (GPG_ERR_CERT_EXPIRED);
1004 return 0;
1007 /* This is a variant of check_validity_period used with the chain
1008 model. The dextra contraint here is that notBefore and notAfter
1009 must exists and if the additional argument CHECK_TIME is given this
1010 time is used to check the validity period of SUBJECT_CERT. */
1011 static gpg_error_t
1012 check_validity_period_cm (ksba_isotime_t current_time,
1013 ksba_isotime_t check_time,
1014 ksba_cert_t subject_cert,
1015 ksba_isotime_t exptime,
1016 int listmode, estream_t listfp, int depth)
1018 gpg_error_t err;
1019 ksba_isotime_t not_before, not_after;
1021 err = ksba_cert_get_validity (subject_cert, 0, not_before);
1022 if (!err)
1023 err = ksba_cert_get_validity (subject_cert, 1, not_after);
1024 if (err)
1026 do_list (1, listmode, listfp,
1027 _("certificate with invalid validity: %s"), gpg_strerror (err));
1028 return gpg_error (GPG_ERR_BAD_CERT);
1030 if (!*not_before || !*not_after)
1032 do_list (1, listmode, listfp,
1033 _("required certificate attributes missing: %s%s%s"),
1034 !*not_before? "notBefore":"",
1035 (!*not_before && !*not_after)? ", ":"",
1036 !*not_before? "notAfter":"");
1037 return gpg_error (GPG_ERR_BAD_CERT);
1039 if (strcmp (not_before, not_after) > 0 )
1041 do_list (1, listmode, listfp,
1042 _("certificate with invalid validity"));
1043 log_info (" (valid from ");
1044 gpgsm_dump_time (not_before);
1045 log_printf (" expired at ");
1046 gpgsm_dump_time (not_after);
1047 log_printf (")\n");
1048 return gpg_error (GPG_ERR_BAD_CERT);
1051 if (!*exptime)
1052 gnupg_copy_time (exptime, not_after);
1053 else if (strcmp (not_after, exptime) < 0 )
1054 gnupg_copy_time (exptime, not_after);
1056 if (strcmp (current_time, not_before) < 0 )
1058 do_list (1, listmode, listfp,
1059 depth == 0 ? _("certificate not yet valid") :
1060 depth == -1 ? _("root certificate not yet valid") :
1061 /* other */ _("intermediate certificate not yet valid"));
1062 if (!listmode)
1064 log_info (" (valid from ");
1065 gpgsm_dump_time (not_before);
1066 log_printf (")\n");
1068 return gpg_error (GPG_ERR_CERT_TOO_YOUNG);
1071 if (*check_time
1072 && (strcmp (check_time, not_before) < 0
1073 || strcmp (check_time, not_after) > 0))
1075 /* Note that we don't need a case for the root certificate
1076 because its own consitency has already been checked. */
1077 do_list(opt.ignore_expiration?0:1, listmode, listfp,
1078 depth == 0 ?
1079 _("signature not created during lifetime of certificate") :
1080 depth == 1 ?
1081 _("certificate not created during lifetime of issuer") :
1082 _("intermediate certificate not created during lifetime "
1083 "of issuer"));
1084 if (!listmode)
1086 log_info (depth== 0? _(" ( signature created at ") :
1087 /* */ _(" (certificate created at ") );
1088 gpgsm_dump_time (check_time);
1089 log_printf (")\n");
1090 log_info (depth==0? _(" (certificate valid from ") :
1091 /* */ _(" ( issuer valid from ") );
1092 gpgsm_dump_time (not_before);
1093 log_info (" to ");
1094 gpgsm_dump_time (not_after);
1095 log_printf (")\n");
1097 if (opt.ignore_expiration)
1098 log_info ("WARNING: ignoring expiration\n");
1099 else
1100 return gpg_error (GPG_ERR_CERT_EXPIRED);
1103 return 0;
1108 /* Ask the user whether he wants to mark the certificate CERT trusted.
1109 Returns true if the CERT is the trusted. We also check whether the
1110 agent is at all enabled to allow marktrusted and don't call it in
1111 this session again if it is not. */
1112 static int
1113 ask_marktrusted (ctrl_t ctrl, ksba_cert_t cert, int listmode)
1115 static int no_more_questions;
1116 int rc;
1117 char *fpr;
1118 int success = 0;
1120 fpr = gpgsm_get_fingerprint_string (cert, GCRY_MD_SHA1);
1121 log_info (_("fingerprint=%s\n"), fpr? fpr : "?");
1122 xfree (fpr);
1124 if (no_more_questions)
1125 rc = gpg_error (GPG_ERR_NOT_SUPPORTED);
1126 else
1127 rc = gpgsm_agent_marktrusted (ctrl, cert);
1128 if (!rc)
1130 log_info (_("root certificate has now been marked as trusted\n"));
1131 success = 1;
1133 else if (!listmode)
1135 gpgsm_dump_cert ("issuer", cert);
1136 log_info ("after checking the fingerprint, you may want "
1137 "to add it manually to the list of trusted certificates.\n");
1140 if (gpg_err_code (rc) == GPG_ERR_NOT_SUPPORTED)
1142 if (!no_more_questions)
1143 log_info (_("interactive marking as trusted "
1144 "not enabled in gpg-agent\n"));
1145 no_more_questions = 1;
1147 else if (gpg_err_code (rc) == GPG_ERR_CANCELED)
1149 log_info (_("interactive marking as trusted "
1150 "disabled for this session\n"));
1151 no_more_questions = 1;
1153 else
1154 set_already_asked_marktrusted (cert);
1156 return success;
1162 /* Validate a chain and optionally return the nearest expiration time
1163 in R_EXPTIME. With LISTMODE set to 1 a special listmode is
1164 activated where only information about the certificate is printed
1165 to LISTFP and no output is send to the usual log stream. If
1166 CHECKTIME_ARG is set, it is used only in the chain model instead of the
1167 current time.
1169 Defined flag bits
1171 VALIDATE_FLAG_NO_DIRMNGR - Do not do any dirmngr isvalid checks.
1172 VALIDATE_FLAG_CHAIN_MODEL - Check according to chain model.
1174 static int
1175 do_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime_arg,
1176 ksba_isotime_t r_exptime,
1177 int listmode, estream_t listfp, unsigned int flags,
1178 struct rootca_flags_s *rootca_flags)
1180 int rc = 0, depth, maxdepth;
1181 char *issuer = NULL;
1182 char *subject = NULL;
1183 KEYDB_HANDLE kh = NULL;
1184 ksba_cert_t subject_cert = NULL, issuer_cert = NULL;
1185 ksba_isotime_t current_time;
1186 ksba_isotime_t check_time;
1187 ksba_isotime_t exptime;
1188 int any_expired = 0;
1189 int any_revoked = 0;
1190 int any_no_crl = 0;
1191 int any_crl_too_old = 0;
1192 int any_no_policy_match = 0;
1193 int is_qualified = -1; /* Indicates whether the certificate stems
1194 from a qualified root certificate.
1195 -1 = unknown, 0 = no, 1 = yes. */
1196 chain_item_t chain = NULL; /* A list of all certificates in the chain. */
1199 gnupg_get_isotime (current_time);
1201 if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1203 if (!strcmp (checktime_arg, "19700101T000000"))
1205 do_list (1, listmode, listfp,
1206 _("WARNING: creation time of signature not known - "
1207 "assuming current time"));
1208 gnupg_copy_time (check_time, current_time);
1210 else
1211 gnupg_copy_time (check_time, checktime_arg);
1213 else
1214 *check_time = 0;
1216 if (r_exptime)
1217 *r_exptime = 0;
1218 *exptime = 0;
1220 if (opt.no_chain_validation && !listmode)
1222 log_info ("WARNING: bypassing certificate chain validation\n");
1223 return 0;
1226 kh = keydb_new (0);
1227 if (!kh)
1229 log_error (_("failed to allocated keyDB handle\n"));
1230 rc = gpg_error (GPG_ERR_GENERAL);
1231 goto leave;
1234 if (DBG_X509 && !listmode)
1235 gpgsm_dump_cert ("target", cert);
1237 subject_cert = cert;
1238 ksba_cert_ref (subject_cert);
1239 maxdepth = 50;
1240 depth = 0;
1242 for (;;)
1244 int is_root;
1245 gpg_error_t istrusted_rc = -1;
1247 /* Put the certificate on our list. */
1249 chain_item_t ci;
1251 ci = xtrycalloc (1, sizeof *ci);
1252 if (!ci)
1254 rc = gpg_error_from_syserror ();
1255 goto leave;
1257 ksba_cert_ref (subject_cert);
1258 ci->cert = subject_cert;
1259 ci->next = chain;
1260 chain = ci;
1263 xfree (issuer);
1264 xfree (subject);
1265 issuer = ksba_cert_get_issuer (subject_cert, 0);
1266 subject = ksba_cert_get_subject (subject_cert, 0);
1268 if (!issuer)
1270 do_list (1, listmode, listfp, _("no issuer found in certificate"));
1271 rc = gpg_error (GPG_ERR_BAD_CERT);
1272 goto leave;
1276 /* Is this a self-issued certificate (i.e. the root certificate)? */
1277 is_root = is_root_cert (subject_cert, issuer, subject);
1278 if (is_root)
1280 chain->is_root = 1;
1281 /* Check early whether the certificate is listed as trusted.
1282 We used to do this only later but changed it to call the
1283 check right here so that we can access special flags
1284 associated with that specific root certificate. */
1285 istrusted_rc = gpgsm_agent_istrusted (ctrl, subject_cert,
1286 rootca_flags);
1287 audit_log_cert (ctrl->audit, AUDIT_ROOT_TRUSTED,
1288 subject_cert, istrusted_rc);
1289 /* If the chain model extended attribute is used, make sure
1290 that our chain model flag is set. */
1291 if (has_validation_model_chain (subject_cert, listmode, listfp))
1292 rootca_flags->chain_model = 1;
1296 /* Check the validity period. */
1297 if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1298 rc = check_validity_period_cm (current_time, check_time, subject_cert,
1299 exptime, listmode, listfp,
1300 (depth && is_root)? -1: depth);
1301 else
1302 rc = check_validity_period (current_time, subject_cert,
1303 exptime, listmode, listfp,
1304 (depth && is_root)? -1: depth);
1305 if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED)
1307 any_expired = 1;
1308 rc = 0;
1310 else if (rc)
1311 goto leave;
1314 /* Assert that we understand all critical extensions. */
1315 rc = unknown_criticals (subject_cert, listmode, listfp);
1316 if (rc)
1317 goto leave;
1319 /* Do a policy check. */
1320 if (!opt.no_policy_check)
1322 rc = check_cert_policy (subject_cert, listmode, listfp);
1323 if (gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH)
1325 any_no_policy_match = 1;
1326 rc = 1;
1328 else if (rc)
1329 goto leave;
1333 /* If this is the root certificate we are at the end of the chain. */
1334 if (is_root)
1336 if (!istrusted_rc)
1337 ; /* No need to check the certificate for a trusted one. */
1338 else if (gpgsm_check_cert_sig (subject_cert, subject_cert) )
1340 /* We only check the signature if the certificate is not
1341 trusted for better diagnostics. */
1342 do_list (1, listmode, listfp,
1343 _("self-signed certificate has a BAD signature"));
1344 if (DBG_X509)
1346 gpgsm_dump_cert ("self-signing cert", subject_cert);
1348 rc = gpg_error (depth? GPG_ERR_BAD_CERT_CHAIN
1349 : GPG_ERR_BAD_CERT);
1350 goto leave;
1352 if (!rootca_flags->relax)
1354 rc = allowed_ca (ctrl, subject_cert, NULL, listmode, listfp);
1355 if (rc)
1356 goto leave;
1360 /* Set the flag for qualified signatures. This flag is
1361 deduced from a list of root certificates allowed for
1362 qualified signatures. */
1363 if (is_qualified == -1)
1365 gpg_error_t err;
1366 size_t buflen;
1367 char buf[1];
1369 if (!ksba_cert_get_user_data (cert, "is_qualified",
1370 &buf, sizeof (buf),
1371 &buflen) && buflen)
1373 /* We already checked this for this certificate,
1374 thus we simply take it from the user data. */
1375 is_qualified = !!*buf;
1377 else
1379 /* Need to consult the list of root certificates for
1380 qualified signatures. */
1381 err = gpgsm_is_in_qualified_list (ctrl, subject_cert, NULL);
1382 if (!err)
1383 is_qualified = 1;
1384 else if ( gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1385 is_qualified = 0;
1386 else
1387 log_error ("checking the list of qualified "
1388 "root certificates failed: %s\n",
1389 gpg_strerror (err));
1390 if ( is_qualified != -1 )
1392 /* Cache the result but don't care too much
1393 about an error. */
1394 buf[0] = !!is_qualified;
1395 err = ksba_cert_set_user_data (subject_cert,
1396 "is_qualified", buf, 1);
1397 if (err)
1398 log_error ("set_user_data(is_qualified) failed: %s\n",
1399 gpg_strerror (err));
1405 /* Act on the check for a trusted root certificates. */
1406 rc = istrusted_rc;
1407 if (!rc)
1409 else if (gpg_err_code (rc) == GPG_ERR_NOT_TRUSTED)
1411 do_list (0, listmode, listfp,
1412 _("root certificate is not marked trusted"));
1413 /* If we already figured out that the certificate is
1414 expired it does not make much sense to ask the user
1415 whether we wants to trust the root certificate. We
1416 should do this only if the certificate under question
1417 will then be usable. */
1418 if ( !any_expired
1419 && (!listmode || !already_asked_marktrusted (subject_cert))
1420 && ask_marktrusted (ctrl, subject_cert, listmode) )
1421 rc = 0;
1423 else
1425 log_error (_("checking the trust list failed: %s\n"),
1426 gpg_strerror (rc));
1429 if (rc)
1430 goto leave;
1432 /* Check for revocations etc. */
1433 if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
1435 else if (opt.no_trusted_cert_crl_check || rootca_flags->relax)
1437 else
1438 rc = is_cert_still_valid (ctrl,
1439 (flags & VALIDATE_FLAG_CHAIN_MODEL),
1440 listmode, listfp,
1441 subject_cert, subject_cert,
1442 &any_revoked, &any_no_crl,
1443 &any_crl_too_old);
1444 if (rc)
1445 goto leave;
1447 break; /* Okay: a self-signed certicate is an end-point. */
1448 } /* End is_root. */
1451 /* Take care that the chain does not get too long. */
1452 if ((depth+1) > maxdepth)
1454 do_list (1, listmode, listfp, _("certificate chain too long\n"));
1455 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1456 goto leave;
1459 /* Find the next cert up the tree. */
1460 keydb_search_reset (kh);
1461 rc = find_up (ctrl, kh, subject_cert, issuer, 0);
1462 if (rc)
1464 if (rc == -1)
1466 do_list (0, listmode, listfp, _("issuer certificate not found"));
1467 if (!listmode)
1469 log_info ("issuer certificate: #/");
1470 gpgsm_dump_string (issuer);
1471 log_printf ("\n");
1474 else
1475 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
1476 rc = gpg_error (GPG_ERR_MISSING_CERT);
1477 goto leave;
1480 ksba_cert_release (issuer_cert); issuer_cert = NULL;
1481 rc = keydb_get_cert (kh, &issuer_cert);
1482 if (rc)
1484 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
1485 rc = gpg_error (GPG_ERR_GENERAL);
1486 goto leave;
1489 try_another_cert:
1490 if (DBG_X509)
1492 log_debug ("got issuer's certificate:\n");
1493 gpgsm_dump_cert ("issuer", issuer_cert);
1496 rc = gpgsm_check_cert_sig (issuer_cert, subject_cert);
1497 if (rc)
1499 do_list (0, listmode, listfp, _("certificate has a BAD signature"));
1500 if (DBG_X509)
1502 gpgsm_dump_cert ("signing issuer", issuer_cert);
1503 gpgsm_dump_cert ("signed subject", subject_cert);
1505 if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
1507 /* We now try to find other issuer certificates which
1508 might have been used. This is required because some
1509 CAs are reusing the issuer and subject DN for new
1510 root certificates. */
1511 /* FIXME: Do this only if we don't have an
1512 AKI.keyIdentifier */
1513 rc = find_up (ctrl, kh, subject_cert, issuer, 1);
1514 if (!rc)
1516 ksba_cert_t tmp_cert;
1518 rc = keydb_get_cert (kh, &tmp_cert);
1519 if (rc || !compare_certs (issuer_cert, tmp_cert))
1521 /* The find next did not work or returned an
1522 identical certificate. We better stop here
1523 to avoid infinite checks. */
1524 rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
1525 ksba_cert_release (tmp_cert);
1527 else
1529 do_list (0, listmode, listfp,
1530 _("found another possible matching "
1531 "CA certificate - trying again"));
1532 ksba_cert_release (issuer_cert);
1533 issuer_cert = tmp_cert;
1534 goto try_another_cert;
1539 /* We give a more descriptive error code than the one
1540 returned from the signature checking. */
1541 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1542 goto leave;
1545 is_root = gpgsm_is_root_cert (issuer_cert);
1546 istrusted_rc = -1;
1549 /* Check that a CA is allowed to issue certificates. */
1551 int chainlen;
1553 rc = allowed_ca (ctrl, issuer_cert, &chainlen, listmode, listfp);
1554 if (rc)
1556 /* Not allowed. Check whether this is a trusted root
1557 certificate and whether we allow special exceptions.
1558 We could carry the result of the test over to the
1559 regular root check at the top of the loop but for
1560 clarity we won't do that. Given that the majority of
1561 certificates carry proper BasicContraints our way of
1562 overriding an error in the way is justified for
1563 performance reasons. */
1564 if (is_root)
1566 istrusted_rc = gpgsm_agent_istrusted (ctrl, issuer_cert,
1567 rootca_flags);
1568 if (!istrusted_rc && rootca_flags->relax)
1570 /* Ignore the error due to the relax flag. */
1571 rc = 0;
1572 chainlen = -1;
1576 if (rc)
1577 goto leave;
1578 if (chainlen >= 0 && depth > chainlen)
1580 do_list (1, listmode, listfp,
1581 _("certificate chain longer than allowed by CA (%d)"),
1582 chainlen);
1583 rc = gpg_error (GPG_ERR_BAD_CERT_CHAIN);
1584 goto leave;
1588 /* Is the certificate allowed to sign other certificates. */
1589 if (!listmode)
1591 rc = gpgsm_cert_use_cert_p (issuer_cert);
1592 if (rc)
1594 char numbuf[50];
1595 sprintf (numbuf, "%d", rc);
1596 gpgsm_status2 (ctrl, STATUS_ERROR, "certcert.issuer.keyusage",
1597 numbuf, NULL);
1598 goto leave;
1602 /* Check for revocations etc. Note that for a root certificate
1603 this test is done a second time later. This should eventually
1604 be fixed. */
1605 if ((flags & VALIDATE_FLAG_NO_DIRMNGR))
1606 rc = 0;
1607 else if (is_root && (opt.no_trusted_cert_crl_check
1608 || (!istrusted_rc && rootca_flags->relax)))
1609 rc = 0;
1610 else
1611 rc = is_cert_still_valid (ctrl,
1612 (flags & VALIDATE_FLAG_CHAIN_MODEL),
1613 listmode, listfp,
1614 subject_cert, issuer_cert,
1615 &any_revoked, &any_no_crl, &any_crl_too_old);
1616 if (rc)
1617 goto leave;
1620 if (opt.verbose && !listmode)
1621 log_info (depth == 0 ? _("certificate is good\n") :
1622 !is_root ? _("intermediate certificate is good\n") :
1623 /* other */ _("root certificate is good\n"));
1625 /* Under the chain model the next check time is the creation
1626 time of the subject certificate. */
1627 if ( (flags & VALIDATE_FLAG_CHAIN_MODEL) )
1629 rc = ksba_cert_get_validity (subject_cert, 0, check_time);
1630 if (rc)
1632 /* That will never happen as we have already checked
1633 this above. */
1634 BUG ();
1638 /* For the next round the current issuer becomes the new subject. */
1639 keydb_search_reset (kh);
1640 ksba_cert_release (subject_cert);
1641 subject_cert = issuer_cert;
1642 issuer_cert = NULL;
1643 depth++;
1644 } /* End chain traversal. */
1646 if (!listmode && !opt.quiet)
1648 if (opt.no_policy_check)
1649 log_info ("policies not checked due to %s option\n",
1650 "--disable-policy-checks");
1651 if (opt.no_crl_check && !ctrl->use_ocsp)
1652 log_info ("CRLs not checked due to %s option\n",
1653 "--disable-crl-checks");
1656 if (!rc)
1657 { /* If we encountered an error somewhere during the checks, set
1658 the error code to the most critical one */
1659 if (any_revoked)
1660 rc = gpg_error (GPG_ERR_CERT_REVOKED);
1661 else if (any_expired)
1662 rc = gpg_error (GPG_ERR_CERT_EXPIRED);
1663 else if (any_no_crl)
1664 rc = gpg_error (GPG_ERR_NO_CRL_KNOWN);
1665 else if (any_crl_too_old)
1666 rc = gpg_error (GPG_ERR_CRL_TOO_OLD);
1667 else if (any_no_policy_match)
1668 rc = gpg_error (GPG_ERR_NO_POLICY_MATCH);
1671 leave:
1672 /* If we have traversed a complete chain up to the root we will
1673 reset the ephemeral flag for all these certificates. This is done
1674 regardless of any error because those errors may only be
1675 transient. */
1676 if (chain && chain->is_root)
1678 gpg_error_t err;
1679 chain_item_t ci;
1681 for (ci = chain; ci; ci = ci->next)
1683 /* Note that it is possible for the last certificate in the
1684 chain (i.e. our target certificate) that it has not yet
1685 been stored in the keybox and thus the flag can't be set.
1686 We ignore this error becuase it will later be stored
1687 anyway. */
1688 err = keydb_set_cert_flags (ci->cert, 1, KEYBOX_FLAG_BLOB, 0,
1689 KEYBOX_FLAG_BLOB_EPHEMERAL, 0);
1690 if (!ci->next && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1692 else if (err)
1693 log_error ("clearing ephemeral flag failed: %s\n",
1694 gpg_strerror (err));
1698 /* If we have figured something about the qualified signature
1699 capability of the certificate under question, store the result as
1700 user data in all certificates of the chain. We do this even if the
1701 validation itself failed. */
1702 if (is_qualified != -1)
1704 gpg_error_t err;
1705 chain_item_t ci;
1706 char buf[1];
1708 buf[0] = !!is_qualified;
1710 for (ci = chain; ci; ci = ci->next)
1712 err = ksba_cert_set_user_data (ci->cert, "is_qualified", buf, 1);
1713 if (err)
1715 log_error ("set_user_data(is_qualified) failed: %s\n",
1716 gpg_strerror (err));
1717 if (!rc)
1718 rc = err;
1723 /* If auditing has been enabled, record what is in the chain. */
1724 if (ctrl->audit)
1726 chain_item_t ci;
1728 audit_log (ctrl->audit, AUDIT_CHAIN_BEGIN);
1729 for (ci = chain; ci; ci = ci->next)
1731 audit_log_cert (ctrl->audit,
1732 ci->is_root? AUDIT_CHAIN_ROOTCERT : AUDIT_CHAIN_CERT,
1733 ci->cert, 0);
1735 audit_log (ctrl->audit, AUDIT_CHAIN_END);
1738 if (r_exptime)
1739 gnupg_copy_time (r_exptime, exptime);
1740 xfree (issuer);
1741 xfree (subject);
1742 keydb_release (kh);
1743 while (chain)
1745 chain_item_t ci_next = chain->next;
1746 ksba_cert_release (chain->cert);
1747 xfree (chain);
1748 chain = ci_next;
1750 ksba_cert_release (issuer_cert);
1751 ksba_cert_release (subject_cert);
1752 return rc;
1756 /* Validate a certificate chain. For a description see
1757 do_validate_chain. This function is a wrapper to handle a root
1758 certificate with the chain_model flag set. If RETFLAGS is not
1759 NULL, flags indicating now the verification was done are stored
1760 there. The only defined flag for RETFLAGS is
1761 VALIDATE_FLAG_CHAIN_MODEL.
1763 If you are verifying a signature you should set CHECKTIME to the
1764 creation time of the signature. If your are verifying a
1765 certificate, set it nil (i.e. the empty string). If the creation
1766 date of the signature is not known use the special date
1767 "19700101T000000" which is treated in a special way here. */
1769 gpgsm_validate_chain (ctrl_t ctrl, ksba_cert_t cert, ksba_isotime_t checktime,
1770 ksba_isotime_t r_exptime,
1771 int listmode, estream_t listfp, unsigned int flags,
1772 unsigned int *retflags)
1774 int rc;
1775 struct rootca_flags_s rootca_flags;
1776 unsigned int dummy_retflags;
1778 if (!retflags)
1779 retflags = &dummy_retflags;
1781 if (ctrl->validation_model == 1)
1782 flags |= VALIDATE_FLAG_CHAIN_MODEL;
1784 *retflags = (flags & VALIDATE_FLAG_CHAIN_MODEL);
1785 memset (&rootca_flags, 0, sizeof rootca_flags);
1787 rc = do_validate_chain (ctrl, cert, checktime,
1788 r_exptime, listmode, listfp, flags,
1789 &rootca_flags);
1790 if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED
1791 && !(flags & VALIDATE_FLAG_CHAIN_MODEL)
1792 && (rootca_flags.valid && rootca_flags.chain_model))
1794 do_list (0, listmode, listfp, _("switching to chain model"));
1795 rc = do_validate_chain (ctrl, cert, checktime,
1796 r_exptime, listmode, listfp,
1797 (flags |= VALIDATE_FLAG_CHAIN_MODEL),
1798 &rootca_flags);
1799 *retflags |= VALIDATE_FLAG_CHAIN_MODEL;
1802 if (opt.verbose)
1803 do_list (0, listmode, listfp, _("validation model used: %s"),
1804 (*retflags & VALIDATE_FLAG_CHAIN_MODEL)?
1805 _("chain"):_("shell"));
1807 return rc;
1811 /* Check that the given certificate is valid but DO NOT check any
1812 constraints. We assume that the issuers certificate is already in
1813 the DB and that this one is valid; which it should be because it
1814 has been checked using this function. */
1816 gpgsm_basic_cert_check (ctrl_t ctrl, ksba_cert_t cert)
1818 int rc = 0;
1819 char *issuer = NULL;
1820 char *subject = NULL;
1821 KEYDB_HANDLE kh;
1822 ksba_cert_t issuer_cert = NULL;
1824 if (opt.no_chain_validation)
1826 log_info ("WARNING: bypassing basic certificate checks\n");
1827 return 0;
1830 kh = keydb_new (0);
1831 if (!kh)
1833 log_error (_("failed to allocated keyDB handle\n"));
1834 rc = gpg_error (GPG_ERR_GENERAL);
1835 goto leave;
1838 issuer = ksba_cert_get_issuer (cert, 0);
1839 subject = ksba_cert_get_subject (cert, 0);
1840 if (!issuer)
1842 log_error ("no issuer found in certificate\n");
1843 rc = gpg_error (GPG_ERR_BAD_CERT);
1844 goto leave;
1847 if (is_root_cert (cert, issuer, subject))
1849 rc = gpgsm_check_cert_sig (cert, cert);
1850 if (rc)
1852 log_error ("self-signed certificate has a BAD signature: %s\n",
1853 gpg_strerror (rc));
1854 if (DBG_X509)
1856 gpgsm_dump_cert ("self-signing cert", cert);
1858 rc = gpg_error (GPG_ERR_BAD_CERT);
1859 goto leave;
1862 else
1864 /* Find the next cert up the tree. */
1865 keydb_search_reset (kh);
1866 rc = find_up (ctrl, kh, cert, issuer, 0);
1867 if (rc)
1869 if (rc == -1)
1871 log_info ("issuer certificate (#/");
1872 gpgsm_dump_string (issuer);
1873 log_printf (") not found\n");
1875 else
1876 log_error ("failed to find issuer's certificate: rc=%d\n", rc);
1877 rc = gpg_error (GPG_ERR_MISSING_CERT);
1878 goto leave;
1881 ksba_cert_release (issuer_cert); issuer_cert = NULL;
1882 rc = keydb_get_cert (kh, &issuer_cert);
1883 if (rc)
1885 log_error ("keydb_get_cert() failed: rc=%d\n", rc);
1886 rc = gpg_error (GPG_ERR_GENERAL);
1887 goto leave;
1890 rc = gpgsm_check_cert_sig (issuer_cert, cert);
1891 if (rc)
1893 log_error ("certificate has a BAD signature: %s\n",
1894 gpg_strerror (rc));
1895 if (DBG_X509)
1897 gpgsm_dump_cert ("signing issuer", issuer_cert);
1898 gpgsm_dump_cert ("signed subject", cert);
1900 rc = gpg_error (GPG_ERR_BAD_CERT);
1901 goto leave;
1903 if (opt.verbose)
1904 log_info (_("certificate is good\n"));
1907 leave:
1908 xfree (issuer);
1909 xfree (subject);
1910 keydb_release (kh);
1911 ksba_cert_release (issuer_cert);
1912 return rc;
1917 /* Check whether the certificate CERT has been issued by the German
1918 authority for qualified signature. They do not set the
1919 basicConstraints and thus we need this workaround. It works by
1920 looking up the root certificate and checking whether that one is
1921 listed as a qualified certificate for Germany.
1923 We also try to cache this data but as long as don't keep a
1924 reference to the certificate this won't be used.
1926 Returns: True if CERT is a RegTP issued CA cert (i.e. the root
1927 certificate itself or one of the CAs). In that case CHAINLEN will
1928 receive the length of the chain which is either 0 or 1.
1930 static int
1931 get_regtp_ca_info (ctrl_t ctrl, ksba_cert_t cert, int *chainlen)
1933 gpg_error_t err;
1934 ksba_cert_t next;
1935 int rc = 0;
1936 int i, depth;
1937 char country[3];
1938 ksba_cert_t array[4];
1939 char buf[2];
1940 size_t buflen;
1941 int dummy_chainlen;
1943 if (!chainlen)
1944 chainlen = &dummy_chainlen;
1946 *chainlen = 0;
1947 err = ksba_cert_get_user_data (cert, "regtp_ca_chainlen",
1948 &buf, sizeof (buf), &buflen);
1949 if (!err)
1951 /* Got info. */
1952 if (buflen < 2 || !*buf)
1953 return 0; /* Nothing found. */
1954 *chainlen = buf[1];
1955 return 1; /* This is a regtp CA. */
1957 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1959 log_error ("ksba_cert_get_user_data(%s) failed: %s\n",
1960 "regtp_ca_chainlen", gpg_strerror (err));
1961 return 0; /* Nothing found. */
1964 /* Need to gather the info. This requires to walk up the chain
1965 until we have found the root. Because we are only interested in
1966 German Bundesnetzagentur (former RegTP) derived certificates 3
1967 levels are enough. (The German signature law demands a 3 tier
1968 hierachy; thus there is only one CA between the EE and the Root
1969 CA.) */
1970 memset (&array, 0, sizeof array);
1972 depth = 0;
1973 ksba_cert_ref (cert);
1974 array[depth++] = cert;
1975 ksba_cert_ref (cert);
1976 while (depth < DIM(array) && !(rc=gpgsm_walk_cert_chain (ctrl, cert, &next)))
1978 ksba_cert_release (cert);
1979 ksba_cert_ref (next);
1980 array[depth++] = next;
1981 cert = next;
1983 ksba_cert_release (cert);
1984 if (rc != -1 || !depth || depth == DIM(array) )
1986 /* We did not reached the root. */
1987 goto leave;
1990 /* If this is a German signature law issued certificate, we store
1991 additional additional information. */
1992 if (!gpgsm_is_in_qualified_list (NULL, array[depth-1], country)
1993 && !strcmp (country, "de"))
1995 /* Setting the pathlen for the root CA and the CA flag for the
1996 next one is all what we need to do. */
1997 err = ksba_cert_set_user_data (array[depth-1], "regtp_ca_chainlen",
1998 "\x01\x01", 2);
1999 if (!err && depth > 1)
2000 err = ksba_cert_set_user_data (array[depth-2], "regtp_ca_chainlen",
2001 "\x01\x00", 2);
2002 if (err)
2003 log_error ("ksba_set_user_data(%s) failed: %s\n",
2004 "regtp_ca_chainlen", gpg_strerror (err));
2005 for (i=0; i < depth; i++)
2006 ksba_cert_release (array[i]);
2007 *chainlen = (depth>1? 0:1);
2008 return 1;
2011 leave:
2012 /* Nothing special with this certificate. Mark the target
2013 certificate anyway to avoid duplicate lookups. */
2014 err = ksba_cert_set_user_data (cert, "regtp_ca_chainlen", "", 1);
2015 if (err)
2016 log_error ("ksba_set_user_data(%s) failed: %s\n",
2017 "regtp_ca_chainlen", gpg_strerror (err));
2018 for (i=0; i < depth; i++)
2019 ksba_cert_release (array[i]);
2020 return 0;