LCOV - code coverage report
Current view: top level - g10 - trustdb.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 480 931 51.6 %
Date: 2016-11-29 15:00:56 Functions: 37 51 72.5 %

          Line data    Source code
       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             : 
      77             : /**********************************************
      78             :  ************* some helpers *******************
      79             :  **********************************************/
      80             : 
      81             : static struct key_item *
      82          46 : new_key_item (void)
      83             : {
      84             :   struct key_item *k;
      85             : 
      86          46 :   k = xmalloc_clear (sizeof *k);
      87          46 :   return k;
      88             : }
      89             : 
      90             : static void
      91        9376 : release_key_items (struct key_item *k)
      92             : {
      93             :   struct key_item *k2;
      94             : 
      95        9391 :   for (; k; k = k2)
      96             :     {
      97          15 :       k2 = k->next;
      98          15 :       xfree (k->trust_regexp);
      99          15 :       xfree (k);
     100             :     }
     101        9376 : }
     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           9 : new_key_hash_table (void)
     115             : {
     116             :   struct key_item **tbl;
     117             : 
     118           9 :   tbl = xmalloc_clear (KEY_HASH_TABLE_SIZE * sizeof *tbl);
     119           9 :   return tbl;
     120             : }
     121             : 
     122             : static void
     123           9 : release_key_hash_table (KeyHashTable tbl)
     124             : {
     125             :   int i;
     126             : 
     127           9 :   if (!tbl)
     128           9 :     return;
     129        9225 :   for (i=0; i < KEY_HASH_TABLE_SIZE; i++)
     130        9216 :     release_key_items (tbl[i]);
     131           9 :   xfree (tbl);
     132             : }
     133             : 
     134             : /*
     135             :  * Returns: True if the keyID is in the given hash table
     136             :  */
     137             : static int
     138           2 : test_key_hash_table (KeyHashTable tbl, u32 *kid)
     139             : {
     140             :   struct key_item *k;
     141             : 
     142           2 :   for (k = tbl[(kid[1] % KEY_HASH_TABLE_SIZE)]; k; k = k->next)
     143           2 :     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
     144           2 :       return 1;
     145           0 :   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          12 : add_key_hash_table (KeyHashTable tbl, u32 *kid)
     153             : {
     154          12 :   int i = kid[1] % KEY_HASH_TABLE_SIZE;
     155             :   struct key_item *k, *kk;
     156             : 
     157          12 :   for (k = tbl[i]; k; k = k->next)
     158           0 :     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
     159          12 :       return; /* already in table */
     160             : 
     161          12 :   kk = new_key_item ();
     162          12 :   kk->kid[0] = kid[0];
     163          12 :   kk->kid[1] = kid[1];
     164          12 :   kk->next = tbl[i];
     165          12 :   tbl[i] = kk;
     166             : }
     167             : 
     168             : /*
     169             :  * Release a key_array
     170             :  */
     171             : static void
     172           5 : release_key_array ( struct key_array *keys )
     173             : {
     174             :     struct key_array *k;
     175             : 
     176           5 :     if (keys) {
     177           2 :         for (k=keys; k->keyblock; k++)
     178           0 :             release_kbnode (k->keyblock);
     179           2 :         xfree (keys);
     180             :     }
     181           5 : }
     182             : 
     183             : 
     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           3 : tdb_register_trusted_keyid (u32 *keyid)
     197             : {
     198             :   struct key_item *k;
     199             : 
     200           3 :   k = new_key_item ();
     201           3 :   k->kid[0] = keyid[0];
     202           3 :   k->kid[1] = keyid[1];
     203           3 :   k->next = user_utk_list;
     204           3 :   user_utk_list = k;
     205           3 : }
     206             : 
     207             : void
     208           0 : tdb_register_trusted_key( const char *string )
     209             : {
     210             :   gpg_error_t err;
     211             :   KEYDB_SEARCH_DESC desc;
     212             : 
     213           0 :   err = classify_user_id (string, &desc, 1);
     214           0 :   if (err || desc.mode != KEYDB_SEARCH_MODE_LONG_KID )
     215             :     {
     216           0 :       log_error(_("'%s' is not a valid long keyID\n"), string );
     217           0 :       return;
     218             :     }
     219             : 
     220           0 :   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          31 : add_utk (u32 *kid)
     229             : {
     230             :   struct key_item *k;
     231             : 
     232          31 :   if (tdb_keyid_is_utk (kid))
     233           0 :     return 0;
     234             : 
     235          31 :   k = new_key_item ();
     236          31 :   k->kid[0] = kid[0];
     237          31 :   k->kid[1] = kid[1];
     238          31 :   k->ownertrust = TRUST_ULTIMATE;
     239          31 :   k->next = utk_list;
     240          31 :   utk_list = k;
     241          31 :   if( opt.verbose > 1 )
     242           0 :     log_info(_("key %s: accepted as trusted key\n"), keystr(kid));
     243          31 :   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         158 : verify_own_keys(void)
     252             : {
     253             :   TRUSTREC rec;
     254             :   ulong recnum;
     255             :   int rc;
     256             :   struct key_item *k;
     257             : 
     258         158 :   if (utk_list)
     259           0 :     return;
     260             : 
     261             :   /* scan the trustdb to find all ultimately trusted keys */
     262        4779 :   for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
     263             :     {
     264        4621 :       if ( rec.rectype == RECTYPE_TRUST
     265          29 :            && (rec.r.trust.ownertrust & TRUST_MASK) == TRUST_ULTIMATE)
     266             :         {
     267          28 :             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          28 :             fprlen = (!fpr[16] && !fpr[17] && !fpr[18] && !fpr[19])? 16:20;
     278          28 :             keyid_from_fingerprint (fpr, fprlen, kid);
     279          28 :             if (!add_utk (kid))
     280           0 :               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         161 :   for (k = user_utk_list; k; k = k->next)
     287             :     {
     288           3 :       if ( add_utk (k->kid) )
     289             :         { /* not yet in trustDB as ultimately trusted */
     290             :           PKT_public_key pk;
     291             : 
     292           3 :           memset (&pk, 0, sizeof pk);
     293           3 :           rc = get_pubkey (&pk, k->kid);
     294           3 :           if (rc)
     295           0 :             log_info(_("key %s: no public key for trusted key - skipped\n"),
     296           0 :                      keystr(k->kid));
     297             :           else
     298             :             {
     299           3 :               tdb_update_ownertrust (&pk,
     300           3 :                                      ((tdb_get_ownertrust (&pk) & ~TRUST_MASK)
     301             :                                       | TRUST_ULTIMATE ));
     302           3 :               release_public_key_parts (&pk);
     303             :             }
     304             : 
     305           3 :           log_info (_("key %s marked as ultimately trusted\n"),keystr(k->kid));
     306             :         }
     307             :     }
     308             : 
     309             :   /* release the helper table table */
     310         158 :   release_key_items (user_utk_list);
     311         158 :   user_utk_list = NULL;
     312         158 :   return;
     313             : }
     314             : 
     315             : /* Returns whether KID is on the list of ultimately trusted keys.  */
     316             : int
     317         372 : tdb_keyid_is_utk (u32 *kid)
     318             : {
     319             :   struct key_item *k;
     320             : 
     321         427 :   for (k = utk_list; k; k = k->next)
     322          77 :     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
     323          22 :       return 1;
     324             : 
     325         350 :   return 0;
     326             : }
     327             : 
     328             : /* Return the list of ultimately trusted keys.  */
     329             : struct key_item *
     330         103 : tdb_utks (void)
     331             : {
     332         103 :   return utk_list;
     333             : }
     334             : 
     335             : /*********************************************
     336             :  *********** TrustDB stuff *******************
     337             :  *********************************************/
     338             : 
     339             : /*
     340             :  * Read a record but die if it does not exist
     341             :  */
     342             : static void
     343          74 : read_record (ulong recno, TRUSTREC *rec, int rectype )
     344             : {
     345          74 :   int rc = tdbio_read_record (recno, rec, rectype);
     346          74 :   if (rc)
     347             :     {
     348           0 :       log_error(_("trust record %lu, req type %d: read failed: %s\n"),
     349             :                 recno, rec->rectype, gpg_strerror (rc) );
     350           0 :       tdbio_invalid();
     351             :     }
     352          74 :   if (rectype != rec->rectype)
     353             :     {
     354           0 :       log_error(_("trust record %lu is not of requested type %d\n"),
     355             :                 rec->recnum, rectype);
     356           0 :       tdbio_invalid();
     357             :     }
     358          74 : }
     359             : 
     360             : /*
     361             :  * Write a record and die on error
     362             :  */
     363             : static void
     364          11 : write_record (TRUSTREC *rec)
     365             : {
     366          11 :   int rc = tdbio_write_record (rec);
     367          11 :   if (rc)
     368             :     {
     369           0 :       log_error(_("trust record %lu, type %d: write failed: %s\n"),
     370             :                             rec->recnum, rec->rectype, gpg_strerror (rc) );
     371           0 :       tdbio_invalid();
     372             :     }
     373          11 : }
     374             : 
     375             : /*
     376             :  * sync the TrustDb and die on error
     377             :  */
     378             : static void
     379          14 : do_sync(void)
     380             : {
     381          14 :     int rc = tdbio_sync ();
     382          14 :     if(rc)
     383             :       {
     384           0 :         log_error (_("trustdb: sync failed: %s\n"), gpg_strerror (rc) );
     385           0 :         g10_exit(2);
     386             :       }
     387          14 : }
     388             : 
     389             : const char *
     390          34 : trust_model_string (int model)
     391             : {
     392          34 :   switch (model)
     393             :     {
     394           0 :     case TM_CLASSIC:  return "classic";
     395           8 :     case TM_PGP:      return "pgp";
     396           0 :     case TM_EXTERNAL: return "external";
     397          26 :     case TM_TOFU:     return "tofu";
     398           0 :     case TM_TOFU_PGP: return "tofu+pgp";
     399           0 :     case TM_ALWAYS:   return "always";
     400           0 :     case TM_DIRECT:   return "direct";
     401           0 :     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        1129 : setup_trustdb( int level, const char *dbname )
     412             : {
     413             :     /* just store the args */
     414        1129 :     if( trustdb_args.init )
     415           0 :         return 0;
     416        1129 :     trustdb_args.level = level;
     417        1129 :     trustdb_args.dbname = dbname? xstrdup(dbname): NULL;
     418        1129 :     return 0;
     419             : }
     420             : 
     421             : void
     422           0 : how_to_fix_the_trustdb ()
     423             : {
     424           0 :   const char *name = trustdb_args.dbname;
     425             : 
     426           0 :   if (!name)
     427           0 :     name = "trustdb.gpg";
     428             : 
     429           0 :   log_info (_("You may try to re-create the trustdb using the commands:\n"));
     430           0 :   log_info ("  cd %s\n", default_homedir ());
     431           0 :   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           0 :   log_info ("  rm %s\n", name);
     436             : #endif
     437           0 :   log_info ("  %s --import-ownertrust < otrust.tmp\n", GPG_NAME);
     438           0 :   log_info (_("If that does not work, please consult the manual\n"));
     439           0 : }
     440             : 
     441             : 
     442             : void
     443        2329 : init_trustdb ()
     444             : {
     445        2329 :   int level = trustdb_args.level;
     446        2329 :   const char* dbname = trustdb_args.dbname;
     447             : 
     448        2329 :   if( trustdb_args.init )
     449        3931 :     return;
     450             : 
     451         727 :   trustdb_args.init = 1;
     452             : 
     453         727 :   if(level==0 || level==1)
     454         727 :     {
     455         727 :       int rc = tdbio_set_dbname( dbname, !!level, &trustdb_args.no_trustdb);
     456         727 :       if( rc )
     457           0 :         log_fatal("can't init trustdb: %s\n", gpg_strerror (rc) );
     458             :     }
     459             :   else
     460           0 :     BUG();
     461             : 
     462         727 :   if(opt.trust_model==TM_AUTO)
     463             :     {
     464             :       /* Try and set the trust model off of whatever the trustdb says
     465             :          it is. */
     466          72 :       opt.trust_model=tdbio_read_model();
     467             : 
     468             :       /* Sanity check this ;) */
     469          72 :       if(opt.trust_model != TM_CLASSIC
     470          72 :          && opt.trust_model != TM_PGP
     471           0 :          && opt.trust_model != TM_TOFU_PGP
     472           0 :          && opt.trust_model != TM_TOFU
     473           0 :          && opt.trust_model != TM_EXTERNAL)
     474             :         {
     475           0 :           log_info(_("unable to use unknown trust model (%d) - "
     476           0 :                      "assuming %s trust model\n"),opt.trust_model,"pgp");
     477           0 :           opt.trust_model = TM_PGP;
     478             :         }
     479             : 
     480          72 :       if(opt.verbose)
     481           0 :         log_info(_("using %s trust model\n"),
     482           0 :                  trust_model_string (opt.trust_model));
     483             :     }
     484             : 
     485         727 :   if (opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC
     486         655 :       || 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         158 :       if(level==1)
     491         158 :         verify_own_keys();
     492             : 
     493         158 :       if(!tdbio_db_matches_options())
     494          86 :         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           4 : check_trustdb (ctrl_t ctrl)
     506             : {
     507           4 :   init_trustdb();
     508           4 :   if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
     509           0 :       || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU)
     510             :     {
     511           4 :       if (opt.batch && !opt.answer_yes)
     512             :         {
     513             :           ulong scheduled;
     514             : 
     515           3 :           scheduled = tdbio_read_nextcheck ();
     516           3 :           if (!scheduled)
     517             :             {
     518           1 :               log_info (_("no need for a trustdb check\n"));
     519           1 :               return;
     520             :             }
     521             : 
     522           2 :           if (scheduled > make_timestamp ())
     523             :             {
     524           0 :               log_info (_("next trustdb check due at %s\n"),
     525             :                         strtimestamp (scheduled));
     526           0 :               return;
     527             :             }
     528             :         }
     529             : 
     530           3 :       validate_keys (ctrl, 0);
     531             :     }
     532             :   else
     533           0 :     log_info (_("no need for a trustdb check with '%s' trust model\n"),
     534           0 :               trust_model_string(opt.trust_model));
     535             : }
     536             : 
     537             : 
     538             : /*
     539             :  * Recreate the WoT.
     540             :  */
     541             : void
     542           0 : update_trustdb (ctrl_t ctrl)
     543             : {
     544           0 :   init_trustdb ();
     545           0 :   if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
     546           0 :       || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU)
     547           0 :     validate_keys (ctrl, 1);
     548             :   else
     549           0 :     log_info (_("no need for a trustdb update with '%s' trust model\n"),
     550           0 :               trust_model_string(opt.trust_model));
     551           0 : }
     552             : 
     553             : void
     554          17 : tdb_revalidation_mark (void)
     555             : {
     556          17 :   init_trustdb();
     557          17 :   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
     558          18 :     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          16 :   if (tdbio_write_nextcheck (1))
     563           5 :     do_sync ();
     564          16 :   pending_check_trustdb = 1;
     565             : }
     566             : 
     567             : int
     568          70 : trustdb_pending_check(void)
     569             : {
     570          70 :   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          70 : tdb_check_or_update (ctrl_t ctrl)
     577             : {
     578          70 :   if (trustdb_pending_check ())
     579             :     {
     580           9 :       if (opt.interactive)
     581           0 :         update_trustdb (ctrl);
     582           9 :       else if (!opt.no_auto_check_trustdb)
     583           0 :         check_trustdb (ctrl);
     584             :     }
     585          70 : }
     586             : 
     587             : void
     588          95 : 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          95 :   init_trustdb();
     595          95 :   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
     596          31 :     memset (&opts, 0, sizeof opts);
     597             :   else
     598          64 :     read_record (0, &opts, RECTYPE_VER);
     599             : 
     600          95 :   if(trust_model)
     601          95 :     *trust_model=opts.r.ver.trust_model;
     602          95 :   if(created)
     603          95 :     *created=opts.r.ver.created;
     604          95 :   if(nextcheck)
     605          95 :     *nextcheck=opts.r.ver.nextcheck;
     606          95 :   if(marginals)
     607          95 :     *marginals=opts.r.ver.marginals;
     608          95 :   if(completes)
     609          95 :     *completes=opts.r.ver.completes;
     610          95 :   if(cert_depth)
     611          95 :     *cert_depth=opts.r.ver.cert_depth;
     612          95 :   if(min_cert_level)
     613          95 :     *min_cert_level=opts.r.ver.min_cert_level;
     614          95 : }
     615             : 
     616             : /***********************************************
     617             :  ***********  Ownertrust et al. ****************
     618             :  ***********************************************/
     619             : 
     620             : static int
     621         299 : read_trust_record (PKT_public_key *pk, TRUSTREC *rec)
     622             : {
     623             :   int rc;
     624             : 
     625         299 :   init_trustdb();
     626         299 :   rc = tdbio_search_trust_bypk (pk, rec);
     627         299 :   if (rc)
     628             :     {
     629         261 :       if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
     630           0 :         log_error ("trustdb: searching trust record failed: %s\n",
     631             :                    gpg_strerror (rc));
     632         261 :       return rc;
     633             :     }
     634             : 
     635          38 :   if (rec->rectype != RECTYPE_TRUST)
     636             :     {
     637           0 :       log_error ("trustdb: record %lu is not a trust record\n",
     638             :                  rec->recnum);
     639           0 :       return GPG_ERR_TRUSTDB;
     640             :     }
     641             : 
     642          38 :   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         106 : tdb_get_ownertrust ( PKT_public_key *pk)
     651             : {
     652             :   TRUSTREC rec;
     653             :   gpg_error_t err;
     654             : 
     655         106 :   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
     656          31 :     return TRUST_UNKNOWN;
     657             : 
     658          75 :   err = read_trust_record (pk, &rec);
     659          75 :   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
     660          63 :     return TRUST_UNKNOWN; /* no record yet */
     661          12 :   if (err)
     662             :     {
     663           0 :       tdbio_invalid ();
     664           0 :       return TRUST_UNKNOWN; /* actually never reached */
     665             :     }
     666             : 
     667          12 :   return rec.r.trust.ownertrust;
     668             : }
     669             : 
     670             : 
     671             : unsigned int
     672         100 : tdb_get_min_ownertrust (PKT_public_key *pk)
     673             : {
     674             :   TRUSTREC rec;
     675             :   gpg_error_t err;
     676             : 
     677         100 :   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
     678          31 :     return TRUST_UNKNOWN;
     679             : 
     680          69 :   err = read_trust_record (pk, &rec);
     681          69 :   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
     682          60 :     return TRUST_UNKNOWN; /* no record yet */
     683           9 :   if (err)
     684             :     {
     685           0 :       tdbio_invalid ();
     686           0 :       return TRUST_UNKNOWN; /* actually never reached */
     687             :     }
     688             : 
     689           9 :   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           6 : tdb_update_ownertrust (PKT_public_key *pk, unsigned int new_trust )
     699             : {
     700             :   TRUSTREC rec;
     701             :   gpg_error_t err;
     702             : 
     703           6 :   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
     704           6 :     return;
     705             : 
     706           6 :   err = read_trust_record (pk, &rec);
     707           6 :   if (!err)
     708             :     {
     709           3 :       if (DBG_TRUST)
     710           0 :         log_debug ("update ownertrust from %u to %u\n",
     711           0 :                    (unsigned int)rec.r.trust.ownertrust, new_trust );
     712           3 :       if (rec.r.trust.ownertrust != new_trust)
     713             :         {
     714           0 :           rec.r.trust.ownertrust = new_trust;
     715           0 :           write_record( &rec );
     716           0 :           tdb_revalidation_mark ();
     717           0 :           do_sync ();
     718             :         }
     719             :     }
     720           3 :   else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
     721             :     { /* no record yet - create a new one */
     722             :       size_t dummy;
     723             : 
     724           3 :       if (DBG_TRUST)
     725           0 :         log_debug ("insert ownertrust %u\n", new_trust );
     726             : 
     727           3 :       memset (&rec, 0, sizeof rec);
     728           3 :       rec.recnum = tdbio_new_recnum ();
     729           3 :       rec.rectype = RECTYPE_TRUST;
     730           3 :       fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
     731           3 :       rec.r.trust.ownertrust = new_trust;
     732           3 :       write_record (&rec);
     733           3 :       tdb_revalidation_mark ();
     734           3 :       do_sync ();
     735             :     }
     736             :   else
     737             :     {
     738           0 :       tdbio_invalid ();
     739             :     }
     740             : }
     741             : 
     742             : static void
     743           0 : 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           0 :   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
     750           0 :     return;
     751             : 
     752           0 :   pk = xmalloc_clear (sizeof *pk);
     753           0 :   err = get_pubkey (pk, kid);
     754           0 :   if (err)
     755             :     {
     756           0 :       log_error (_("public key %s not found: %s\n"),
     757             :                  keystr (kid), gpg_strerror (err));
     758           0 :       return;
     759             :     }
     760             : 
     761           0 :   err = read_trust_record (pk, &rec);
     762           0 :   if (!err)
     763             :     {
     764           0 :       if (DBG_TRUST)
     765           0 :         log_debug ("key %08lX%08lX: update min_ownertrust from %u to %u\n",
     766           0 :                    (ulong)kid[0],(ulong)kid[1],
     767           0 :                    (unsigned int)rec.r.trust.min_ownertrust,
     768             :                    new_trust );
     769           0 :       if (rec.r.trust.min_ownertrust != new_trust)
     770             :         {
     771           0 :           rec.r.trust.min_ownertrust = new_trust;
     772           0 :           write_record( &rec );
     773           0 :           tdb_revalidation_mark ();
     774           0 :           do_sync ();
     775             :         }
     776             :     }
     777           0 :   else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
     778             :     { /* no record yet - create a new one */
     779             :       size_t dummy;
     780             : 
     781           0 :       if (DBG_TRUST)
     782           0 :         log_debug ("insert min_ownertrust %u\n", new_trust );
     783             : 
     784           0 :       memset (&rec, 0, sizeof rec);
     785           0 :       rec.recnum = tdbio_new_recnum ();
     786           0 :       rec.rectype = RECTYPE_TRUST;
     787           0 :       fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
     788           0 :       rec.r.trust.min_ownertrust = new_trust;
     789           0 :       write_record (&rec);
     790           0 :       tdb_revalidation_mark ();
     791           0 :       do_sync ();
     792             :     }
     793             :   else
     794             :     {
     795           0 :       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         235 : tdb_clear_ownertrusts (PKT_public_key *pk)
     807             : {
     808             :   TRUSTREC rec;
     809             :   gpg_error_t err;
     810             : 
     811         235 :   init_trustdb ();
     812             : 
     813         235 :   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
     814         207 :     return 0;
     815             : 
     816          28 :   err = read_trust_record (pk, &rec);
     817          28 :   if (!err)
     818             :     {
     819           1 :       if (DBG_TRUST)
     820             :         {
     821           0 :           log_debug ("clearing ownertrust (old value %u)\n",
     822           0 :                      (unsigned int)rec.r.trust.ownertrust);
     823           0 :           log_debug ("clearing min_ownertrust (old value %u)\n",
     824           0 :                      (unsigned int)rec.r.trust.min_ownertrust);
     825             :         }
     826           1 :       if (rec.r.trust.ownertrust || rec.r.trust.min_ownertrust)
     827             :         {
     828           1 :           rec.r.trust.ownertrust = 0;
     829           1 :           rec.r.trust.min_ownertrust = 0;
     830           1 :           write_record( &rec );
     831           1 :           tdb_revalidation_mark ();
     832           1 :           do_sync ();
     833           1 :           return 1;
     834             :         }
     835             :     }
     836          27 :   else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
     837             :     {
     838           0 :       tdbio_invalid ();
     839             :     }
     840          27 :   return 0;
     841             : }
     842             : 
     843             : /*
     844             :  * Note: Caller has to do a sync
     845             :  */
     846             : static void
     847           3 : 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           3 :   namehash_from_uid(uid);
     855             : 
     856           3 :   err = read_trust_record (pk, &trec);
     857           3 :   if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
     858             :     {
     859           0 :       tdbio_invalid ();
     860           3 :       return;
     861             :     }
     862           3 :   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
     863             :     {
     864             :       /* No record yet - create a new one. */
     865             :       size_t dummy;
     866             : 
     867           0 :       memset (&trec, 0, sizeof trec);
     868           0 :       trec.recnum = tdbio_new_recnum ();
     869           0 :       trec.rectype = RECTYPE_TRUST;
     870           0 :       fingerprint_from_pk (pk, trec.r.trust.fingerprint, &dummy);
     871           0 :       trec.r.trust.ownertrust = 0;
     872             :       }
     873             : 
     874             :   /* locate an existing one */
     875           3 :   recno = trec.r.trust.validlist;
     876           7 :   while (recno)
     877             :     {
     878           2 :       read_record (recno, &vrec, RECTYPE_VALID);
     879           2 :       if ( !memcmp (vrec.r.valid.namehash, uid->namehash, 20) )
     880           1 :         break;
     881           1 :       recno = vrec.r.valid.next;
     882             :     }
     883             : 
     884           3 :   if (!recno) /* insert a new validity record */
     885             :     {
     886           2 :       memset (&vrec, 0, sizeof vrec);
     887           2 :       vrec.recnum = tdbio_new_recnum ();
     888           2 :       vrec.rectype = RECTYPE_VALID;
     889           2 :       memcpy (vrec.r.valid.namehash, uid->namehash, 20);
     890           2 :       vrec.r.valid.next = trec.r.trust.validlist;
     891           2 :       trec.r.trust.validlist = vrec.recnum;
     892             :     }
     893           3 :   vrec.r.valid.validity = validity;
     894           3 :   vrec.r.valid.full_count = uid->help_full_count;
     895           3 :   vrec.r.valid.marginal_count = uid->help_marginal_count;
     896           3 :   write_record (&vrec);
     897           3 :   trec.r.trust.depth = depth;
     898           3 :   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         314 : tdb_cache_disabled_value (PKT_public_key *pk)
     910             : {
     911             :   gpg_error_t err;
     912             :   TRUSTREC trec;
     913         314 :   int disabled = 0;
     914             : 
     915         314 :   if (pk->flags.disabled_valid)
     916           0 :     return pk->flags.disabled;
     917             : 
     918         314 :   init_trustdb();
     919             : 
     920         314 :   if (trustdb_args.no_trustdb)
     921         241 :     return 0;  /* No trustdb => not disabled.  */
     922             : 
     923          73 :   err = read_trust_record (pk, &trec);
     924          73 :   if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
     925             :     {
     926           0 :       tdbio_invalid ();
     927           0 :       goto leave;
     928             :     }
     929          73 :   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
     930             :     {
     931             :       /* No record found, so assume not disabled.  */
     932          70 :       goto leave;
     933             :     }
     934             : 
     935           3 :   if ((trec.r.trust.ownertrust & TRUST_FLAG_DISABLED))
     936           0 :     disabled = 1;
     937             : 
     938             :   /* Cache it for later so we don't need to look at the trustdb every
     939             :      time */
     940           3 :   pk->flags.disabled = disabled;
     941           3 :   pk->flags.disabled_valid = 1;
     942             : 
     943             :  leave:
     944          73 :   return disabled;
     945             : }
     946             : 
     947             : 
     948             : void
     949         432 : tdb_check_trustdb_stale (ctrl_t ctrl)
     950             : {
     951             :   static int did_nextcheck=0;
     952             : 
     953         432 :   init_trustdb ();
     954             : 
     955         432 :   if (trustdb_args.no_trustdb)
     956         463 :     return;  /* No trustdb => can't be stale.  */
     957             : 
     958         401 :   if (!did_nextcheck
     959         184 :       && (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
     960         153 :           || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU))
     961             :     {
     962             :       ulong scheduled;
     963             : 
     964         117 :       did_nextcheck = 1;
     965         117 :       scheduled = tdbio_read_nextcheck ();
     966         117 :       if ((scheduled && scheduled <= make_timestamp ())
     967          81 :           || pending_check_trustdb)
     968             :         {
     969          86 :           if (opt.no_auto_check_trustdb)
     970             :             {
     971          86 :               pending_check_trustdb = 1;
     972          86 :               if (!opt.quiet)
     973          86 :                 log_info (_("please do a --check-trustdb\n"));
     974             :             }
     975             :           else
     976             :             {
     977           0 :               if (!opt.quiet)
     978           0 :                 log_info (_("checking the trustdb\n"));
     979           0 :               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         932 : 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         932 :   gpg_error_t err = 0;
    1002             :   ulong recno;
    1003             : #ifdef USE_TOFU
    1004         932 :   unsigned int tofu_validity = TRUST_UNKNOWN;
    1005             : #endif
    1006         932 :   unsigned int validity = TRUST_UNKNOWN;
    1007         932 :   int free_kb = 0;
    1008             : 
    1009         932 :   if (kb && pk)
    1010         630 :     log_assert (keyid_cmp (pk_main_keyid (pk),
    1011             :                            pk_main_keyid (kb->pkt->pkt.public_key)) == 0);
    1012             : 
    1013         932 :   if (! pk)
    1014             :     {
    1015           0 :       log_assert (kb);
    1016           0 :       pk = kb->pkt->pkt.public_key;
    1017             :     }
    1018             : 
    1019             : #ifndef USE_TOFU
    1020             :   (void)sig;
    1021             :   (void)may_ask;
    1022             : #endif
    1023             : 
    1024         932 :   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         932 :   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
    1031         641 :     return TRUST_UNKNOWN;
    1032             : 
    1033         291 :   check_trustdb_stale (ctrl);
    1034             : 
    1035         291 :   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           0 :       validity = tdb_get_ownertrust (main_pk);
    1040           0 :       goto leave;
    1041             :     }
    1042             : 
    1043             : #ifdef USE_TOFU
    1044         291 :   if (opt.trust_model == TM_TOFU || opt.trust_model == TM_TOFU_PGP)
    1045             :     {
    1046         181 :       kbnode_t n = NULL;
    1047         181 :       strlist_t user_id_list = NULL;
    1048         181 :       int done = 0;
    1049             : 
    1050             :       /* If the caller didn't supply a user id then use all uids.  */
    1051         181 :       if (! uid)
    1052             :         {
    1053          86 :           if (! kb)
    1054             :             {
    1055          26 :               kb = get_pubkeyblock (main_pk->keyid);
    1056          26 :               free_kb = 1;
    1057             :             }
    1058          86 :           n = kb;
    1059             :         }
    1060             : 
    1061         181 :       if (DBG_TRUST && sig && sig->signers_uid)
    1062           0 :         log_debug ("TOFU: only considering user id: '%s'\n",
    1063             :                    sig->signers_uid);
    1064             : 
    1065         555 :       while (!done && (uid || (n = find_next_kbnode (n, PKT_USER_ID))))
    1066             :         {
    1067             :           PKT_user_id *user_id;
    1068         193 :           int expired = 0;
    1069             : 
    1070         193 :           if (uid)
    1071             :             {
    1072          95 :               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          95 :               done = 1;
    1077             :             }
    1078             :           else
    1079          98 :             user_id = n->pkt->pkt.user_id;
    1080             : 
    1081         193 :           if (user_id->attrib_data)
    1082             :             /* Skip user attributes.  */
    1083           0 :             continue;
    1084             : 
    1085         193 :           if (sig && sig->signers_uid)
    1086             :             /* Make sure the UID matches.  */
    1087             :             {
    1088          16 :               char *email = mailbox_from_userid (user_id->name);
    1089          16 :               if (!email || !*email || strcmp (sig->signers_uid, email) != 0)
    1090             :                 {
    1091           4 :                   if (DBG_TRUST)
    1092           0 :                     log_debug ("TOFU: skipping user id '%s', which does"
    1093             :                                " not match the signer's email ('%s')\n",
    1094             :                                email, sig->signers_uid);
    1095           4 :                   xfree (email);
    1096           4 :                   continue;
    1097             :                 }
    1098          12 :               xfree (email);
    1099             :             }
    1100             : 
    1101             :           /* If the user id is revoked or expired, then skip it.  */
    1102         189 :           if (user_id->is_revoked || user_id->is_expired)
    1103             :             {
    1104           0 :               if (DBG_TRUST)
    1105             :                 {
    1106             :                   char *s;
    1107           0 :                   if (user_id->is_revoked && user_id->is_expired)
    1108           0 :                     s = "revoked and expired";
    1109           0 :                   else if (user_id->is_revoked)
    1110           0 :                     s = "revoked";
    1111             :                   else
    1112           0 :                     s = "expire";
    1113             : 
    1114           0 :                   log_debug ("TOFU: Ignoring %s user id (%s)\n",
    1115           0 :                              s, user_id->name);
    1116             :                 }
    1117             : 
    1118           0 :               if (user_id->is_revoked)
    1119           0 :                 continue;
    1120             : 
    1121           0 :               expired = 1;
    1122             :             }
    1123             : 
    1124         189 :           add_to_strlist (&user_id_list, user_id->name);
    1125         189 :           user_id_list->flags = expired;
    1126             :         }
    1127             : 
    1128             :       /* Process the user ids in the order they appear in the key
    1129             :          block.  */
    1130         181 :       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         181 :       if (sig)
    1137             :         {
    1138          52 :           err = tofu_register_signature (ctrl, main_pk, user_id_list,
    1139          26 :                                          sig->digest, sig->digest_len,
    1140          26 :                                          sig->timestamp, "unknown");
    1141          26 :           if (err)
    1142             :             {
    1143           0 :               log_error ("TOFU: error registering signature: %s\n",
    1144             :                          gpg_strerror (err));
    1145             : 
    1146           0 :               tofu_validity = TRUST_UNKNOWN;
    1147             :             }
    1148             :         }
    1149         181 :       if (! err)
    1150         181 :         tofu_validity = tofu_get_validity (ctrl, main_pk, user_id_list,
    1151             :                                            may_ask);
    1152             : 
    1153         181 :       free_strlist (user_id_list);
    1154         181 :       if (free_kb)
    1155          26 :         release_kbnode (kb);
    1156             :     }
    1157             : #endif /*USE_TOFU*/
    1158             : 
    1159         291 :   if (opt.trust_model == TM_TOFU_PGP
    1160         291 :       || opt.trust_model == TM_CLASSIC
    1161         291 :       || opt.trust_model == TM_PGP)
    1162             :     {
    1163          45 :       err = read_trust_record (main_pk, &trec);
    1164          45 :       if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
    1165             :         {
    1166           0 :           tdbio_invalid ();
    1167           0 :           return 0;
    1168             :         }
    1169          45 :       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
    1170             :         {
    1171             :           /* No record found.  */
    1172          38 :           validity = TRUST_UNKNOWN;
    1173          38 :           goto leave;
    1174             :         }
    1175             : 
    1176             :       /* Loop over all user IDs */
    1177           7 :       recno = trec.r.trust.validlist;
    1178           7 :       validity = 0;
    1179          21 :       while (recno)
    1180             :         {
    1181           8 :           read_record (recno, &vrec, RECTYPE_VALID);
    1182             : 
    1183           8 :           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           1 :               if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
    1190             :                 {
    1191           1 :                   validity=(vrec.r.valid.validity & TRUST_MASK);
    1192           1 :                   break;
    1193             :                 }
    1194             :             }
    1195             :           else
    1196             :             {
    1197             :               /* If no user ID is given, we take the maximum validity
    1198             :                  over all user IDs */
    1199           7 :               if (validity < (vrec.r.valid.validity & TRUST_MASK))
    1200           6 :                 validity = (vrec.r.valid.validity & TRUST_MASK);
    1201             :             }
    1202             : 
    1203           7 :           recno = vrec.r.valid.next;
    1204             :         }
    1205             : 
    1206           7 :       if ((trec.r.trust.ownertrust & TRUST_FLAG_DISABLED))
    1207             :         {
    1208           0 :           validity |= TRUST_FLAG_DISABLED;
    1209           0 :           pk->flags.disabled = 1;
    1210             :         }
    1211             :       else
    1212           7 :         pk->flags.disabled = 0;
    1213           7 :       pk->flags.disabled_valid = 1;
    1214             :     }
    1215             : 
    1216             :  leave:
    1217             : #ifdef USE_TOFU
    1218         291 :   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         291 :   if (opt.trust_model != TM_TOFU
    1231         110 :       && pending_check_trustdb)
    1232           0 :     validity |= TRUST_FLAG_PENDING_CHECK;
    1233             : 
    1234         291 :   return validity;
    1235             : }
    1236             : 
    1237             : 
    1238             : static void
    1239           0 : get_validity_counts (PKT_public_key *pk, PKT_user_id *uid)
    1240             : {
    1241             :   TRUSTREC trec, vrec;
    1242             :   ulong recno;
    1243             : 
    1244           0 :   if(pk==NULL || uid==NULL)
    1245           0 :     BUG();
    1246             : 
    1247           0 :   namehash_from_uid(uid);
    1248             : 
    1249           0 :   uid->help_marginal_count=uid->help_full_count=0;
    1250             : 
    1251           0 :   init_trustdb ();
    1252             : 
    1253           0 :   if(read_trust_record (pk, &trec))
    1254           0 :     return;
    1255             : 
    1256             :   /* loop over all user IDs */
    1257           0 :   recno = trec.r.trust.validlist;
    1258           0 :   while (recno)
    1259             :     {
    1260           0 :       read_record (recno, &vrec, RECTYPE_VALID);
    1261             : 
    1262           0 :       if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
    1263             :         {
    1264           0 :           uid->help_marginal_count=vrec.r.valid.marginal_count;
    1265           0 :           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           0 :           break;
    1268             :         }
    1269             : 
    1270           0 :       recno = vrec.r.valid.next;
    1271             :     }
    1272             : }
    1273             : 
    1274             : void
    1275           0 : list_trust_path( const char *username )
    1276             : {
    1277             :   (void)username;
    1278           0 : }
    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           0 : 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           0 :   return -1;
    1307             : }
    1308             : 
    1309             : 
    1310             : /****************
    1311             :  * Print the current path
    1312             :  */
    1313             : void
    1314           0 : 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           0 : }
    1322             : 
    1323             : 
    1324             : 
    1325             : /****************************************
    1326             :  *********** NEW NEW NEW ****************
    1327             :  ****************************************/
    1328             : 
    1329             : static int
    1330           0 : ask_ownertrust (ctrl_t ctrl, u32 *kid, int minimum)
    1331             : {
    1332             :   PKT_public_key *pk;
    1333             :   int rc;
    1334             :   int ot;
    1335             : 
    1336           0 :   pk = xmalloc_clear (sizeof *pk);
    1337           0 :   rc = get_pubkey (pk, kid);
    1338           0 :   if (rc)
    1339             :     {
    1340           0 :       log_error (_("public key %s not found: %s\n"),
    1341             :                  keystr(kid), gpg_strerror (rc) );
    1342           0 :       return TRUST_UNKNOWN;
    1343             :     }
    1344             : 
    1345           0 :   if(opt.force_ownertrust)
    1346             :     {
    1347           0 :       log_info("force trust for key %s to %s\n",
    1348           0 :                keystr(kid),trust_value_to_string(opt.force_ownertrust));
    1349           0 :       tdb_update_ownertrust (pk, opt.force_ownertrust);
    1350           0 :       ot=opt.force_ownertrust;
    1351             :     }
    1352             :   else
    1353             :     {
    1354           0 :       ot=edit_ownertrust (ctrl, pk, 0);
    1355           0 :       if(ot>0)
    1356           0 :         ot = tdb_get_ownertrust (pk);
    1357           0 :       else if(ot==0)
    1358           0 :         ot = minimum?minimum:TRUST_UNDEFINED;
    1359             :       else
    1360           0 :         ot = -1; /* quit */
    1361             :     }
    1362             : 
    1363           0 :   free_public_key( pk );
    1364             : 
    1365           0 :   return ot;
    1366             : }
    1367             : 
    1368             : 
    1369             : static void
    1370           6 : mark_keyblock_seen (KeyHashTable tbl, KBNODE node)
    1371             : {
    1372          45 :   for ( ;node; node = node->next )
    1373          39 :     if (node->pkt->pkttype == PKT_PUBLIC_KEY
    1374          33 :         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
    1375             :       {
    1376             :         u32 aki[2];
    1377             : 
    1378          12 :         keyid_from_pk (node->pkt->pkt.public_key, aki);
    1379          12 :         add_key_hash_table (tbl, aki);
    1380             :       }
    1381           6 : }
    1382             : 
    1383             : 
    1384             : static void
    1385           0 : dump_key_array (int depth, struct key_array *keys)
    1386             : {
    1387             :   struct key_array *kar;
    1388             : 
    1389           0 :   for (kar=keys; kar->keyblock; kar++)
    1390             :     {
    1391           0 :       KBNODE node = kar->keyblock;
    1392             :       u32 kid[2];
    1393             : 
    1394           0 :       keyid_from_pk(node->pkt->pkt.public_key, kid);
    1395           0 :       es_printf ("%d:%08lX%08lX:K::%c::::\n",
    1396           0 :                  depth, (ulong)kid[0], (ulong)kid[1], '?');
    1397             : 
    1398           0 :       for (; node; node = node->next)
    1399             :         {
    1400           0 :           if (node->pkt->pkttype == PKT_USER_ID)
    1401             :             {
    1402           0 :               int len = node->pkt->pkt.user_id->len;
    1403             : 
    1404           0 :               if (len > 30)
    1405           0 :                 len = 30;
    1406           0 :               es_printf ("%d:%08lX%08lX:U:::%c:::",
    1407           0 :                          depth, (ulong)kid[0], (ulong)kid[1],
    1408           0 :                          (node->flag & 4)? 'f':
    1409           0 :                          (node->flag & 2)? 'm':
    1410           0 :                          (node->flag & 1)? 'q':'-');
    1411           0 :               es_write_sanitized (es_stdout, node->pkt->pkt.user_id->name,
    1412             :                                   len, ":", NULL);
    1413           0 :               es_putc (':', es_stdout);
    1414           0 :               es_putc ('\n', es_stdout);
    1415             :             }
    1416             :         }
    1417             :     }
    1418           0 : }
    1419             : 
    1420             : 
    1421             : static void
    1422           0 : store_validation_status (int depth, KBNODE keyblock, KeyHashTable stored)
    1423             : {
    1424             :   KBNODE node;
    1425             :   int status;
    1426           0 :   int any = 0;
    1427             : 
    1428           0 :   for (node=keyblock; node; node = node->next)
    1429             :     {
    1430           0 :       if (node->pkt->pkttype == PKT_USER_ID)
    1431             :         {
    1432           0 :           PKT_user_id *uid = node->pkt->pkt.user_id;
    1433           0 :           if (node->flag & 4)
    1434           0 :             status = TRUST_FULLY;
    1435           0 :           else if (node->flag & 2)
    1436           0 :             status = TRUST_MARGINAL;
    1437           0 :           else if (node->flag & 1)
    1438           0 :             status = TRUST_UNDEFINED;
    1439             :           else
    1440           0 :             status = 0;
    1441             : 
    1442           0 :           if (status)
    1443             :             {
    1444           0 :               update_validity (keyblock->pkt->pkt.public_key,
    1445             :                                uid, depth, status);
    1446             : 
    1447           0 :               mark_keyblock_seen(stored,keyblock);
    1448             : 
    1449           0 :               any = 1;
    1450             :             }
    1451             :         }
    1452             :     }
    1453             : 
    1454           0 :   if (any)
    1455           0 :     do_sync ();
    1456           0 : }
    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           0 : sanitize_regexp(const char *old)
    1464             : {
    1465           0 :   size_t start=0,len=strlen(old),idx=0;
    1466           0 :   int escaped=0,standard_bracket=0;
    1467           0 :   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           0 :   if(len>=12 && strncmp(old,"<[^>]+[@.]",10)==0
    1486           0 :      && old[len-2]=='>' && old[len-1]=='$')
    1487             :     {
    1488           0 :       strcpy(new,"<[^>]+[@.]");
    1489           0 :       idx=strlen(new);
    1490           0 :       standard_bracket=1;
    1491           0 :       start+=10;
    1492           0 :       len-=2;
    1493             :     }
    1494             : 
    1495             :   /* Walk the remaining characters and ensure that everything that is
    1496             :      left is not an operational regex character. */
    1497           0 :   for(;start<len;start++)
    1498             :     {
    1499           0 :       if(!escaped && old[start]=='\\')
    1500           0 :         escaped=1;
    1501           0 :       else if(!escaped && old[start]!='.')
    1502           0 :         new[idx++]='\\';
    1503             :       else
    1504           0 :         escaped=0;
    1505             : 
    1506           0 :       new[idx++]=old[start];
    1507             :     }
    1508             : 
    1509           0 :   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           0 :   if(standard_bracket)
    1518           0 :     strcat(new,">$");
    1519             : 
    1520           0 :   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           0 : 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           0 :   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           0 :     ret=regcomp(&pat,regexp,REG_ICASE|REG_NOSUB|REG_EXTENDED);
    1549           0 :     if(ret==0)
    1550             :       {
    1551           0 :         ret=regexec(&pat,string,0,NULL,0);
    1552           0 :         regfree(&pat);
    1553           0 :         ret=(ret==0);
    1554             :       }
    1555             :   }
    1556             : #endif
    1557             : 
    1558           0 :   if(DBG_TRUST)
    1559           0 :     log_debug("regexp '%s' ('%s') on '%s': %s\n",
    1560             :               regexp,expr,string,ret==0?"YES":"NO");
    1561             : 
    1562           0 :   xfree(regexp);
    1563             : 
    1564           0 :   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           0 : validate_one_keyblock (KBNODE kb, struct key_item *klist,
    1582             :                        u32 curtime, u32 *next_expire)
    1583             : {
    1584             :   struct key_item *kr;
    1585           0 :   KBNODE node, uidnode=NULL;
    1586           0 :   PKT_user_id *uid=NULL;
    1587           0 :   PKT_public_key *pk = kb->pkt->pkt.public_key;
    1588             :   u32 main_kid[2];
    1589           0 :   int issigned=0, any_signed = 0;
    1590             : 
    1591           0 :   keyid_from_pk(pk, main_kid);
    1592           0 :   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           0 :       if (node->pkt->pkttype == PKT_USER_ID
    1607           0 :           && !node->pkt->pkt.user_id->is_revoked
    1608           0 :           && !node->pkt->pkt.user_id->is_expired)
    1609             :         {
    1610           0 :           if (uidnode && issigned)
    1611             :             {
    1612           0 :               if (uid->help_full_count >= opt.completes_needed
    1613           0 :                   || uid->help_marginal_count >= opt.marginals_needed )
    1614           0 :                 uidnode->flag |= 4;
    1615           0 :               else if (uid->help_full_count || uid->help_marginal_count)
    1616           0 :                 uidnode->flag |= 2;
    1617           0 :               uidnode->flag |= 1;
    1618           0 :               any_signed = 1;
    1619             :             }
    1620           0 :           uidnode = node;
    1621           0 :           uid=uidnode->pkt->pkt.user_id;
    1622             : 
    1623             :           /* If the selfsig is going to expire... */
    1624           0 :           if(uid->expiredate && uid->expiredate<*next_expire)
    1625           0 :             *next_expire = uid->expiredate;
    1626             : 
    1627           0 :           issigned = 0;
    1628           0 :           get_validity_counts(pk,uid);
    1629           0 :           mark_usable_uid_certs (kb, uidnode, main_kid, klist,
    1630             :                                  curtime, next_expire);
    1631             :         }
    1632           0 :       else if (node->pkt->pkttype == PKT_SIGNATURE
    1633           0 :                && (node->flag & (1<<8)) && uid)
    1634             :         {
    1635             :           /* Note that we are only seeing unrevoked sigs here */
    1636           0 :           PKT_signature *sig = node->pkt->pkt.signature;
    1637             : 
    1638           0 :           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           0 :           if (kr && (!kr->trust_regexp
    1644           0 :                      || !(opt.trust_model == TM_PGP
    1645           0 :                           || opt.trust_model == TM_TOFU_PGP)
    1646           0 :                      || (uidnode
    1647           0 :                          && check_regexp(kr->trust_regexp,
    1648           0 :                                          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           0 :               if ((opt.trust_model == TM_PGP
    1656           0 :                    || opt.trust_model == TM_TOFU_PGP)
    1657           0 :                   && sig->trust_depth
    1658           0 :                   && 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           0 :                   if (sig->trust_depth < kr->trust_depth
    1673           0 :                       || kr->ownertrust == TRUST_ULTIMATE)
    1674           0 :                     depth = sig->trust_depth;
    1675             :                   else
    1676           0 :                     depth = kr->trust_depth;
    1677             : 
    1678           0 :                   if (depth)
    1679             :                     {
    1680           0 :                       if(DBG_TRUST)
    1681           0 :                         log_debug ("trust sig on %s, sig depth is %d,"
    1682             :                                    " kr depth is %d\n",
    1683           0 :                                    uidnode->pkt->pkt.user_id->name,
    1684           0 :                                    sig->trust_depth,
    1685           0 :                                    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           0 :                       if (DBG_TRUST)
    1704           0 :                         log_debug ("replacing trust value %d with %d and "
    1705             :                                    "depth %d with %d\n",
    1706           0 :                                    pk->trust_value,sig->trust_value,
    1707           0 :                                    pk->trust_depth,depth);
    1708             : 
    1709           0 :                       pk->trust_value = sig->trust_value;
    1710           0 :                       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           0 :                       if (sig->trust_regexp)
    1715           0 :                         pk->trust_regexp = sig->trust_regexp;
    1716             :                     }
    1717             :                 }
    1718             : 
    1719           0 :               if (kr->ownertrust == TRUST_ULTIMATE)
    1720           0 :                 uid->help_full_count = opt.completes_needed;
    1721           0 :               else if (kr->ownertrust == TRUST_FULLY)
    1722           0 :                 uid->help_full_count++;
    1723           0 :               else if (kr->ownertrust == TRUST_MARGINAL)
    1724           0 :                 uid->help_marginal_count++;
    1725           0 :               issigned = 1;
    1726             :             }
    1727             :         }
    1728             :     }
    1729             : 
    1730           0 :   if (uidnode && issigned)
    1731             :     {
    1732           0 :       if (uid->help_full_count >= opt.completes_needed
    1733           0 :           || uid->help_marginal_count >= opt.marginals_needed )
    1734           0 :         uidnode->flag |= 4;
    1735           0 :       else if (uid->help_full_count || uid->help_marginal_count)
    1736           0 :         uidnode->flag |= 2;
    1737           0 :       uidnode->flag |= 1;
    1738           0 :       any_signed = 1;
    1739             :     }
    1740             : 
    1741           0 :   return any_signed;
    1742             : }
    1743             : 
    1744             : 
    1745             : static int
    1746           2 : search_skipfnc (void *opaque, u32 *kid, int dummy_uid_no)
    1747             : {
    1748             :   (void)dummy_uid_no;
    1749           2 :   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           2 : validate_key_list (KEYDB_HANDLE hd, KeyHashTable full_trust,
    1762             :                    struct key_item *klist, u32 curtime, u32 *next_expire)
    1763             : {
    1764           2 :   KBNODE keyblock = NULL;
    1765           2 :   struct key_array *keys = NULL;
    1766             :   size_t nkeys, maxkeys;
    1767             :   int rc;
    1768             :   KEYDB_SEARCH_DESC desc;
    1769             : 
    1770           2 :   maxkeys = 1000;
    1771           2 :   keys = xmalloc ((maxkeys+1) * sizeof *keys);
    1772           2 :   nkeys = 0;
    1773             : 
    1774           2 :   rc = keydb_search_reset (hd);
    1775           2 :   if (rc)
    1776             :     {
    1777           0 :       log_error ("keydb_search_reset failed: %s\n", gpg_strerror (rc));
    1778           0 :       xfree (keys);
    1779           0 :       return NULL;
    1780             :     }
    1781             : 
    1782           2 :   memset (&desc, 0, sizeof desc);
    1783           2 :   desc.mode = KEYDB_SEARCH_MODE_FIRST;
    1784           2 :   desc.skipfnc = search_skipfnc;
    1785           2 :   desc.skipfncvalue = full_trust;
    1786           2 :   rc = keydb_search (hd, &desc, 1, NULL);
    1787           2 :   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
    1788             :     {
    1789           2 :       keys[nkeys].keyblock = NULL;
    1790           2 :       return keys;
    1791             :     }
    1792           0 :   if (rc)
    1793             :     {
    1794           0 :       log_error ("keydb_search(first) failed: %s\n", gpg_strerror (rc));
    1795           0 :       goto die;
    1796             :     }
    1797             : 
    1798           0 :   desc.mode = KEYDB_SEARCH_MODE_NEXT; /* change mode */
    1799             :   do
    1800             :     {
    1801             :       PKT_public_key *pk;
    1802             : 
    1803           0 :       rc = keydb_get_keyblock (hd, &keyblock);
    1804           0 :       if (rc)
    1805             :         {
    1806           0 :           log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
    1807           0 :           goto die;
    1808             :         }
    1809             : 
    1810           0 :       if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
    1811             :         {
    1812           0 :           log_debug ("ooops: invalid pkttype %d encountered\n",
    1813           0 :                      keyblock->pkt->pkttype);
    1814           0 :           dump_kbnode (keyblock);
    1815           0 :           release_kbnode(keyblock);
    1816           0 :           continue;
    1817             :         }
    1818             : 
    1819             :       /* prepare the keyblock for further processing */
    1820           0 :       merge_keys_and_selfsig (keyblock);
    1821           0 :       clear_kbnode_flags (keyblock);
    1822           0 :       pk = keyblock->pkt->pkt.public_key;
    1823           0 :       if (pk->has_expired || pk->flags.revoked)
    1824             :         {
    1825             :           /* it does not make sense to look further at those keys */
    1826           0 :           mark_keyblock_seen (full_trust, keyblock);
    1827             :         }
    1828           0 :       else if (validate_one_keyblock (keyblock, klist, curtime, next_expire))
    1829             :         {
    1830             :           KBNODE node;
    1831             : 
    1832           0 :           if (pk->expiredate && pk->expiredate >= curtime
    1833           0 :               && pk->expiredate < *next_expire)
    1834           0 :             *next_expire = pk->expiredate;
    1835             : 
    1836           0 :           if (nkeys == maxkeys) {
    1837           0 :             maxkeys += 1000;
    1838           0 :             keys = xrealloc (keys, (maxkeys+1) * sizeof *keys);
    1839             :           }
    1840           0 :           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           0 :           for (node=keyblock; node; node = node->next)
    1846           0 :             if (node->pkt->pkttype == PKT_USER_ID && !(node->flag & 4))
    1847           0 :               break;
    1848             : 
    1849           0 :           if(node==NULL)
    1850           0 :             mark_keyblock_seen (full_trust, keyblock);
    1851             : 
    1852           0 :           keyblock = NULL;
    1853             :         }
    1854             : 
    1855           0 :       release_kbnode (keyblock);
    1856           0 :       keyblock = NULL;
    1857             :     }
    1858           0 :   while (!(rc = keydb_search (hd, &desc, 1, NULL)));
    1859             : 
    1860           0 :   if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
    1861             :     {
    1862           0 :       log_error ("keydb_search_next failed: %s\n", gpg_strerror (rc));
    1863           0 :       goto die;
    1864             :     }
    1865             : 
    1866           0 :   keys[nkeys].keyblock = NULL;
    1867           0 :   return keys;
    1868             : 
    1869             :  die:
    1870           0 :   keys[nkeys].keyblock = NULL;
    1871           0 :   release_key_array (keys);
    1872           0 :   return NULL;
    1873             : }
    1874             : 
    1875             : /* Caller must sync */
    1876             : static void
    1877           3 : reset_trust_records(void)
    1878             : {
    1879             :   TRUSTREC rec;
    1880             :   ulong recnum;
    1881           3 :   int count = 0, nreset = 0;
    1882             : 
    1883          93 :   for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
    1884             :     {
    1885          90 :       if(rec.rectype==RECTYPE_TRUST)
    1886             :         {
    1887           2 :           count++;
    1888           2 :           if(rec.r.trust.min_ownertrust)
    1889             :             {
    1890           0 :               rec.r.trust.min_ownertrust=0;
    1891           0 :               write_record(&rec);
    1892             :             }
    1893             : 
    1894             :         }
    1895          88 :       else if(rec.rectype==RECTYPE_VALID
    1896           1 :               && ((rec.r.valid.validity&TRUST_MASK)
    1897           0 :                   || rec.r.valid.marginal_count
    1898           0 :                   || rec.r.valid.full_count))
    1899             :         {
    1900           1 :           rec.r.valid.validity &= ~TRUST_MASK;
    1901           1 :           rec.r.valid.marginal_count=rec.r.valid.full_count=0;
    1902           1 :           nreset++;
    1903           1 :           write_record(&rec);
    1904             :         }
    1905             : 
    1906             :     }
    1907             : 
    1908           3 :   if (opt.verbose)
    1909             :     {
    1910           0 :       log_info (ngettext("%d key processed",
    1911             :                          "%d keys processed",
    1912             :                          count), count);
    1913           0 :       log_printf (ngettext(" (%d validity count cleared)\n",
    1914             :                            " (%d validity counts cleared)\n",
    1915             :                            nreset), nreset);
    1916             :     }
    1917           3 : }
    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           3 : validate_keys (ctrl_t ctrl, int interactive)
    1945             : {
    1946           3 :   int rc = 0;
    1947           3 :   int quit=0;
    1948           3 :   struct key_item *klist = NULL;
    1949             :   struct key_item *k;
    1950           3 :   struct key_array *keys = NULL;
    1951             :   struct key_array *kar;
    1952           3 :   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           3 :   keydb_rebuild_caches(0);
    1965             : 
    1966           3 :   kdb = keydb_new ();
    1967           3 :   if (!kdb)
    1968           0 :     return gpg_error_from_syserror ();
    1969             : 
    1970           3 :   start_time = make_timestamp ();
    1971           3 :   next_expire = 0xffffffff; /* set next expire to the year 2106 */
    1972           3 :   stored = new_key_hash_table ();
    1973           3 :   used = new_key_hash_table ();
    1974           3 :   full_trust = new_key_hash_table ();
    1975             : 
    1976           3 :   reset_trust_records();
    1977             : 
    1978             :   /* Fixme: Instead of always building a UTK list, we could just build it
    1979             :    * here when needed */
    1980           3 :   if (!utk_list)
    1981             :     {
    1982           1 :       if (!opt.quiet)
    1983           1 :         log_info (_("no ultimately trusted keys found\n"));
    1984           1 :       goto leave;
    1985             :     }
    1986             : 
    1987             :   /* mark all UTKs as used and fully_trusted and set validity to
    1988             :      ultimate */
    1989           4 :   for (k=utk_list; k; k = k->next)
    1990             :     {
    1991             :       KBNODE keyblock;
    1992             :       PKT_public_key *pk;
    1993             : 
    1994           2 :       keyblock = get_pubkeyblock (k->kid);
    1995           2 :       if (!keyblock)
    1996             :         {
    1997           0 :           log_error (_("public key of ultimately"
    1998           0 :                        " trusted key %s not found\n"), keystr(k->kid));
    1999           0 :           continue;
    2000             :         }
    2001           2 :       mark_keyblock_seen (used, keyblock);
    2002           2 :       mark_keyblock_seen (stored, keyblock);
    2003           2 :       mark_keyblock_seen (full_trust, keyblock);
    2004           2 :       pk = keyblock->pkt->pkt.public_key;
    2005          15 :       for (node=keyblock; node; node = node->next)
    2006             :         {
    2007          13 :           if (node->pkt->pkttype == PKT_USER_ID)
    2008           3 :             update_validity (pk, node->pkt->pkt.user_id, 0, TRUST_ULTIMATE);
    2009             :         }
    2010           2 :       if ( pk->expiredate && pk->expiredate >= start_time
    2011           0 :            && pk->expiredate < next_expire)
    2012           0 :         next_expire = pk->expiredate;
    2013             : 
    2014           2 :       release_kbnode (keyblock);
    2015           2 :       do_sync ();
    2016             :     }
    2017             : 
    2018           2 :   if (opt.trust_model == TM_TOFU)
    2019             :     /* In the TOFU trust model, we only need to save the ultimately
    2020             :        trusted keys.  */
    2021           0 :     goto leave;
    2022             : 
    2023           2 :   klist = utk_list;
    2024             : 
    2025           2 :   if (!opt.quiet)
    2026           2 :     log_info ("marginals needed: %d  completes needed: %d  trust model: %s\n",
    2027             :               opt.marginals_needed, opt.completes_needed,
    2028           2 :               trust_model_string (opt.trust_model));
    2029             : 
    2030           2 :   for (depth=0; depth < opt.max_cert_depth; depth++)
    2031             :     {
    2032           2 :       int valids=0,key_count;
    2033             :       /* See whether we should assign ownertrust values to the keys in
    2034             :          klist.  */
    2035           2 :       ot_unknown = ot_undefined = ot_never = 0;
    2036           2 :       ot_marginal = ot_full = ot_ultimate = 0;
    2037           4 :       for (k=klist; k; k = k->next)
    2038             :         {
    2039           2 :           int min=0;
    2040             : 
    2041             :           /* 120 and 60 are as per RFC2440 */
    2042           2 :           if(k->trust_value>=120)
    2043           0 :             min=TRUST_FULLY;
    2044           2 :           else if(k->trust_value>=60)
    2045           0 :             min=TRUST_MARGINAL;
    2046             : 
    2047           2 :           if(min!=k->min_ownertrust)
    2048           0 :             update_min_ownertrust(k->kid,min);
    2049             : 
    2050           2 :           if (interactive && k->ownertrust == TRUST_UNKNOWN)
    2051             :             {
    2052           0 :               k->ownertrust = ask_ownertrust (ctrl, k->kid,min);
    2053             : 
    2054           0 :               if (k->ownertrust == (unsigned int)(-1))
    2055             :                 {
    2056           0 :                   quit=1;
    2057           0 :                   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           2 :           if(k->ownertrust<min)
    2066             :             {
    2067           0 :               if(DBG_TRUST)
    2068           0 :                 log_debug("key %08lX%08lX:"
    2069             :                           " overriding ownertrust '%s' with '%s'\n",
    2070           0 :                           (ulong)k->kid[0],(ulong)k->kid[1],
    2071             :                           trust_value_to_string(k->ownertrust),
    2072             :                           trust_value_to_string(min));
    2073             : 
    2074           0 :               k->ownertrust=min;
    2075             :             }
    2076             : 
    2077           2 :           if (k->ownertrust == TRUST_UNKNOWN)
    2078           0 :             ot_unknown++;
    2079           2 :           else if (k->ownertrust == TRUST_UNDEFINED)
    2080           0 :             ot_undefined++;
    2081           2 :           else if (k->ownertrust == TRUST_NEVER)
    2082           0 :             ot_never++;
    2083           2 :           else if (k->ownertrust == TRUST_MARGINAL)
    2084           0 :             ot_marginal++;
    2085           2 :           else if (k->ownertrust == TRUST_FULLY)
    2086           0 :             ot_full++;
    2087           2 :           else if (k->ownertrust == TRUST_ULTIMATE)
    2088           2 :             ot_ultimate++;
    2089             : 
    2090           2 :           valids++;
    2091             :         }
    2092             : 
    2093             :       /* Find all keys which are signed by a key in kdlist */
    2094           2 :       keys = validate_key_list (kdb, full_trust, klist,
    2095             :                                 start_time, &next_expire);
    2096           2 :       if (!keys)
    2097             :         {
    2098           0 :           log_error ("validate_key_list failed\n");
    2099           0 :           rc = GPG_ERR_GENERAL;
    2100           0 :           goto leave;
    2101             :         }
    2102             : 
    2103           2 :       for (key_count=0, kar=keys; kar->keyblock; kar++, key_count++)
    2104             :         ;
    2105             : 
    2106             :       /* Store the calculated valididation status somewhere */
    2107           2 :       if (opt.verbose > 1 && DBG_TRUST)
    2108           0 :         dump_key_array (depth, keys);
    2109             : 
    2110           2 :       for (kar=keys; kar->keyblock; kar++)
    2111           0 :           store_validation_status (depth, kar->keyblock, stored);
    2112             : 
    2113           2 :       if (!opt.quiet)
    2114           2 :         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           2 :       if (klist != utk_list)
    2121           0 :         release_key_items (klist);
    2122           2 :       klist = NULL;
    2123           2 :       for (kar=keys; kar->keyblock; kar++)
    2124             :         {
    2125           0 :           for (node=kar->keyblock; node; node = node->next)
    2126             :             {
    2127           0 :               if (node->pkt->pkttype == PKT_USER_ID && (node->flag & 4))
    2128             :                 {
    2129             :                   u32 kid[2];
    2130             : 
    2131             :                   /* have we used this key already? */
    2132           0 :                   keyid_from_pk (kar->keyblock->pkt->pkt.public_key, kid);
    2133           0 :                   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           0 :                       add_key_hash_table (used,kid);
    2140           0 :                       k = new_key_item ();
    2141           0 :                       k->kid[0]=kid[0];
    2142           0 :                       k->kid[1]=kid[1];
    2143           0 :                       k->ownertrust =
    2144           0 :                         (tdb_get_ownertrust
    2145           0 :                          (kar->keyblock->pkt->pkt.public_key) & TRUST_MASK);
    2146           0 :                       k->min_ownertrust = tdb_get_min_ownertrust
    2147           0 :                         (kar->keyblock->pkt->pkt.public_key);
    2148           0 :                       k->trust_depth=
    2149           0 :                         kar->keyblock->pkt->pkt.public_key->trust_depth;
    2150           0 :                       k->trust_value=
    2151           0 :                         kar->keyblock->pkt->pkt.public_key->trust_value;
    2152           0 :                       if(kar->keyblock->pkt->pkt.public_key->trust_regexp)
    2153           0 :                         k->trust_regexp=
    2154           0 :                           xstrdup(kar->keyblock->pkt->
    2155             :                                    pkt.public_key->trust_regexp);
    2156           0 :                       k->next = klist;
    2157           0 :                       klist = k;
    2158           0 :                       break;
    2159             :                     }
    2160             :                 }
    2161             :             }
    2162             :         }
    2163           2 :       release_key_array (keys);
    2164           2 :       keys = NULL;
    2165           2 :       if (!klist)
    2166           2 :         break; /* no need to dive in deeper */
    2167             :     }
    2168             : 
    2169             :  leave:
    2170           3 :   keydb_release (kdb);
    2171           3 :   release_key_array (keys);
    2172           3 :   if (klist != utk_list)
    2173           2 :     release_key_items (klist);
    2174           3 :   release_key_hash_table (full_trust);
    2175           3 :   release_key_hash_table (used);
    2176           3 :   release_key_hash_table (stored);
    2177           3 :   if (!rc && !quit) /* mark trustDB as checked */
    2178             :     {
    2179             :       int rc2;
    2180             : 
    2181           3 :       if (next_expire == 0xffffffff || next_expire < start_time )
    2182           3 :         tdbio_write_nextcheck (0);
    2183             :       else
    2184             :         {
    2185           0 :           tdbio_write_nextcheck (next_expire);
    2186           0 :           if (!opt.quiet)
    2187           0 :             log_info (_("next trustdb check due at %s\n"),
    2188             :                       strtimestamp (next_expire));
    2189             :         }
    2190             : 
    2191           3 :       rc2 = tdbio_update_version_record ();
    2192           3 :       if (rc2)
    2193             :         {
    2194           0 :           log_error (_("unable to update trustdb version record: "
    2195             :                        "write failed: %s\n"), gpg_strerror (rc2));
    2196           0 :           tdbio_invalid ();
    2197             :         }
    2198             : 
    2199           3 :       do_sync ();
    2200           3 :       pending_check_trustdb = 0;
    2201             :     }
    2202             : 
    2203           3 :   return rc;
    2204             : }

Generated by: LCOV version 1.11