Coverage Report

Created: 2026-01-09 06:46

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