chiark / gitweb /
asshelp.c: add a lot of debug logging
[gnupg2.git] / g10 / trustdb.c
1 /* trustdb.c
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3  *               2008, 2012 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25
26 #ifndef DISABLE_REGEX
27 #include <sys/types.h>
28 #include <regex.h>
29 #endif /* !DISABLE_REGEX */
30
31 #include "gpg.h"
32 #include "status.h"
33 #include "iobuf.h"
34 #include "keydb.h"
35 #include "util.h"
36 #include "options.h"
37 #include "packet.h"
38 #include "main.h"
39 #include "mbox-util.h"
40 #include "i18n.h"
41 #include "tdbio.h"
42 #include "trustdb.h"
43 #include "tofu.h"
44
45
46 typedef struct key_item **KeyHashTable; /* see new_key_hash_table() */
47
48 /*
49  * Structure to keep track of keys, this is used as an array wherre
50  * the item right after the last one has a keyblock set to NULL.
51  * Maybe we can drop this thing and replace it by key_item
52  */
53 struct key_array
54 {
55   KBNODE keyblock;
56 };
57
58
59 /* Control information for the trust DB.  */
60 static struct
61 {
62   int init;
63   int level;
64   char *dbname;
65   int no_trustdb;
66 } trustdb_args;
67
68 /* Some globals.  */
69 static struct key_item *user_utk_list; /* temp. used to store --trusted-keys */
70 static struct key_item *utk_list;      /* all ultimately trusted keys */
71
72 static int pending_check_trustdb;
73
74 static int validate_keys (ctrl_t ctrl, int interactive);
75
76 \f
77 /**********************************************
78  ************* some helpers *******************
79  **********************************************/
80
81 static struct key_item *
82 new_key_item (void)
83 {
84   struct key_item *k;
85
86   k = xmalloc_clear (sizeof *k);
87   return k;
88 }
89
90 static void
91 release_key_items (struct key_item *k)
92 {
93   struct key_item *k2;
94
95   for (; k; k = k2)
96     {
97       k2 = k->next;
98       xfree (k->trust_regexp);
99       xfree (k);
100     }
101 }
102
103 #define KEY_HASH_TABLE_SIZE 1024
104
105 /*
106  * For fast keylook up we need a hash table.  Each byte of a KeyID
107  * should be distributed equally over the 256 possible values (except
108  * for v3 keyIDs but we consider them as not important here). So we
109  * can just use 10 bits to index a table of KEY_HASH_TABLE_SIZE key items.
110  * Possible optimization: Do not use key_items but other hash_table when the
111  * duplicates lists get too large.
112  */
113 static KeyHashTable
114 new_key_hash_table (void)
115 {
116   struct key_item **tbl;
117
118   tbl = xmalloc_clear (KEY_HASH_TABLE_SIZE * sizeof *tbl);
119   return tbl;
120 }
121
122 static void
123 release_key_hash_table (KeyHashTable tbl)
124 {
125   int i;
126
127   if (!tbl)
128     return;
129   for (i=0; i < KEY_HASH_TABLE_SIZE; i++)
130     release_key_items (tbl[i]);
131   xfree (tbl);
132 }
133
134 /*
135  * Returns: True if the keyID is in the given hash table
136  */
137 static int
138 test_key_hash_table (KeyHashTable tbl, u32 *kid)
139 {
140   struct key_item *k;
141
142   for (k = tbl[(kid[1] % KEY_HASH_TABLE_SIZE)]; k; k = k->next)
143     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
144       return 1;
145   return 0;
146 }
147
148 /*
149  * Add a new key to the hash table.  The key is identified by its key ID.
150  */
151 static void
152 add_key_hash_table (KeyHashTable tbl, u32 *kid)
153 {
154   int i = kid[1] % KEY_HASH_TABLE_SIZE;
155   struct key_item *k, *kk;
156
157   for (k = tbl[i]; k; k = k->next)
158     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
159       return; /* already in table */
160
161   kk = new_key_item ();
162   kk->kid[0] = kid[0];
163   kk->kid[1] = kid[1];
164   kk->next = tbl[i];
165   tbl[i] = kk;
166 }
167
168 /*
169  * Release a key_array
170  */
171 static void
172 release_key_array ( struct key_array *keys )
173 {
174     struct key_array *k;
175
176     if (keys) {
177         for (k=keys; k->keyblock; k++)
178             release_kbnode (k->keyblock);
179         xfree (keys);
180     }
181 }
182
183 \f
184 /*********************************************
185  **********  Initialization  *****************
186  *********************************************/
187
188
189
190 /*
191  * Used to register extra ultimately trusted keys - this has to be done
192  * before initializing the validation module.
193  * FIXME: Should be replaced by a function to add those keys to the trustdb.
194  */
195 void
196 tdb_register_trusted_keyid (u32 *keyid)
197 {
198   struct key_item *k;
199
200   k = new_key_item ();
201   k->kid[0] = keyid[0];
202   k->kid[1] = keyid[1];
203   k->next = user_utk_list;
204   user_utk_list = k;
205 }
206
207 void
208 tdb_register_trusted_key( const char *string )
209 {
210   gpg_error_t err;
211   KEYDB_SEARCH_DESC desc;
212
213   err = classify_user_id (string, &desc, 1);
214   if (err || desc.mode != KEYDB_SEARCH_MODE_LONG_KID )
215     {
216       log_error(_("'%s' is not a valid long keyID\n"), string );
217       return;
218     }
219
220   register_trusted_keyid(desc.u.kid);
221 }
222
223 /*
224  * Helper to add a key to the global list of ultimately trusted keys.
225  * Retruns: true = inserted, false = already in in list.
226  */
227 static int
228 add_utk (u32 *kid)
229 {
230   struct key_item *k;
231
232   if (tdb_keyid_is_utk (kid))
233     return 0;
234
235   k = new_key_item ();
236   k->kid[0] = kid[0];
237   k->kid[1] = kid[1];
238   k->ownertrust = TRUST_ULTIMATE;
239   k->next = utk_list;
240   utk_list = k;
241   if( opt.verbose > 1 )
242     log_info(_("key %s: accepted as trusted key\n"), keystr(kid));
243   return 1;
244 }
245
246
247 /****************
248  * Verify that all our secret keys are usable and put them into the utk_list.
249  */
250 static void
251 verify_own_keys(void)
252 {
253   TRUSTREC rec;
254   ulong recnum;
255   int rc;
256   struct key_item *k;
257
258   if (utk_list)
259     return;
260
261   /* scan the trustdb to find all ultimately trusted keys */
262   for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
263     {
264       if ( rec.rectype == RECTYPE_TRUST
265            && (rec.r.trust.ownertrust & TRUST_MASK) == TRUST_ULTIMATE)
266         {
267             byte *fpr = rec.r.trust.fingerprint;
268             int fprlen;
269             u32 kid[2];
270
271             /* Problem: We do only use fingerprints in the trustdb but
272              * we need the keyID here to indetify the key; we can only
273              * use that ugly hack to distinguish between 16 and 20
274              * butes fpr - it does not work always so we better change
275              * the whole validation code to only work with
276              * fingerprints */
277             fprlen = (!fpr[16] && !fpr[17] && !fpr[18] && !fpr[19])? 16:20;
278             keyid_from_fingerprint (fpr, fprlen, kid);
279             if (!add_utk (kid))
280               log_info(_("key %s occurs more than once in the trustdb\n"),
281                        keystr(kid));
282         }
283     }
284
285   /* Put any --trusted-key keys into the trustdb */
286   for (k = user_utk_list; k; k = k->next)
287     {
288       if ( add_utk (k->kid) )
289         { /* not yet in trustDB as ultimately trusted */
290           PKT_public_key pk;
291
292           memset (&pk, 0, sizeof pk);
293           rc = get_pubkey (&pk, k->kid);
294           if (rc)
295             log_info(_("key %s: no public key for trusted key - skipped\n"),
296                      keystr(k->kid));
297           else
298             {
299               tdb_update_ownertrust (&pk,
300                                      ((tdb_get_ownertrust (&pk) & ~TRUST_MASK)
301                                       | TRUST_ULTIMATE ));
302               release_public_key_parts (&pk);
303             }
304
305           log_info (_("key %s marked as ultimately trusted\n"),keystr(k->kid));
306         }
307     }
308
309   /* release the helper table table */
310   release_key_items (user_utk_list);
311   user_utk_list = NULL;
312   return;
313 }
314
315 /* Returns whether KID is on the list of ultimately trusted keys.  */
316 int
317 tdb_keyid_is_utk (u32 *kid)
318 {
319   struct key_item *k;
320
321   for (k = utk_list; k; k = k->next)
322     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
323       return 1;
324
325   return 0;
326 }
327
328 /* Return the list of ultimately trusted keys.  */
329 struct key_item *
330 tdb_utks (void)
331 {
332   return utk_list;
333 }
334 \f
335 /*********************************************
336  *********** TrustDB stuff *******************
337  *********************************************/
338
339 /*
340  * Read a record but die if it does not exist
341  */
342 static void
343 read_record (ulong recno, TRUSTREC *rec, int rectype )
344 {
345   int rc = tdbio_read_record (recno, rec, rectype);
346   if (rc)
347     {
348       log_error(_("trust record %lu, req type %d: read failed: %s\n"),
349                 recno, rec->rectype, gpg_strerror (rc) );
350       tdbio_invalid();
351     }
352   if (rectype != rec->rectype)
353     {
354       log_error(_("trust record %lu is not of requested type %d\n"),
355                 rec->recnum, rectype);
356       tdbio_invalid();
357     }
358 }
359
360 /*
361  * Write a record and die on error
362  */
363 static void
364 write_record (TRUSTREC *rec)
365 {
366   int rc = tdbio_write_record (rec);
367   if (rc)
368     {
369       log_error(_("trust record %lu, type %d: write failed: %s\n"),
370                             rec->recnum, rec->rectype, gpg_strerror (rc) );
371       tdbio_invalid();
372     }
373 }
374
375 /*
376  * sync the TrustDb and die on error
377  */
378 static void
379 do_sync(void)
380 {
381     int rc = tdbio_sync ();
382     if(rc)
383       {
384         log_error (_("trustdb: sync failed: %s\n"), gpg_strerror (rc) );
385         g10_exit(2);
386       }
387 }
388
389 const char *
390 trust_model_string (int model)
391 {
392   switch (model)
393     {
394     case TM_CLASSIC:  return "classic";
395     case TM_PGP:      return "pgp";
396     case TM_EXTERNAL: return "external";
397     case TM_TOFU:     return "tofu";
398     case TM_TOFU_PGP: return "tofu+pgp";
399     case TM_ALWAYS:   return "always";
400     case TM_DIRECT:   return "direct";
401     default:          return "unknown";
402     }
403 }
404
405 /****************
406  * Perform some checks over the trustdb
407  *  level 0: only open the db
408  *        1: used for initial program startup
409  */
410 int
411 setup_trustdb( int level, const char *dbname )
412 {
413     /* just store the args */
414     if( trustdb_args.init )
415         return 0;
416     trustdb_args.level = level;
417     trustdb_args.dbname = dbname? xstrdup(dbname): NULL;
418     return 0;
419 }
420
421 void
422 how_to_fix_the_trustdb ()
423 {
424   const char *name = trustdb_args.dbname;
425
426   if (!name)
427     name = "trustdb.gpg";
428
429   log_info (_("You may try to re-create the trustdb using the commands:\n"));
430   log_info ("  cd %s\n", default_homedir ());
431   log_info ("  %s --export-ownertrust > otrust.tmp\n", GPG_NAME);
432 #ifdef HAVE_W32_SYSTEM
433   log_info ("  del %s\n", name);
434 #else
435   log_info ("  rm %s\n", name);
436 #endif
437   log_info ("  %s --import-ownertrust < otrust.tmp\n", GPG_NAME);
438   log_info (_("If that does not work, please consult the manual\n"));
439 }
440
441
442 void
443 init_trustdb ()
444 {
445   int level = trustdb_args.level;
446   const char* dbname = trustdb_args.dbname;
447
448   if( trustdb_args.init )
449     return;
450
451   trustdb_args.init = 1;
452
453   if(level==0 || level==1)
454     {
455       int rc = tdbio_set_dbname( dbname, !!level, &trustdb_args.no_trustdb);
456       if( rc )
457         log_fatal("can't init trustdb: %s\n", gpg_strerror (rc) );
458     }
459   else
460     BUG();
461
462   if(opt.trust_model==TM_AUTO)
463     {
464       /* Try and set the trust model off of whatever the trustdb says
465          it is. */
466       opt.trust_model=tdbio_read_model();
467
468       /* Sanity check this ;) */
469       if(opt.trust_model != TM_CLASSIC
470          && opt.trust_model != TM_PGP
471          && opt.trust_model != TM_TOFU_PGP
472          && opt.trust_model != TM_TOFU
473          && opt.trust_model != TM_EXTERNAL)
474         {
475           log_info(_("unable to use unknown trust model (%d) - "
476                      "assuming %s trust model\n"),opt.trust_model,"pgp");
477           opt.trust_model = TM_PGP;
478         }
479
480       if(opt.verbose)
481         log_info(_("using %s trust model\n"),
482                  trust_model_string (opt.trust_model));
483     }
484
485   if (opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC
486       || opt.trust_model == TM_TOFU || opt.trust_model == TM_TOFU_PGP)
487     {
488       /* Verify the list of ultimately trusted keys and move the
489          --trusted-keys list there as well. */
490       if(level==1)
491         verify_own_keys();
492
493       if(!tdbio_db_matches_options())
494         pending_check_trustdb=1;
495     }
496 }
497
498
499 /****************
500  * Recreate the WoT but do not ask for new ownertrusts.  Special
501  * feature: In batch mode and without a forced yes, this is only done
502  * when a check is due.  This can be used to run the check from a crontab
503  */
504 void
505 check_trustdb (ctrl_t ctrl)
506 {
507   init_trustdb();
508   if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
509       || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU)
510     {
511       if (opt.batch && !opt.answer_yes)
512         {
513           ulong scheduled;
514
515           scheduled = tdbio_read_nextcheck ();
516           if (!scheduled)
517             {
518               log_info (_("no need for a trustdb check\n"));
519               return;
520             }
521
522           if (scheduled > make_timestamp ())
523             {
524               log_info (_("next trustdb check due at %s\n"),
525                         strtimestamp (scheduled));
526               return;
527             }
528         }
529
530       validate_keys (ctrl, 0);
531     }
532   else
533     log_info (_("no need for a trustdb check with '%s' trust model\n"),
534               trust_model_string(opt.trust_model));
535 }
536
537
538 /*
539  * Recreate the WoT.
540  */
541 void
542 update_trustdb (ctrl_t ctrl)
543 {
544   init_trustdb ();
545   if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
546       || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU)
547     validate_keys (ctrl, 1);
548   else
549     log_info (_("no need for a trustdb update with '%s' trust model\n"),
550               trust_model_string(opt.trust_model));
551 }
552
553 void
554 tdb_revalidation_mark (void)
555 {
556   init_trustdb();
557   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
558     return;
559
560   /* We simply set the time for the next check to 1 (far back in 1970)
561      so that a --update-trustdb will be scheduled.  */
562   if (tdbio_write_nextcheck (1))
563     do_sync ();
564   pending_check_trustdb = 1;
565 }
566
567 int
568 trustdb_pending_check(void)
569 {
570   return pending_check_trustdb;
571 }
572
573 /* If the trustdb is dirty, and we're interactive, update it.
574    Otherwise, check it unless no-auto-check-trustdb is set. */
575 void
576 tdb_check_or_update (ctrl_t ctrl)
577 {
578   if (trustdb_pending_check ())
579     {
580       if (opt.interactive)
581         update_trustdb (ctrl);
582       else if (!opt.no_auto_check_trustdb)
583         check_trustdb (ctrl);
584     }
585 }
586
587 void
588 read_trust_options(byte *trust_model,ulong *created,ulong *nextcheck,
589                    byte *marginals,byte *completes,byte *cert_depth,
590                    byte *min_cert_level)
591 {
592   TRUSTREC opts;
593
594   init_trustdb();
595   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
596     memset (&opts, 0, sizeof opts);
597   else
598     read_record (0, &opts, RECTYPE_VER);
599
600   if(trust_model)
601     *trust_model=opts.r.ver.trust_model;
602   if(created)
603     *created=opts.r.ver.created;
604   if(nextcheck)
605     *nextcheck=opts.r.ver.nextcheck;
606   if(marginals)
607     *marginals=opts.r.ver.marginals;
608   if(completes)
609     *completes=opts.r.ver.completes;
610   if(cert_depth)
611     *cert_depth=opts.r.ver.cert_depth;
612   if(min_cert_level)
613     *min_cert_level=opts.r.ver.min_cert_level;
614 }
615
616 /***********************************************
617  ***********  Ownertrust et al. ****************
618  ***********************************************/
619
620 static int
621 read_trust_record (PKT_public_key *pk, TRUSTREC *rec)
622 {
623   int rc;
624
625   init_trustdb();
626   rc = tdbio_search_trust_bypk (pk, rec);
627   if (rc)
628     {
629       if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
630         log_error ("trustdb: searching trust record failed: %s\n",
631                    gpg_strerror (rc));
632       return rc;
633     }
634
635   if (rec->rectype != RECTYPE_TRUST)
636     {
637       log_error ("trustdb: record %lu is not a trust record\n",
638                  rec->recnum);
639       return GPG_ERR_TRUSTDB;
640     }
641
642   return 0;
643 }
644
645 /****************
646  * Return the assigned ownertrust value for the given public key.
647  * The key should be the primary key.
648  */
649 unsigned int
650 tdb_get_ownertrust ( PKT_public_key *pk)
651 {
652   TRUSTREC rec;
653   gpg_error_t err;
654
655   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
656     return TRUST_UNKNOWN;
657
658   err = read_trust_record (pk, &rec);
659   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
660     return TRUST_UNKNOWN; /* no record yet */
661   if (err)
662     {
663       tdbio_invalid ();
664       return TRUST_UNKNOWN; /* actually never reached */
665     }
666
667   return rec.r.trust.ownertrust;
668 }
669
670
671 unsigned int
672 tdb_get_min_ownertrust (PKT_public_key *pk)
673 {
674   TRUSTREC rec;
675   gpg_error_t err;
676
677   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
678     return TRUST_UNKNOWN;
679
680   err = read_trust_record (pk, &rec);
681   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
682     return TRUST_UNKNOWN; /* no record yet */
683   if (err)
684     {
685       tdbio_invalid ();
686       return TRUST_UNKNOWN; /* actually never reached */
687     }
688
689   return rec.r.trust.min_ownertrust;
690 }
691
692
693 /*
694  * Set the trust value of the given public key to the new value.
695  * The key should be a primary one.
696  */
697 void
698 tdb_update_ownertrust (PKT_public_key *pk, unsigned int new_trust )
699 {
700   TRUSTREC rec;
701   gpg_error_t err;
702
703   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
704     return;
705
706   err = read_trust_record (pk, &rec);
707   if (!err)
708     {
709       if (DBG_TRUST)
710         log_debug ("update ownertrust from %u to %u\n",
711                    (unsigned int)rec.r.trust.ownertrust, new_trust );
712       if (rec.r.trust.ownertrust != new_trust)
713         {
714           rec.r.trust.ownertrust = new_trust;
715           write_record( &rec );
716           tdb_revalidation_mark ();
717           do_sync ();
718         }
719     }
720   else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
721     { /* no record yet - create a new one */
722       size_t dummy;
723
724       if (DBG_TRUST)
725         log_debug ("insert ownertrust %u\n", new_trust );
726
727       memset (&rec, 0, sizeof rec);
728       rec.recnum = tdbio_new_recnum ();
729       rec.rectype = RECTYPE_TRUST;
730       fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
731       rec.r.trust.ownertrust = new_trust;
732       write_record (&rec);
733       tdb_revalidation_mark ();
734       do_sync ();
735     }
736   else
737     {
738       tdbio_invalid ();
739     }
740 }
741
742 static void
743 update_min_ownertrust (u32 *kid, unsigned int new_trust )
744 {
745   PKT_public_key *pk;
746   TRUSTREC rec;
747   gpg_error_t err;
748
749   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
750     return;
751
752   pk = xmalloc_clear (sizeof *pk);
753   err = get_pubkey (pk, kid);
754   if (err)
755     {
756       log_error (_("public key %s not found: %s\n"),
757                  keystr (kid), gpg_strerror (err));
758       return;
759     }
760
761   err = read_trust_record (pk, &rec);
762   if (!err)
763     {
764       if (DBG_TRUST)
765         log_debug ("key %08lX%08lX: update min_ownertrust from %u to %u\n",
766                    (ulong)kid[0],(ulong)kid[1],
767                    (unsigned int)rec.r.trust.min_ownertrust,
768                    new_trust );
769       if (rec.r.trust.min_ownertrust != new_trust)
770         {
771           rec.r.trust.min_ownertrust = new_trust;
772           write_record( &rec );
773           tdb_revalidation_mark ();
774           do_sync ();
775         }
776     }
777   else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
778     { /* no record yet - create a new one */
779       size_t dummy;
780
781       if (DBG_TRUST)
782         log_debug ("insert min_ownertrust %u\n", new_trust );
783
784       memset (&rec, 0, sizeof rec);
785       rec.recnum = tdbio_new_recnum ();
786       rec.rectype = RECTYPE_TRUST;
787       fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
788       rec.r.trust.min_ownertrust = new_trust;
789       write_record (&rec);
790       tdb_revalidation_mark ();
791       do_sync ();
792     }
793   else
794     {
795       tdbio_invalid ();
796     }
797 }
798
799
800 /*
801  * Clear the ownertrust and min_ownertrust values.
802  *
803  * Return: True if a change actually happened.
804  */
805 int
806 tdb_clear_ownertrusts (PKT_public_key *pk)
807 {
808   TRUSTREC rec;
809   gpg_error_t err;
810
811   init_trustdb ();
812
813   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
814     return 0;
815
816   err = read_trust_record (pk, &rec);
817   if (!err)
818     {
819       if (DBG_TRUST)
820         {
821           log_debug ("clearing ownertrust (old value %u)\n",
822                      (unsigned int)rec.r.trust.ownertrust);
823           log_debug ("clearing min_ownertrust (old value %u)\n",
824                      (unsigned int)rec.r.trust.min_ownertrust);
825         }
826       if (rec.r.trust.ownertrust || rec.r.trust.min_ownertrust)
827         {
828           rec.r.trust.ownertrust = 0;
829           rec.r.trust.min_ownertrust = 0;
830           write_record( &rec );
831           tdb_revalidation_mark ();
832           do_sync ();
833           return 1;
834         }
835     }
836   else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
837     {
838       tdbio_invalid ();
839     }
840   return 0;
841 }
842
843 /*
844  * Note: Caller has to do a sync
845  */
846 static void
847 update_validity (PKT_public_key *pk, PKT_user_id *uid,
848                  int depth, int validity)
849 {
850   TRUSTREC trec, vrec;
851   gpg_error_t err;
852   ulong recno;
853
854   namehash_from_uid(uid);
855
856   err = read_trust_record (pk, &trec);
857   if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
858     {
859       tdbio_invalid ();
860       return;
861     }
862   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
863     {
864       /* No record yet - create a new one. */
865       size_t dummy;
866
867       memset (&trec, 0, sizeof trec);
868       trec.recnum = tdbio_new_recnum ();
869       trec.rectype = RECTYPE_TRUST;
870       fingerprint_from_pk (pk, trec.r.trust.fingerprint, &dummy);
871       trec.r.trust.ownertrust = 0;
872       }
873
874   /* locate an existing one */
875   recno = trec.r.trust.validlist;
876   while (recno)
877     {
878       read_record (recno, &vrec, RECTYPE_VALID);
879       if ( !memcmp (vrec.r.valid.namehash, uid->namehash, 20) )
880         break;
881       recno = vrec.r.valid.next;
882     }
883
884   if (!recno) /* insert a new validity record */
885     {
886       memset (&vrec, 0, sizeof vrec);
887       vrec.recnum = tdbio_new_recnum ();
888       vrec.rectype = RECTYPE_VALID;
889       memcpy (vrec.r.valid.namehash, uid->namehash, 20);
890       vrec.r.valid.next = trec.r.trust.validlist;
891       trec.r.trust.validlist = vrec.recnum;
892     }
893   vrec.r.valid.validity = validity;
894   vrec.r.valid.full_count = uid->help_full_count;
895   vrec.r.valid.marginal_count = uid->help_marginal_count;
896   write_record (&vrec);
897   trec.r.trust.depth = depth;
898   write_record (&trec);
899 }
900
901
902 /***********************************************
903  *********  Query trustdb values  **************
904  ***********************************************/
905
906 /* Return true if key is disabled.  Note that this is usually used via
907    the pk_is_disabled macro.  */
908 int
909 tdb_cache_disabled_value (PKT_public_key *pk)
910 {
911   gpg_error_t err;
912   TRUSTREC trec;
913   int disabled = 0;
914
915   if (pk->flags.disabled_valid)
916     return pk->flags.disabled;
917
918   init_trustdb();
919
920   if (trustdb_args.no_trustdb)
921     return 0;  /* No trustdb => not disabled.  */
922
923   err = read_trust_record (pk, &trec);
924   if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
925     {
926       tdbio_invalid ();
927       goto leave;
928     }
929   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
930     {
931       /* No record found, so assume not disabled.  */
932       goto leave;
933     }
934
935   if ((trec.r.trust.ownertrust & TRUST_FLAG_DISABLED))
936     disabled = 1;
937
938   /* Cache it for later so we don't need to look at the trustdb every
939      time */
940   pk->flags.disabled = disabled;
941   pk->flags.disabled_valid = 1;
942
943  leave:
944   return disabled;
945 }
946
947
948 void
949 tdb_check_trustdb_stale (ctrl_t ctrl)
950 {
951   static int did_nextcheck=0;
952
953   init_trustdb ();
954
955   if (trustdb_args.no_trustdb)
956     return;  /* No trustdb => can't be stale.  */
957
958   if (!did_nextcheck
959       && (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
960           || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU))
961     {
962       ulong scheduled;
963
964       did_nextcheck = 1;
965       scheduled = tdbio_read_nextcheck ();
966       if ((scheduled && scheduled <= make_timestamp ())
967           || pending_check_trustdb)
968         {
969           if (opt.no_auto_check_trustdb)
970             {
971               pending_check_trustdb = 1;
972               if (!opt.quiet)
973                 log_info (_("please do a --check-trustdb\n"));
974             }
975           else
976             {
977               if (!opt.quiet)
978                 log_info (_("checking the trustdb\n"));
979               validate_keys (ctrl, 0);
980             }
981         }
982     }
983 }
984
985 /*
986  * Return the validity information for KB/PK (at least one of them
987  * must be non-NULL).  This is the core of get_validity.  If SIG is
988  * not NULL, then the trust is being evaluated in the context of the
989  * provided signature.  This is used by the TOFU code to record
990  * statistics.
991  */
992 unsigned int
993 tdb_get_validity_core (ctrl_t ctrl,
994                        kbnode_t kb,
995                        PKT_public_key *pk, PKT_user_id *uid,
996                        PKT_public_key *main_pk,
997                        PKT_signature *sig,
998                        int may_ask)
999 {
1000   TRUSTREC trec, vrec;
1001   gpg_error_t err = 0;
1002   ulong recno;
1003 #ifdef USE_TOFU
1004   unsigned int tofu_validity = TRUST_UNKNOWN;
1005   int free_kb = 0;
1006 #endif
1007   unsigned int validity = TRUST_UNKNOWN;
1008
1009   if (kb && pk)
1010     log_assert (keyid_cmp (pk_main_keyid (pk),
1011                            pk_main_keyid (kb->pkt->pkt.public_key)) == 0);
1012
1013   if (! pk)
1014     {
1015       log_assert (kb);
1016       pk = kb->pkt->pkt.public_key;
1017     }
1018
1019 #ifndef USE_TOFU
1020   (void)sig;
1021   (void)may_ask;
1022 #endif
1023
1024   init_trustdb ();
1025
1026   /* If we have no trustdb (which also means it has not been created)
1027      and the trust-model is always, we don't know the validity -
1028      return immediately.  If we won't do that the tdbio code would try
1029      to open the trustdb and run into a fatal error.  */
1030   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
1031     return TRUST_UNKNOWN;
1032
1033   check_trustdb_stale (ctrl);
1034
1035   if(opt.trust_model==TM_DIRECT)
1036     {
1037       /* Note that this happens BEFORE any user ID stuff is checked.
1038          The direct trust model applies to keys as a whole. */
1039       validity = tdb_get_ownertrust (main_pk);
1040       goto leave;
1041     }
1042
1043 #ifdef USE_TOFU
1044   if (opt.trust_model == TM_TOFU || opt.trust_model == TM_TOFU_PGP)
1045     {
1046       kbnode_t n = NULL;
1047       strlist_t user_id_list = NULL;
1048       int done = 0;
1049
1050       /* If the caller didn't supply a user id then use all uids.  */
1051       if (! uid)
1052         {
1053           if (! kb)
1054             {
1055               kb = get_pubkeyblock (main_pk->keyid);
1056               free_kb = 1;
1057             }
1058           n = kb;
1059         }
1060
1061       if (DBG_TRUST && sig && sig->signers_uid)
1062         log_debug ("TOFU: only considering user id: '%s'\n",
1063                    sig->signers_uid);
1064
1065       while (!done && (uid || (n = find_next_kbnode (n, PKT_USER_ID))))
1066         {
1067           PKT_user_id *user_id;
1068           int expired = 0;
1069
1070           if (uid)
1071             {
1072               user_id = uid;
1073               /* If the caller specified a user id, then we only
1074                  process the specified user id and are done after the
1075                  first iteration.  */
1076               done = 1;
1077             }
1078           else
1079             user_id = n->pkt->pkt.user_id;
1080
1081           if (user_id->attrib_data)
1082             /* Skip user attributes.  */
1083             continue;
1084
1085           if (sig && sig->signers_uid)
1086             /* Make sure the UID matches.  */
1087             {
1088               char *email = mailbox_from_userid (user_id->name);
1089               if (!email || !*email || strcmp (sig->signers_uid, email) != 0)
1090                 {
1091                   if (DBG_TRUST)
1092                     log_debug ("TOFU: skipping user id '%s', which does"
1093                                " not match the signer's email ('%s')\n",
1094                                email, sig->signers_uid);
1095                   xfree (email);
1096                   continue;
1097                 }
1098               xfree (email);
1099             }
1100
1101           /* If the user id is revoked or expired, then skip it.  */
1102           if (user_id->is_revoked || user_id->is_expired)
1103             {
1104               if (DBG_TRUST)
1105                 {
1106                   char *s;
1107                   if (user_id->is_revoked && user_id->is_expired)
1108                     s = "revoked and expired";
1109                   else if (user_id->is_revoked)
1110                     s = "revoked";
1111                   else
1112                     s = "expire";
1113
1114                   log_debug ("TOFU: Ignoring %s user id (%s)\n",
1115                              s, user_id->name);
1116                 }
1117
1118               if (user_id->is_revoked)
1119                 continue;
1120
1121               expired = 1;
1122             }
1123
1124           add_to_strlist (&user_id_list, user_id->name);
1125           user_id_list->flags = expired;
1126         }
1127
1128       /* Process the user ids in the order they appear in the key
1129          block.  */
1130       strlist_rev (&user_id_list);
1131
1132       /* It only makes sense to observe any signature before getting
1133          the validity.  This is because if the current signature
1134          results in a conflict, then we damn well want to take that
1135          into account.  */
1136       if (sig)
1137         {
1138           err = tofu_register_signature (ctrl, main_pk, user_id_list,
1139                                          sig->digest, sig->digest_len,
1140                                          sig->timestamp, "unknown");
1141           if (err)
1142             {
1143               log_error ("TOFU: error registering signature: %s\n",
1144                          gpg_strerror (err));
1145
1146               tofu_validity = TRUST_UNKNOWN;
1147             }
1148         }
1149       if (! err)
1150         tofu_validity = tofu_get_validity (ctrl, main_pk, user_id_list,
1151                                            may_ask);
1152
1153       free_strlist (user_id_list);
1154       if (free_kb)
1155         release_kbnode (kb);
1156     }
1157 #endif /*USE_TOFU*/
1158
1159   if (opt.trust_model == TM_TOFU_PGP
1160       || opt.trust_model == TM_CLASSIC
1161       || opt.trust_model == TM_PGP)
1162     {
1163       err = read_trust_record (main_pk, &trec);
1164       if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1165         {
1166           tdbio_invalid ();
1167           return 0;
1168         }
1169       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1170         {
1171           /* No record found.  */
1172           validity = TRUST_UNKNOWN;
1173           goto leave;
1174         }
1175
1176       /* Loop over all user IDs */
1177       recno = trec.r.trust.validlist;
1178       validity = 0;
1179       while (recno)
1180         {
1181           read_record (recno, &vrec, RECTYPE_VALID);
1182
1183           if(uid)
1184             {
1185               /* If a user ID is given we return the validity for that
1186                  user ID ONLY.  If the namehash is not found, then
1187                  there is no validity at all (i.e. the user ID wasn't
1188                  signed). */
1189               if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1190                 {
1191                   validity=(vrec.r.valid.validity & TRUST_MASK);
1192                   break;
1193                 }
1194             }
1195           else
1196             {
1197               /* If no user ID is given, we take the maximum validity
1198                  over all user IDs */
1199               if (validity < (vrec.r.valid.validity & TRUST_MASK))
1200                 validity = (vrec.r.valid.validity & TRUST_MASK);
1201             }
1202
1203           recno = vrec.r.valid.next;
1204         }
1205
1206       if ((trec.r.trust.ownertrust & TRUST_FLAG_DISABLED))
1207         {
1208           validity |= TRUST_FLAG_DISABLED;
1209           pk->flags.disabled = 1;
1210         }
1211       else
1212         pk->flags.disabled = 0;
1213       pk->flags.disabled_valid = 1;
1214     }
1215
1216  leave:
1217 #ifdef USE_TOFU
1218   validity = tofu_wot_trust_combine (tofu_validity, validity);
1219 #else /*!USE_TOFU*/
1220   validity &= TRUST_MASK;
1221
1222   if (validity == TRUST_NEVER)
1223     /* TRUST_NEVER trumps everything else.  */
1224     validity |= TRUST_NEVER;
1225   if (validity == TRUST_EXPIRED)
1226     /* TRUST_EXPIRED trumps everything but TRUST_NEVER.  */
1227     validity |= TRUST_EXPIRED;
1228 #endif /*!USE_TOFU*/
1229
1230   if (opt.trust_model != TM_TOFU
1231       && pending_check_trustdb)
1232     validity |= TRUST_FLAG_PENDING_CHECK;
1233
1234   return validity;
1235 }
1236
1237
1238 static void
1239 get_validity_counts (PKT_public_key *pk, PKT_user_id *uid)
1240 {
1241   TRUSTREC trec, vrec;
1242   ulong recno;
1243
1244   if(pk==NULL || uid==NULL)
1245     BUG();
1246
1247   namehash_from_uid(uid);
1248
1249   uid->help_marginal_count=uid->help_full_count=0;
1250
1251   init_trustdb ();
1252
1253   if(read_trust_record (pk, &trec))
1254     return;
1255
1256   /* loop over all user IDs */
1257   recno = trec.r.trust.validlist;
1258   while (recno)
1259     {
1260       read_record (recno, &vrec, RECTYPE_VALID);
1261
1262       if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1263         {
1264           uid->help_marginal_count=vrec.r.valid.marginal_count;
1265           uid->help_full_count=vrec.r.valid.full_count;
1266           /*  es_printf("Fetched marginal %d, full %d\n",uid->help_marginal_count,uid->help_full_count); */
1267           break;
1268         }
1269
1270       recno = vrec.r.valid.next;
1271     }
1272 }
1273
1274 void
1275 list_trust_path( const char *username )
1276 {
1277   (void)username;
1278 }
1279
1280 /****************
1281  * Enumerate all keys, which are needed to build all trust paths for
1282  * the given key.  This function does not return the key itself or
1283  * the ultimate key (the last point in cerificate chain).  Only
1284  * certificate chains which ends up at an ultimately trusted key
1285  * are listed.  If ownertrust or validity is not NULL, the corresponding
1286  * value for the returned LID is also returned in these variable(s).
1287  *
1288  *  1) create a void pointer and initialize it to NULL
1289  *  2) pass this void pointer by reference to this function.
1290  *     Set lid to the key you want to enumerate and pass it by reference.
1291  *  3) call this function as long as it does not return -1
1292  *     to indicate EOF. LID does contain the next key used to build the web
1293  *  4) Always call this function a last time with LID set to NULL,
1294  *     so that it can free its context.
1295  *
1296  * Returns: -1 on EOF or the level of the returned LID
1297  */
1298 int
1299 enum_cert_paths( void **context, ulong *lid,
1300                  unsigned *ownertrust, unsigned *validity )
1301 {
1302   (void)context;
1303   (void)lid;
1304   (void)ownertrust;
1305   (void)validity;
1306   return -1;
1307 }
1308
1309
1310 /****************
1311  * Print the current path
1312  */
1313 void
1314 enum_cert_paths_print (void **context, FILE *fp,
1315                        int refresh, ulong selected_lid)
1316 {
1317   (void)context;
1318   (void)fp;
1319   (void)refresh;
1320   (void)selected_lid;
1321 }
1322
1323
1324 \f
1325 /****************************************
1326  *********** NEW NEW NEW ****************
1327  ****************************************/
1328
1329 static int
1330 ask_ownertrust (ctrl_t ctrl, u32 *kid, int minimum)
1331 {
1332   PKT_public_key *pk;
1333   int rc;
1334   int ot;
1335
1336   pk = xmalloc_clear (sizeof *pk);
1337   rc = get_pubkey (pk, kid);
1338   if (rc)
1339     {
1340       log_error (_("public key %s not found: %s\n"),
1341                  keystr(kid), gpg_strerror (rc) );
1342       return TRUST_UNKNOWN;
1343     }
1344
1345   if(opt.force_ownertrust)
1346     {
1347       log_info("force trust for key %s to %s\n",
1348                keystr(kid),trust_value_to_string(opt.force_ownertrust));
1349       tdb_update_ownertrust (pk, opt.force_ownertrust);
1350       ot=opt.force_ownertrust;
1351     }
1352   else
1353     {
1354       ot=edit_ownertrust (ctrl, pk, 0);
1355       if(ot>0)
1356         ot = tdb_get_ownertrust (pk);
1357       else if(ot==0)
1358         ot = minimum?minimum:TRUST_UNDEFINED;
1359       else
1360         ot = -1; /* quit */
1361     }
1362
1363   free_public_key( pk );
1364
1365   return ot;
1366 }
1367
1368
1369 static void
1370 mark_keyblock_seen (KeyHashTable tbl, KBNODE node)
1371 {
1372   for ( ;node; node = node->next )
1373     if (node->pkt->pkttype == PKT_PUBLIC_KEY
1374         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1375       {
1376         u32 aki[2];
1377
1378         keyid_from_pk (node->pkt->pkt.public_key, aki);
1379         add_key_hash_table (tbl, aki);
1380       }
1381 }
1382
1383
1384 static void
1385 dump_key_array (int depth, struct key_array *keys)
1386 {
1387   struct key_array *kar;
1388
1389   for (kar=keys; kar->keyblock; kar++)
1390     {
1391       KBNODE node = kar->keyblock;
1392       u32 kid[2];
1393
1394       keyid_from_pk(node->pkt->pkt.public_key, kid);
1395       es_printf ("%d:%08lX%08lX:K::%c::::\n",
1396                  depth, (ulong)kid[0], (ulong)kid[1], '?');
1397
1398       for (; node; node = node->next)
1399         {
1400           if (node->pkt->pkttype == PKT_USER_ID)
1401             {
1402               int len = node->pkt->pkt.user_id->len;
1403
1404               if (len > 30)
1405                 len = 30;
1406               es_printf ("%d:%08lX%08lX:U:::%c:::",
1407                          depth, (ulong)kid[0], (ulong)kid[1],
1408                          (node->flag & 4)? 'f':
1409                          (node->flag & 2)? 'm':
1410                          (node->flag & 1)? 'q':'-');
1411               es_write_sanitized (es_stdout, node->pkt->pkt.user_id->name,
1412                                   len, ":", NULL);
1413               es_putc (':', es_stdout);
1414               es_putc ('\n', es_stdout);
1415             }
1416         }
1417     }
1418 }
1419
1420
1421 static void
1422 store_validation_status (int depth, KBNODE keyblock, KeyHashTable stored)
1423 {
1424   KBNODE node;
1425   int status;
1426   int any = 0;
1427
1428   for (node=keyblock; node; node = node->next)
1429     {
1430       if (node->pkt->pkttype == PKT_USER_ID)
1431         {
1432           PKT_user_id *uid = node->pkt->pkt.user_id;
1433           if (node->flag & 4)
1434             status = TRUST_FULLY;
1435           else if (node->flag & 2)
1436             status = TRUST_MARGINAL;
1437           else if (node->flag & 1)
1438             status = TRUST_UNDEFINED;
1439           else
1440             status = 0;
1441
1442           if (status)
1443             {
1444               update_validity (keyblock->pkt->pkt.public_key,
1445                                uid, depth, status);
1446
1447               mark_keyblock_seen(stored,keyblock);
1448
1449               any = 1;
1450             }
1451         }
1452     }
1453
1454   if (any)
1455     do_sync ();
1456 }
1457
1458
1459 /* Returns a sanitized copy of the regexp (which might be "", but not
1460    NULL). */
1461 #ifndef DISABLE_REGEX
1462 static char *
1463 sanitize_regexp(const char *old)
1464 {
1465   size_t start=0,len=strlen(old),idx=0;
1466   int escaped=0,standard_bracket=0;
1467   char *new=xmalloc((len*2)+1); /* enough to \-escape everything if we
1468                                    have to */
1469
1470   /* There are basically two commonly-used regexps here.  GPG and most
1471      versions of PGP use "<[^>]+[@.]example\.com>$" and PGP (9)
1472      command line uses "example.com" (i.e. whatever the user specfies,
1473      and we can't expect users know to use "\." instead of ".").  So
1474      here are the rules: we're allowed to start with "<[^>]+[@.]" and
1475      end with ">$" or start and end with nothing.  In between, the
1476      only legal regex character is ".", and everything else gets
1477      escaped.  Part of the gotcha here is that some regex packages
1478      allow more than RFC-4880 requires.  For example, 4880 has no "{}"
1479      operator, but GNU regex does.  Commenting removes these operators
1480      from consideration.  A possible future enhancement is to use
1481      commenting to effectively back off a given regex to the Henry
1482      Spencer syntax in 4880. -dshaw */
1483
1484   /* Are we bracketed between "<[^>]+[@.]" and ">$" ? */
1485   if(len>=12 && strncmp(old,"<[^>]+[@.]",10)==0
1486      && old[len-2]=='>' && old[len-1]=='$')
1487     {
1488       strcpy(new,"<[^>]+[@.]");
1489       idx=strlen(new);
1490       standard_bracket=1;
1491       start+=10;
1492       len-=2;
1493     }
1494
1495   /* Walk the remaining characters and ensure that everything that is
1496      left is not an operational regex character. */
1497   for(;start<len;start++)
1498     {
1499       if(!escaped && old[start]=='\\')
1500         escaped=1;
1501       else if(!escaped && old[start]!='.')
1502         new[idx++]='\\';
1503       else
1504         escaped=0;
1505
1506       new[idx++]=old[start];
1507     }
1508
1509   new[idx]='\0';
1510
1511   /* Note that the (sub)string we look at might end with a bare "\".
1512      If it does, leave it that way.  If the regexp actually ended with
1513      ">$", then it was escaping the ">" and is fine.  If the regexp
1514      actually ended with the bare "\", then it's an illegal regexp and
1515      regcomp should kick it out. */
1516
1517   if(standard_bracket)
1518     strcat(new,">$");
1519
1520   return new;
1521 }
1522 #endif /*!DISABLE_REGEX*/
1523
1524 /* Used by validate_one_keyblock to confirm a regexp within a trust
1525    signature.  Returns 1 for match, and 0 for no match or regex
1526    error. */
1527 static int
1528 check_regexp(const char *expr,const char *string)
1529 {
1530 #ifdef DISABLE_REGEX
1531   (void)expr;
1532   (void)string;
1533   /* When DISABLE_REGEX is defined, assume all regexps do not
1534      match. */
1535   return 0;
1536 #else
1537   int ret;
1538   char *regexp;
1539
1540   regexp=sanitize_regexp(expr);
1541
1542 #ifdef __riscos__
1543   ret=riscos_check_regexp(expr, string, DBG_TRUST);
1544 #else
1545   {
1546     regex_t pat;
1547
1548     ret=regcomp(&pat,regexp,REG_ICASE|REG_NOSUB|REG_EXTENDED);
1549     if(ret==0)
1550       {
1551         ret=regexec(&pat,string,0,NULL,0);
1552         regfree(&pat);
1553         ret=(ret==0);
1554       }
1555   }
1556 #endif
1557
1558   if(DBG_TRUST)
1559     log_debug("regexp '%s' ('%s') on '%s': %s\n",
1560               regexp,expr,string,ret==0?"YES":"NO");
1561
1562   xfree(regexp);
1563
1564   return ret;
1565 #endif
1566 }
1567
1568 /*
1569  * Return true if the key is signed by one of the keys in the given
1570  * key ID list.  User IDs with a valid signature are marked by node
1571  * flags as follows:
1572  *  flag bit 0: There is at least one signature
1573  *           1: There is marginal confidence that this is a legitimate uid
1574  *           2: There is full confidence that this is a legitimate uid.
1575  *           8: Used for internal purposes.
1576  *           9: Ditto (in mark_usable_uid_certs())
1577  *          10: Ditto (ditto)
1578  * This function assumes that all kbnode flags are cleared on entry.
1579  */
1580 static int
1581 validate_one_keyblock (KBNODE kb, struct key_item *klist,
1582                        u32 curtime, u32 *next_expire)
1583 {
1584   struct key_item *kr;
1585   KBNODE node, uidnode=NULL;
1586   PKT_user_id *uid=NULL;
1587   PKT_public_key *pk = kb->pkt->pkt.public_key;
1588   u32 main_kid[2];
1589   int issigned=0, any_signed = 0;
1590
1591   keyid_from_pk(pk, main_kid);
1592   for (node=kb; node; node = node->next)
1593     {
1594       /* A bit of discussion here: is it better for the web of trust
1595          to be built among only self-signed uids?  On the one hand, a
1596          self-signed uid is a statement that the key owner definitely
1597          intended that uid to be there, but on the other hand, a
1598          signed (but not self-signed) uid does carry trust, of a sort,
1599          even if it is a statement being made by people other than the
1600          key owner "through" the uids on the key owner's key.  I'm
1601          going with the latter.  However, if the user ID was
1602          explicitly revoked, or passively allowed to expire, that
1603          should stop validity through the user ID until it is
1604          resigned.  -dshaw */
1605
1606       if (node->pkt->pkttype == PKT_USER_ID
1607           && !node->pkt->pkt.user_id->is_revoked
1608           && !node->pkt->pkt.user_id->is_expired)
1609         {
1610           if (uidnode && issigned)
1611             {
1612               if (uid->help_full_count >= opt.completes_needed
1613                   || uid->help_marginal_count >= opt.marginals_needed )
1614                 uidnode->flag |= 4;
1615               else if (uid->help_full_count || uid->help_marginal_count)
1616                 uidnode->flag |= 2;
1617               uidnode->flag |= 1;
1618               any_signed = 1;
1619             }
1620           uidnode = node;
1621           uid=uidnode->pkt->pkt.user_id;
1622
1623           /* If the selfsig is going to expire... */
1624           if(uid->expiredate && uid->expiredate<*next_expire)
1625             *next_expire = uid->expiredate;
1626
1627           issigned = 0;
1628           get_validity_counts(pk,uid);
1629           mark_usable_uid_certs (kb, uidnode, main_kid, klist,
1630                                  curtime, next_expire);
1631         }
1632       else if (node->pkt->pkttype == PKT_SIGNATURE
1633                && (node->flag & (1<<8)) && uid)
1634         {
1635           /* Note that we are only seeing unrevoked sigs here */
1636           PKT_signature *sig = node->pkt->pkt.signature;
1637
1638           kr = is_in_klist (klist, sig);
1639           /* If the trust_regexp does not match, it's as if the sig
1640              did not exist.  This is safe for non-trust sigs as well
1641              since we don't accept a regexp on the sig unless it's a
1642              trust sig. */
1643           if (kr && (!kr->trust_regexp
1644                      || !(opt.trust_model == TM_PGP
1645                           || opt.trust_model == TM_TOFU_PGP)
1646                      || (uidnode
1647                          && check_regexp(kr->trust_regexp,
1648                                          uidnode->pkt->pkt.user_id->name))))
1649             {
1650               /* Are we part of a trust sig chain?  We always favor
1651                  the latest trust sig, rather than the greater or
1652                  lesser trust sig or value.  I could make a decent
1653                  argument for any of these cases, but this seems to be
1654                  what PGP does, and I'd like to be compatible. -dms */
1655               if ((opt.trust_model == TM_PGP
1656                    || opt.trust_model == TM_TOFU_PGP)
1657                   && sig->trust_depth
1658                   && pk->trust_timestamp <= sig->timestamp)
1659                 {
1660                   unsigned char depth;
1661
1662                   /* If the depth on the signature is less than the
1663                      chain currently has, then use the signature depth
1664                      so we don't increase the depth beyond what the
1665                      signer wanted.  If the depth on the signature is
1666                      more than the chain currently has, then use the
1667                      chain depth so we use as much of the signature
1668                      depth as the chain will permit.  An ultimately
1669                      trusted signature can restart the depth to
1670                      whatever level it likes. */
1671
1672                   if (sig->trust_depth < kr->trust_depth
1673                       || kr->ownertrust == TRUST_ULTIMATE)
1674                     depth = sig->trust_depth;
1675                   else
1676                     depth = kr->trust_depth;
1677
1678                   if (depth)
1679                     {
1680                       if(DBG_TRUST)
1681                         log_debug ("trust sig on %s, sig depth is %d,"
1682                                    " kr depth is %d\n",
1683                                    uidnode->pkt->pkt.user_id->name,
1684                                    sig->trust_depth,
1685                                    kr->trust_depth);
1686
1687                       /* If we got here, we know that:
1688
1689                          this is a trust sig.
1690
1691                          it's a newer trust sig than any previous trust
1692                          sig on this key (not uid).
1693
1694                          it is legal in that it was either generated by an
1695                          ultimate key, or a key that was part of a trust
1696                          chain, and the depth does not violate the
1697                          original trust sig.
1698
1699                          if there is a regexp attached, it matched
1700                          successfully.
1701                       */
1702
1703                       if (DBG_TRUST)
1704                         log_debug ("replacing trust value %d with %d and "
1705                                    "depth %d with %d\n",
1706                                    pk->trust_value,sig->trust_value,
1707                                    pk->trust_depth,depth);
1708
1709                       pk->trust_value = sig->trust_value;
1710                       pk->trust_depth = depth-1;
1711
1712                       /* If the trust sig contains a regexp, record it
1713                          on the pk for the next round. */
1714                       if (sig->trust_regexp)
1715                         pk->trust_regexp = sig->trust_regexp;
1716                     }
1717                 }
1718
1719               if (kr->ownertrust == TRUST_ULTIMATE)
1720                 uid->help_full_count = opt.completes_needed;
1721               else if (kr->ownertrust == TRUST_FULLY)
1722                 uid->help_full_count++;
1723               else if (kr->ownertrust == TRUST_MARGINAL)
1724                 uid->help_marginal_count++;
1725               issigned = 1;
1726             }
1727         }
1728     }
1729
1730   if (uidnode && issigned)
1731     {
1732       if (uid->help_full_count >= opt.completes_needed
1733           || uid->help_marginal_count >= opt.marginals_needed )
1734         uidnode->flag |= 4;
1735       else if (uid->help_full_count || uid->help_marginal_count)
1736         uidnode->flag |= 2;
1737       uidnode->flag |= 1;
1738       any_signed = 1;
1739     }
1740
1741   return any_signed;
1742 }
1743
1744
1745 static int
1746 search_skipfnc (void *opaque, u32 *kid, int dummy_uid_no)
1747 {
1748   (void)dummy_uid_no;
1749   return test_key_hash_table ((KeyHashTable)opaque, kid);
1750 }
1751
1752
1753 /*
1754  * Scan all keys and return a key_array of all suitable keys from
1755  * kllist.  The caller has to pass keydb handle so that we don't use
1756  * to create our own.  Returns either a key_array or NULL in case of
1757  * an error.  No results found are indicated by an empty array.
1758  * Caller hast to release the returned array.
1759  */
1760 static struct key_array *
1761 validate_key_list (KEYDB_HANDLE hd, KeyHashTable full_trust,
1762                    struct key_item *klist, u32 curtime, u32 *next_expire)
1763 {
1764   KBNODE keyblock = NULL;
1765   struct key_array *keys = NULL;
1766   size_t nkeys, maxkeys;
1767   int rc;
1768   KEYDB_SEARCH_DESC desc;
1769
1770   maxkeys = 1000;
1771   keys = xmalloc ((maxkeys+1) * sizeof *keys);
1772   nkeys = 0;
1773
1774   rc = keydb_search_reset (hd);
1775   if (rc)
1776     {
1777       log_error ("keydb_search_reset failed: %s\n", gpg_strerror (rc));
1778       xfree (keys);
1779       return NULL;
1780     }
1781
1782   memset (&desc, 0, sizeof desc);
1783   desc.mode = KEYDB_SEARCH_MODE_FIRST;
1784   desc.skipfnc = search_skipfnc;
1785   desc.skipfncvalue = full_trust;
1786   rc = keydb_search (hd, &desc, 1, NULL);
1787   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1788     {
1789       keys[nkeys].keyblock = NULL;
1790       return keys;
1791     }
1792   if (rc)
1793     {
1794       log_error ("keydb_search(first) failed: %s\n", gpg_strerror (rc));
1795       goto die;
1796     }
1797
1798   desc.mode = KEYDB_SEARCH_MODE_NEXT; /* change mode */
1799   do
1800     {
1801       PKT_public_key *pk;
1802
1803       rc = keydb_get_keyblock (hd, &keyblock);
1804       if (rc)
1805         {
1806           log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1807           goto die;
1808         }
1809
1810       if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1811         {
1812           log_debug ("ooops: invalid pkttype %d encountered\n",
1813                      keyblock->pkt->pkttype);
1814           dump_kbnode (keyblock);
1815           release_kbnode(keyblock);
1816           continue;
1817         }
1818
1819       /* prepare the keyblock for further processing */
1820       merge_keys_and_selfsig (keyblock);
1821       clear_kbnode_flags (keyblock);
1822       pk = keyblock->pkt->pkt.public_key;
1823       if (pk->has_expired || pk->flags.revoked)
1824         {
1825           /* it does not make sense to look further at those keys */
1826           mark_keyblock_seen (full_trust, keyblock);
1827         }
1828       else if (validate_one_keyblock (keyblock, klist, curtime, next_expire))
1829         {
1830           KBNODE node;
1831
1832           if (pk->expiredate && pk->expiredate >= curtime
1833               && pk->expiredate < *next_expire)
1834             *next_expire = pk->expiredate;
1835
1836           if (nkeys == maxkeys) {
1837             maxkeys += 1000;
1838             keys = xrealloc (keys, (maxkeys+1) * sizeof *keys);
1839           }
1840           keys[nkeys++].keyblock = keyblock;
1841
1842           /* Optimization - if all uids are fully trusted, then we
1843              never need to consider this key as a candidate again. */
1844
1845           for (node=keyblock; node; node = node->next)
1846             if (node->pkt->pkttype == PKT_USER_ID && !(node->flag & 4))
1847               break;
1848
1849           if(node==NULL)
1850             mark_keyblock_seen (full_trust, keyblock);
1851
1852           keyblock = NULL;
1853         }
1854
1855       release_kbnode (keyblock);
1856       keyblock = NULL;
1857     }
1858   while (!(rc = keydb_search (hd, &desc, 1, NULL)));
1859
1860   if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
1861     {
1862       log_error ("keydb_search_next failed: %s\n", gpg_strerror (rc));
1863       goto die;
1864     }
1865
1866   keys[nkeys].keyblock = NULL;
1867   return keys;
1868
1869  die:
1870   keys[nkeys].keyblock = NULL;
1871   release_key_array (keys);
1872   return NULL;
1873 }
1874
1875 /* Caller must sync */
1876 static void
1877 reset_trust_records(void)
1878 {
1879   TRUSTREC rec;
1880   ulong recnum;
1881   int count = 0, nreset = 0;
1882
1883   for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
1884     {
1885       if(rec.rectype==RECTYPE_TRUST)
1886         {
1887           count++;
1888           if(rec.r.trust.min_ownertrust)
1889             {
1890               rec.r.trust.min_ownertrust=0;
1891               write_record(&rec);
1892             }
1893
1894         }
1895       else if(rec.rectype==RECTYPE_VALID
1896               && ((rec.r.valid.validity&TRUST_MASK)
1897                   || rec.r.valid.marginal_count
1898                   || rec.r.valid.full_count))
1899         {
1900           rec.r.valid.validity &= ~TRUST_MASK;
1901           rec.r.valid.marginal_count=rec.r.valid.full_count=0;
1902           nreset++;
1903           write_record(&rec);
1904         }
1905
1906     }
1907
1908   if (opt.verbose)
1909     {
1910       log_info (ngettext("%d key processed",
1911                          "%d keys processed",
1912                          count), count);
1913       log_printf (ngettext(" (%d validity count cleared)\n",
1914                            " (%d validity counts cleared)\n",
1915                            nreset), nreset);
1916     }
1917 }
1918
1919 /*
1920  * Run the key validation procedure.
1921  *
1922  * This works this way:
1923  * Step 1: Find all ultimately trusted keys (UTK).
1924  *         mark them all as seen and put them into klist.
1925  * Step 2: loop max_cert_times
1926  * Step 3:   if OWNERTRUST of any key in klist is undefined
1927  *             ask user to assign ownertrust
1928  * Step 4:   Loop over all keys in the keyDB which are not marked seen
1929  * Step 5:     if key is revoked or expired
1930  *                mark key as seen
1931  *                continue loop at Step 4
1932  * Step 6:     For each user ID of that key signed by a key in klist
1933  *                Calculate validity by counting trusted signatures.
1934  *                Set validity of user ID
1935  * Step 7:     If any signed user ID was found
1936  *                mark key as seen
1937  *             End Loop
1938  * Step 8:   Build a new klist from all fully trusted keys from step 6
1939  *           End Loop
1940  *         Ready
1941  *
1942  */
1943 static int
1944 validate_keys (ctrl_t ctrl, int interactive)
1945 {
1946   int rc = 0;
1947   int quit=0;
1948   struct key_item *klist = NULL;
1949   struct key_item *k;
1950   struct key_array *keys = NULL;
1951   struct key_array *kar;
1952   KEYDB_HANDLE kdb = NULL;
1953   KBNODE node;
1954   int depth;
1955   int ot_unknown, ot_undefined, ot_never, ot_marginal, ot_full, ot_ultimate;
1956   KeyHashTable stored,used,full_trust;
1957   u32 start_time, next_expire;
1958
1959   /* Make sure we have all sigs cached.  TODO: This is going to
1960      require some architectural re-thinking, as it is agonizingly slow.
1961      Perhaps combine this with reset_trust_records(), or only check
1962      the caches on keys that are actually involved in the web of
1963      trust. */
1964   keydb_rebuild_caches(0);
1965
1966   kdb = keydb_new ();
1967   if (!kdb)
1968     return gpg_error_from_syserror ();
1969
1970   start_time = make_timestamp ();
1971   next_expire = 0xffffffff; /* set next expire to the year 2106 */
1972   stored = new_key_hash_table ();
1973   used = new_key_hash_table ();
1974   full_trust = new_key_hash_table ();
1975
1976   reset_trust_records();
1977
1978   /* Fixme: Instead of always building a UTK list, we could just build it
1979    * here when needed */
1980   if (!utk_list)
1981     {
1982       if (!opt.quiet)
1983         log_info (_("no ultimately trusted keys found\n"));
1984       goto leave;
1985     }
1986
1987   /* mark all UTKs as used and fully_trusted and set validity to
1988      ultimate */
1989   for (k=utk_list; k; k = k->next)
1990     {
1991       KBNODE keyblock;
1992       PKT_public_key *pk;
1993
1994       keyblock = get_pubkeyblock (k->kid);
1995       if (!keyblock)
1996         {
1997           log_error (_("public key of ultimately"
1998                        " trusted key %s not found\n"), keystr(k->kid));
1999           continue;
2000         }
2001       mark_keyblock_seen (used, keyblock);
2002       mark_keyblock_seen (stored, keyblock);
2003       mark_keyblock_seen (full_trust, keyblock);
2004       pk = keyblock->pkt->pkt.public_key;
2005       for (node=keyblock; node; node = node->next)
2006         {
2007           if (node->pkt->pkttype == PKT_USER_ID)
2008             update_validity (pk, node->pkt->pkt.user_id, 0, TRUST_ULTIMATE);
2009         }
2010       if ( pk->expiredate && pk->expiredate >= start_time
2011            && pk->expiredate < next_expire)
2012         next_expire = pk->expiredate;
2013
2014       release_kbnode (keyblock);
2015       do_sync ();
2016     }
2017
2018   if (opt.trust_model == TM_TOFU)
2019     /* In the TOFU trust model, we only need to save the ultimately
2020        trusted keys.  */
2021     goto leave;
2022
2023   klist = utk_list;
2024
2025   if (!opt.quiet)
2026     log_info ("marginals needed: %d  completes needed: %d  trust model: %s\n",
2027               opt.marginals_needed, opt.completes_needed,
2028               trust_model_string (opt.trust_model));
2029
2030   for (depth=0; depth < opt.max_cert_depth; depth++)
2031     {
2032       int valids=0,key_count;
2033       /* See whether we should assign ownertrust values to the keys in
2034          klist.  */
2035       ot_unknown = ot_undefined = ot_never = 0;
2036       ot_marginal = ot_full = ot_ultimate = 0;
2037       for (k=klist; k; k = k->next)
2038         {
2039           int min=0;
2040
2041           /* 120 and 60 are as per RFC2440 */
2042           if(k->trust_value>=120)
2043             min=TRUST_FULLY;
2044           else if(k->trust_value>=60)
2045             min=TRUST_MARGINAL;
2046
2047           if(min!=k->min_ownertrust)
2048             update_min_ownertrust(k->kid,min);
2049
2050           if (interactive && k->ownertrust == TRUST_UNKNOWN)
2051             {
2052               k->ownertrust = ask_ownertrust (ctrl, k->kid,min);
2053
2054               if (k->ownertrust == (unsigned int)(-1))
2055                 {
2056                   quit=1;
2057                   goto leave;
2058                 }
2059             }
2060
2061           /* This can happen during transition from an old trustdb
2062              before trust sigs.  It can also happen if a user uses two
2063              different versions of GnuPG or changes the --trust-model
2064              setting. */
2065           if(k->ownertrust<min)
2066             {
2067               if(DBG_TRUST)
2068                 log_debug("key %08lX%08lX:"
2069                           " overriding ownertrust '%s' with '%s'\n",
2070                           (ulong)k->kid[0],(ulong)k->kid[1],
2071                           trust_value_to_string(k->ownertrust),
2072                           trust_value_to_string(min));
2073
2074               k->ownertrust=min;
2075             }
2076
2077           if (k->ownertrust == TRUST_UNKNOWN)
2078             ot_unknown++;
2079           else if (k->ownertrust == TRUST_UNDEFINED)
2080             ot_undefined++;
2081           else if (k->ownertrust == TRUST_NEVER)
2082             ot_never++;
2083           else if (k->ownertrust == TRUST_MARGINAL)
2084             ot_marginal++;
2085           else if (k->ownertrust == TRUST_FULLY)
2086             ot_full++;
2087           else if (k->ownertrust == TRUST_ULTIMATE)
2088             ot_ultimate++;
2089
2090           valids++;
2091         }
2092
2093       /* Find all keys which are signed by a key in kdlist */
2094       keys = validate_key_list (kdb, full_trust, klist,
2095                                 start_time, &next_expire);
2096       if (!keys)
2097         {
2098           log_error ("validate_key_list failed\n");
2099           rc = GPG_ERR_GENERAL;
2100           goto leave;
2101         }
2102
2103       for (key_count=0, kar=keys; kar->keyblock; kar++, key_count++)
2104         ;
2105
2106       /* Store the calculated valididation status somewhere */
2107       if (opt.verbose > 1 && DBG_TRUST)
2108         dump_key_array (depth, keys);
2109
2110       for (kar=keys; kar->keyblock; kar++)
2111           store_validation_status (depth, kar->keyblock, stored);
2112
2113       if (!opt.quiet)
2114         log_info (_("depth: %d  valid: %3d  signed: %3d"
2115                     "  trust: %d-, %dq, %dn, %dm, %df, %du\n"),
2116                   depth, valids, key_count, ot_unknown, ot_undefined,
2117                   ot_never, ot_marginal, ot_full, ot_ultimate );
2118
2119       /* Build a new kdlist from all fully valid keys in KEYS */
2120       if (klist != utk_list)
2121         release_key_items (klist);
2122       klist = NULL;
2123       for (kar=keys; kar->keyblock; kar++)
2124         {
2125           for (node=kar->keyblock; node; node = node->next)
2126             {
2127               if (node->pkt->pkttype == PKT_USER_ID && (node->flag & 4))
2128                 {
2129                   u32 kid[2];
2130
2131                   /* have we used this key already? */
2132                   keyid_from_pk (kar->keyblock->pkt->pkt.public_key, kid);
2133                   if(test_key_hash_table(used,kid)==0)
2134                     {
2135                       /* Normally we add both the primary and subkey
2136                          ids to the hash via mark_keyblock_seen, but
2137                          since we aren't using this hash as a skipfnc,
2138                          that doesn't matter here. */
2139                       add_key_hash_table (used,kid);
2140                       k = new_key_item ();
2141                       k->kid[0]=kid[0];
2142                       k->kid[1]=kid[1];
2143                       k->ownertrust =
2144                         (tdb_get_ownertrust
2145                          (kar->keyblock->pkt->pkt.public_key) & TRUST_MASK);
2146                       k->min_ownertrust = tdb_get_min_ownertrust
2147                         (kar->keyblock->pkt->pkt.public_key);
2148                       k->trust_depth=
2149                         kar->keyblock->pkt->pkt.public_key->trust_depth;
2150                       k->trust_value=
2151                         kar->keyblock->pkt->pkt.public_key->trust_value;
2152                       if(kar->keyblock->pkt->pkt.public_key->trust_regexp)
2153                         k->trust_regexp=
2154                           xstrdup(kar->keyblock->pkt->
2155                                    pkt.public_key->trust_regexp);
2156                       k->next = klist;
2157                       klist = k;
2158                       break;
2159                     }
2160                 }
2161             }
2162         }
2163       release_key_array (keys);
2164       keys = NULL;
2165       if (!klist)
2166         break; /* no need to dive in deeper */
2167     }
2168
2169  leave:
2170   keydb_release (kdb);
2171   release_key_array (keys);
2172   if (klist != utk_list)
2173     release_key_items (klist);
2174   release_key_hash_table (full_trust);
2175   release_key_hash_table (used);
2176   release_key_hash_table (stored);
2177   if (!rc && !quit) /* mark trustDB as checked */
2178     {
2179       int rc2;
2180
2181       if (next_expire == 0xffffffff || next_expire < start_time )
2182         tdbio_write_nextcheck (0);
2183       else
2184         {
2185           tdbio_write_nextcheck (next_expire);
2186           if (!opt.quiet)
2187             log_info (_("next trustdb check due at %s\n"),
2188                       strtimestamp (next_expire));
2189         }
2190
2191       rc2 = tdbio_update_version_record ();
2192       if (rc2)
2193         {
2194           log_error (_("unable to update trustdb version record: "
2195                        "write failed: %s\n"), gpg_strerror (rc2));
2196           tdbio_invalid ();
2197         }
2198
2199       do_sync ();
2200       pending_check_trustdb = 0;
2201     }
2202
2203   return rc;
2204 }