LCOV - code coverage report
Current view: top level - g10 - trustdb.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 303 912 33.2 %
Date: 2016-09-12 12:29:17 Functions: 30 50 60.0 %

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

Generated by: LCOV version 1.11