2006-09-24 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / trustdb.c
blob573c12903de575f71d5cbeff87e7c36aa6b87d76
1 /* trustdb.c
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3 * 2005 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 * USA.
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
29 #ifndef DISABLE_REGEX
30 #include <sys/types.h>
31 #ifdef USE_INTERNAL_REGEX
32 #include "_regex.h"
33 #else
34 #include <regex.h>
35 #endif
36 #endif /* !DISABLE_REGEX */
38 #include "gpg.h"
39 #include "errors.h"
40 #include "iobuf.h"
41 #include "keydb.h"
42 #include "util.h"
43 #include "options.h"
44 #include "packet.h"
45 #include "main.h"
46 #include "i18n.h"
47 #include "tdbio.h"
48 #include "trustdb.h"
52 * A structure to store key identification as well as some stuff needed
53 * for validation
55 struct key_item {
56 struct key_item *next;
57 unsigned int ownertrust,min_ownertrust;
58 byte trust_depth;
59 byte trust_value;
60 char *trust_regexp;
61 u32 kid[2];
65 typedef struct key_item **KeyHashTable; /* see new_key_hash_table() */
68 * Structure to keep track of keys, this is used as an array wherre
69 * the item right after the last one has a keyblock set to NULL.
70 * Maybe we can drop this thing and replace it by key_item
72 struct key_array {
73 KBNODE keyblock;
77 /* control information for the trust DB */
78 static struct {
79 int init;
80 int level;
81 char *dbname;
82 } trustdb_args;
84 /* some globals */
85 static struct key_item *user_utk_list; /* temp. used to store --trusted-keys */
86 static struct key_item *utk_list; /* all ultimately trusted keys */
88 static int pending_check_trustdb;
90 static int validate_keys (int interactive);
93 /**********************************************
94 ************* some helpers *******************
95 **********************************************/
97 static struct key_item *
98 new_key_item (void)
100 struct key_item *k;
102 k = xmalloc_clear (sizeof *k);
103 return k;
106 static void
107 release_key_items (struct key_item *k)
109 struct key_item *k2;
111 for (; k; k = k2)
113 k2 = k->next;
114 xfree (k->trust_regexp);
115 xfree (k);
120 * For fast keylook up we need a hash table. Each byte of a KeyIDs
121 * should be distributed equally over the 256 possible values (except
122 * for v3 keyIDs but we consider them as not important here). So we
123 * can just use 10 bits to index a table of 1024 key items.
124 * Possible optimization: Don not use key_items but other hash_table when the
125 * duplicates lists gets too large.
127 static KeyHashTable
128 new_key_hash_table (void)
130 struct key_item **tbl;
132 tbl = xmalloc_clear (1024 * sizeof *tbl);
133 return tbl;
136 static void
137 release_key_hash_table (KeyHashTable tbl)
139 int i;
141 if (!tbl)
142 return;
143 for (i=0; i < 1024; i++)
144 release_key_items (tbl[i]);
145 xfree (tbl);
149 * Returns: True if the keyID is in the given hash table
151 static int
152 test_key_hash_table (KeyHashTable tbl, u32 *kid)
154 struct key_item *k;
156 for (k = tbl[(kid[1] & 0x03ff)]; k; k = k->next)
157 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
158 return 1;
159 return 0;
163 * Add a new key to the hash table. The key is identified by its key ID.
165 static void
166 add_key_hash_table (KeyHashTable tbl, u32 *kid)
168 struct key_item *k, *kk;
170 for (k = tbl[(kid[1] & 0x03ff)]; k; k = k->next)
171 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
172 return; /* already in table */
174 kk = new_key_item ();
175 kk->kid[0] = kid[0];
176 kk->kid[1] = kid[1];
177 kk->next = tbl[(kid[1] & 0x03ff)];
178 tbl[(kid[1] & 0x03ff)] = kk;
182 * Release a key_array
184 static void
185 release_key_array ( struct key_array *keys )
187 struct key_array *k;
189 if (keys) {
190 for (k=keys; k->keyblock; k++)
191 release_kbnode (k->keyblock);
192 xfree (keys);
197 /*********************************************
198 ********** Initialization *****************
199 *********************************************/
204 * Used to register extra ultimately trusted keys - this has to be done
205 * before initializing the validation module.
206 * FIXME: Should be replaced by a function to add those keys to the trustdb.
208 void
209 register_trusted_keyid(u32 *keyid)
211 struct key_item *k;
213 k = new_key_item ();
214 k->kid[0] = keyid[0];
215 k->kid[1] = keyid[1];
216 k->next = user_utk_list;
217 user_utk_list = k;
220 void
221 register_trusted_key( const char *string )
223 KEYDB_SEARCH_DESC desc;
225 if (classify_user_id (string, &desc) != KEYDB_SEARCH_MODE_LONG_KID )
227 log_error(_("`%s' is not a valid long keyID\n"), string );
228 return;
231 register_trusted_keyid(desc.u.kid);
235 * Helper to add a key to the global list of ultimately trusted keys.
236 * Retruns: true = inserted, false = already in in list.
238 static int
239 add_utk (u32 *kid)
241 struct key_item *k;
243 for (k = utk_list; k; k = k->next)
245 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
247 return 0;
251 k = new_key_item ();
252 k->kid[0] = kid[0];
253 k->kid[1] = kid[1];
254 k->ownertrust = TRUST_ULTIMATE;
255 k->next = utk_list;
256 utk_list = k;
257 if( opt.verbose > 1 )
258 log_info(_("key %s: accepted as trusted key\n"), keystr(kid));
259 return 1;
263 /****************
264 * Verify that all our secret keys are usable and put them into the utk_list.
266 static void
267 verify_own_keys(void)
269 TRUSTREC rec;
270 ulong recnum;
271 int rc;
272 struct key_item *k;
274 if (utk_list)
275 return;
277 /* scan the trustdb to find all ultimately trusted keys */
278 for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
280 if ( rec.rectype == RECTYPE_TRUST
281 && (rec.r.trust.ownertrust & TRUST_MASK) == TRUST_ULTIMATE)
283 byte *fpr = rec.r.trust.fingerprint;
284 int fprlen;
285 u32 kid[2];
287 /* Problem: We do only use fingerprints in the trustdb but
288 * we need the keyID here to indetify the key; we can only
289 * use that ugly hack to distinguish between 16 and 20
290 * butes fpr - it does not work always so we better change
291 * the whole validation code to only work with
292 * fingerprints */
293 fprlen = (!fpr[16] && !fpr[17] && !fpr[18] && !fpr[19])? 16:20;
294 keyid_from_fingerprint (fpr, fprlen, kid);
295 if (!add_utk (kid))
296 log_info(_("key %s occurs more than once in the trustdb\n"),
297 keystr(kid));
301 /* Put any --trusted-key keys into the trustdb */
302 for (k = user_utk_list; k; k = k->next)
304 if ( add_utk (k->kid) )
305 { /* not yet in trustDB as ultimately trusted */
306 PKT_public_key pk;
308 memset (&pk, 0, sizeof pk);
309 rc = get_pubkey (&pk, k->kid);
310 if (rc)
311 log_info(_("key %s: no public key for trusted key - skipped\n"),
312 keystr(k->kid));
313 else
315 update_ownertrust (&pk,
316 ((get_ownertrust (&pk) & ~TRUST_MASK)
317 | TRUST_ULTIMATE ));
318 release_public_key_parts (&pk);
321 log_info (_("key %s marked as ultimately trusted\n"),keystr(k->kid));
325 /* release the helper table table */
326 release_key_items (user_utk_list);
327 user_utk_list = NULL;
328 return;
332 /*********************************************
333 *********** TrustDB stuff *******************
334 *********************************************/
337 * Read a record but die if it does not exist
339 static void
340 read_record (ulong recno, TRUSTREC *rec, int rectype )
342 int rc = tdbio_read_record (recno, rec, rectype);
343 if (rc)
345 log_error(_("trust record %lu, req type %d: read failed: %s\n"),
346 recno, rec->rectype, g10_errstr(rc) );
347 tdbio_invalid();
349 if (rectype != rec->rectype)
351 log_error(_("trust record %lu is not of requested type %d\n"),
352 rec->recnum, rectype);
353 tdbio_invalid();
358 * Write a record and die on error
360 static void
361 write_record (TRUSTREC *rec)
363 int rc = tdbio_write_record (rec);
364 if (rc)
366 log_error(_("trust record %lu, type %d: write failed: %s\n"),
367 rec->recnum, rec->rectype, g10_errstr(rc) );
368 tdbio_invalid();
373 * sync the TrustDb and die on error
375 static void
376 do_sync(void)
378 int rc = tdbio_sync ();
379 if(rc)
381 log_error (_("trustdb: sync failed: %s\n"), g10_errstr(rc) );
382 g10_exit(2);
386 static const char *
387 trust_model_string(void)
389 switch(opt.trust_model)
391 case TM_CLASSIC: return "classic";
392 case TM_PGP: return "PGP";
393 case TM_EXTERNAL: return "external";
394 case TM_ALWAYS: return "always";
395 case TM_DIRECT: return "direct";
396 default: return "unknown";
400 /****************
401 * Perform some checks over the trustdb
402 * level 0: only open the db
403 * 1: used for initial program startup
406 setup_trustdb( int level, const char *dbname )
408 /* just store the args */
409 if( trustdb_args.init )
410 return 0;
411 trustdb_args.level = level;
412 trustdb_args.dbname = dbname? xstrdup(dbname): NULL;
413 return 0;
416 void
417 init_trustdb()
419 int level = trustdb_args.level;
420 const char* dbname = trustdb_args.dbname;
422 if( trustdb_args.init )
423 return;
425 trustdb_args.init = 1;
427 if(level==0 || level==1)
429 int rc = tdbio_set_dbname( dbname, !!level );
430 if( rc )
431 log_fatal("can't init trustdb: %s\n", g10_errstr(rc) );
433 else
434 BUG();
436 if(opt.trust_model==TM_AUTO)
438 /* Try and set the trust model off of whatever the trustdb says
439 it is. */
440 opt.trust_model=tdbio_read_model();
442 /* Sanity check this ;) */
443 if(opt.trust_model!=TM_CLASSIC
444 && opt.trust_model!=TM_PGP
445 && opt.trust_model!=TM_EXTERNAL)
447 log_info(_("unable to use unknown trust model (%d) - "
448 "assuming %s trust model\n"),opt.trust_model,"PGP");
449 opt.trust_model=TM_PGP;
452 if(opt.verbose)
453 log_info(_("using %s trust model\n"),trust_model_string());
456 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
458 /* Verify the list of ultimately trusted keys and move the
459 --trusted-keys list there as well. */
460 if(level==1)
461 verify_own_keys();
463 if(!tdbio_db_matches_options())
464 pending_check_trustdb=1;
469 /***********************************************
470 ************* Print helpers ****************
471 ***********************************************/
473 /****************
474 * This function returns a letter for a trustvalue Trust flags
475 * are ignore.
477 static int
478 trust_letter (unsigned int value)
480 switch( (value & TRUST_MASK) )
482 case TRUST_UNKNOWN: return '-';
483 case TRUST_EXPIRED: return 'e';
484 case TRUST_UNDEFINED: return 'q';
485 case TRUST_NEVER: return 'n';
486 case TRUST_MARGINAL: return 'm';
487 case TRUST_FULLY: return 'f';
488 case TRUST_ULTIMATE: return 'u';
489 default: return '?';
493 /* NOTE TO TRANSLATOR: these strings are similar to those in
494 trust_value_to_string(), but are a fixed length. This is needed to
495 make attractive information listings where columns line up
496 properly. The value "10" should be the length of the strings you
497 choose to translate to. This is the length in printable columns.
498 It gets passed to atoi() so everything after the number is
499 essentially a comment and need not be translated. Either key and
500 uid are both NULL, or neither are NULL. */
501 const char *
502 uid_trust_string_fixed(PKT_public_key *key,PKT_user_id *uid)
504 if(!key && !uid)
505 return _("10 translator see trustdb.c:uid_trust_string_fixed");
506 else if(uid->is_revoked || (key && key->is_revoked))
507 return _("[ revoked]");
508 else if(uid->is_expired)
509 return _("[ expired]");
510 else if(key)
511 switch(get_validity(key,uid)&TRUST_MASK)
513 case TRUST_UNKNOWN: return _("[ unknown]");
514 case TRUST_EXPIRED: return _("[ expired]");
515 case TRUST_UNDEFINED: return _("[ undef ]");
516 case TRUST_MARGINAL: return _("[marginal]");
517 case TRUST_FULLY: return _("[ full ]");
518 case TRUST_ULTIMATE: return _("[ultimate]");
521 return "err";
524 /* The strings here are similar to those in
525 pkclist.c:do_edit_ownertrust() */
526 const char *
527 trust_value_to_string (unsigned int value)
529 switch( (value & TRUST_MASK) )
531 case TRUST_UNKNOWN: return _("unknown");
532 case TRUST_EXPIRED: return _("expired");
533 case TRUST_UNDEFINED: return _("undefined");
534 case TRUST_NEVER: return _("never");
535 case TRUST_MARGINAL: return _("marginal");
536 case TRUST_FULLY: return _("full");
537 case TRUST_ULTIMATE: return _("ultimate");
538 default: return "err";
543 string_to_trust_value (const char *str)
545 if(ascii_strcasecmp(str,"undefined")==0)
546 return TRUST_UNDEFINED;
547 else if(ascii_strcasecmp(str,"never")==0)
548 return TRUST_NEVER;
549 else if(ascii_strcasecmp(str,"marginal")==0)
550 return TRUST_MARGINAL;
551 else if(ascii_strcasecmp(str,"full")==0)
552 return TRUST_FULLY;
553 else if(ascii_strcasecmp(str,"ultimate")==0)
554 return TRUST_ULTIMATE;
555 else
556 return -1;
559 /****************
560 * Recreate the WoT but do not ask for new ownertrusts. Special
561 * feature: In batch mode and without a forced yes, this is only done
562 * when a check is due. This can be used to run the check from a crontab
564 void
565 check_trustdb ()
567 init_trustdb();
568 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
570 if (opt.batch && !opt.answer_yes)
572 ulong scheduled;
574 scheduled = tdbio_read_nextcheck ();
575 if (!scheduled)
577 log_info (_("no need for a trustdb check\n"));
578 return;
581 if (scheduled > make_timestamp ())
583 log_info (_("next trustdb check due at %s\n"),
584 strtimestamp (scheduled));
585 return;
589 validate_keys (0);
591 else
592 log_info (_("no need for a trustdb check with `%s' trust model\n"),
593 trust_model_string());
598 * Recreate the WoT.
600 void
601 update_trustdb()
603 init_trustdb();
604 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
605 validate_keys (1);
606 else
607 log_info (_("no need for a trustdb update with `%s' trust model\n"),
608 trust_model_string());
611 void
612 revalidation_mark (void)
614 init_trustdb();
615 /* we simply set the time for the next check to 1 (far back in 1970)
616 * so that a --update-trustdb will be scheduled */
617 if (tdbio_write_nextcheck (1))
618 do_sync ();
619 pending_check_trustdb = 1;
623 trustdb_pending_check(void)
625 return pending_check_trustdb;
628 /* If the trustdb is dirty, and we're interactive, update it.
629 Otherwise, check it unless no-auto-check-trustdb is set. */
630 void
631 trustdb_check_or_update(void)
633 if(trustdb_pending_check())
635 if(opt.interactive)
636 update_trustdb();
637 else if(!opt.no_auto_check_trustdb)
638 check_trustdb();
642 void
643 read_trust_options(byte *trust_model,ulong *created,ulong *nextcheck,
644 byte *marginals,byte *completes,byte *cert_depth)
646 TRUSTREC opts;
648 init_trustdb();
650 read_record(0,&opts,RECTYPE_VER);
652 if(trust_model)
653 *trust_model=opts.r.ver.trust_model;
654 if(created)
655 *created=opts.r.ver.created;
656 if(nextcheck)
657 *nextcheck=opts.r.ver.nextcheck;
658 if(marginals)
659 *marginals=opts.r.ver.marginals;
660 if(completes)
661 *completes=opts.r.ver.completes;
662 if(cert_depth)
663 *cert_depth=opts.r.ver.cert_depth;
666 /***********************************************
667 *********** Ownertrust et al. ****************
668 ***********************************************/
670 static int
671 read_trust_record (PKT_public_key *pk, TRUSTREC *rec)
673 int rc;
675 init_trustdb();
676 rc = tdbio_search_trust_bypk (pk, rec);
677 if (rc == -1)
678 return -1; /* no record yet */
679 if (rc)
681 log_error ("trustdb: searching trust record failed: %s\n",
682 g10_errstr (rc));
683 return rc;
686 if (rec->rectype != RECTYPE_TRUST)
688 log_error ("trustdb: record %lu is not a trust record\n",
689 rec->recnum);
690 return G10ERR_TRUSTDB;
693 return 0;
696 /****************
697 * Return the assigned ownertrust value for the given public key.
698 * The key should be the primary key.
700 unsigned int
701 get_ownertrust ( PKT_public_key *pk)
703 TRUSTREC rec;
704 int rc;
706 rc = read_trust_record (pk, &rec);
707 if (rc == -1)
708 return TRUST_UNKNOWN; /* no record yet */
709 if (rc)
711 tdbio_invalid ();
712 return rc; /* actually never reached */
715 return rec.r.trust.ownertrust;
718 unsigned int
719 get_min_ownertrust (PKT_public_key *pk)
721 TRUSTREC rec;
722 int rc;
724 rc = read_trust_record (pk, &rec);
725 if (rc == -1)
726 return TRUST_UNKNOWN; /* no record yet */
727 if (rc)
729 tdbio_invalid ();
730 return rc; /* actually never reached */
733 return rec.r.trust.min_ownertrust;
737 * Same as get_ownertrust but this takes the minimum ownertrust value
738 * into into account, and will bump up the value as needed.
740 static int
741 get_ownertrust_with_min (PKT_public_key *pk)
743 unsigned int otrust,otrust_min;
745 otrust = (get_ownertrust (pk) & TRUST_MASK);
746 otrust_min = get_min_ownertrust (pk);
747 if(otrust<otrust_min)
749 /* If the trust that the user has set is less than the trust
750 that was calculated from a trust signature chain, use the
751 higher of the two. We do this here and not in
752 get_ownertrust since the underlying ownertrust should not
753 really be set - just the appearance of the ownertrust. */
755 otrust=otrust_min;
758 return otrust;
762 * Same as get_ownertrust but return a trust letter instead of an
763 * value. This takes the minimum ownertrust value into account.
766 get_ownertrust_info (PKT_public_key *pk)
768 return trust_letter(get_ownertrust_with_min(pk));
772 * Same as get_ownertrust but return a trust string instead of an
773 * value. This takes the minimum ownertrust value into account.
775 const char *
776 get_ownertrust_string (PKT_public_key *pk)
778 return trust_value_to_string(get_ownertrust_with_min(pk));
782 * Set the trust value of the given public key to the new value.
783 * The key should be a primary one.
785 void
786 update_ownertrust (PKT_public_key *pk, unsigned int new_trust )
788 TRUSTREC rec;
789 int rc;
791 rc = read_trust_record (pk, &rec);
792 if (!rc)
794 if (DBG_TRUST)
795 log_debug ("update ownertrust from %u to %u\n",
796 (unsigned int)rec.r.trust.ownertrust, new_trust );
797 if (rec.r.trust.ownertrust != new_trust)
799 rec.r.trust.ownertrust = new_trust;
800 write_record( &rec );
801 revalidation_mark ();
802 do_sync ();
805 else if (rc == -1)
806 { /* no record yet - create a new one */
807 size_t dummy;
809 if (DBG_TRUST)
810 log_debug ("insert ownertrust %u\n", new_trust );
812 memset (&rec, 0, sizeof rec);
813 rec.recnum = tdbio_new_recnum ();
814 rec.rectype = RECTYPE_TRUST;
815 fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
816 rec.r.trust.ownertrust = new_trust;
817 write_record (&rec);
818 revalidation_mark ();
819 do_sync ();
820 rc = 0;
822 else
824 tdbio_invalid ();
828 static void
829 update_min_ownertrust (u32 *kid, unsigned int new_trust )
831 PKT_public_key *pk;
832 TRUSTREC rec;
833 int rc;
835 pk = xmalloc_clear (sizeof *pk);
836 rc = get_pubkey (pk, kid);
837 if (rc)
839 log_error(_("public key %s not found: %s\n"),keystr(kid),g10_errstr(rc));
840 return;
843 rc = read_trust_record (pk, &rec);
844 if (!rc)
846 if (DBG_TRUST)
847 log_debug ("key %08lX%08lX: update min_ownertrust from %u to %u\n",
848 (ulong)kid[0],(ulong)kid[1],
849 (unsigned int)rec.r.trust.min_ownertrust,
850 new_trust );
851 if (rec.r.trust.min_ownertrust != new_trust)
853 rec.r.trust.min_ownertrust = new_trust;
854 write_record( &rec );
855 revalidation_mark ();
856 do_sync ();
859 else if (rc == -1)
860 { /* no record yet - create a new one */
861 size_t dummy;
863 if (DBG_TRUST)
864 log_debug ("insert min_ownertrust %u\n", new_trust );
866 memset (&rec, 0, sizeof rec);
867 rec.recnum = tdbio_new_recnum ();
868 rec.rectype = RECTYPE_TRUST;
869 fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
870 rec.r.trust.min_ownertrust = new_trust;
871 write_record (&rec);
872 revalidation_mark ();
873 do_sync ();
874 rc = 0;
876 else
878 tdbio_invalid ();
882 /* Clear the ownertrust and min_ownertrust values. Return true if a
883 change actually happened. */
885 clear_ownertrusts (PKT_public_key *pk)
887 TRUSTREC rec;
888 int rc;
890 rc = read_trust_record (pk, &rec);
891 if (!rc)
893 if (DBG_TRUST)
895 log_debug ("clearing ownertrust (old value %u)\n",
896 (unsigned int)rec.r.trust.ownertrust);
897 log_debug ("clearing min_ownertrust (old value %u)\n",
898 (unsigned int)rec.r.trust.min_ownertrust);
900 if (rec.r.trust.ownertrust || rec.r.trust.min_ownertrust)
902 rec.r.trust.ownertrust = 0;
903 rec.r.trust.min_ownertrust = 0;
904 write_record( &rec );
905 revalidation_mark ();
906 do_sync ();
907 return 1;
910 else if (rc != -1)
912 tdbio_invalid ();
914 return 0;
918 * Note: Caller has to do a sync
920 static void
921 update_validity (PKT_public_key *pk, PKT_user_id *uid,
922 int depth, int validity)
924 TRUSTREC trec, vrec;
925 int rc;
926 ulong recno;
928 namehash_from_uid(uid);
930 rc = read_trust_record (pk, &trec);
931 if (rc && rc != -1)
933 tdbio_invalid ();
934 return;
936 if (rc == -1) /* no record yet - create a new one */
938 size_t dummy;
940 rc = 0;
941 memset (&trec, 0, sizeof trec);
942 trec.recnum = tdbio_new_recnum ();
943 trec.rectype = RECTYPE_TRUST;
944 fingerprint_from_pk (pk, trec.r.trust.fingerprint, &dummy);
945 trec.r.trust.ownertrust = 0;
948 /* locate an existing one */
949 recno = trec.r.trust.validlist;
950 while (recno)
952 read_record (recno, &vrec, RECTYPE_VALID);
953 if ( !memcmp (vrec.r.valid.namehash, uid->namehash, 20) )
954 break;
955 recno = vrec.r.valid.next;
958 if (!recno) /* insert a new validity record */
960 memset (&vrec, 0, sizeof vrec);
961 vrec.recnum = tdbio_new_recnum ();
962 vrec.rectype = RECTYPE_VALID;
963 memcpy (vrec.r.valid.namehash, uid->namehash, 20);
964 vrec.r.valid.next = trec.r.trust.validlist;
965 trec.r.trust.validlist = vrec.recnum;
967 vrec.r.valid.validity = validity;
968 vrec.r.valid.full_count = uid->help_full_count;
969 vrec.r.valid.marginal_count = uid->help_marginal_count;
970 write_record (&vrec);
971 trec.r.trust.depth = depth;
972 write_record (&trec);
976 /***********************************************
977 ********* Query trustdb values **************
978 ***********************************************/
980 /* Return true if key is disabled */
982 cache_disabled_value(PKT_public_key *pk)
984 int rc;
985 TRUSTREC trec;
986 int disabled=0;
988 if(pk->is_disabled)
989 return (pk->is_disabled==2);
991 init_trustdb();
993 rc = read_trust_record (pk, &trec);
994 if (rc && rc != -1)
996 tdbio_invalid ();
997 goto leave;
999 if (rc == -1) /* no record found, so assume not disabled */
1000 goto leave;
1002 if(trec.r.trust.ownertrust & TRUST_FLAG_DISABLED)
1003 disabled=1;
1005 /* Cache it for later so we don't need to look at the trustdb every
1006 time */
1007 if(disabled)
1008 pk->is_disabled=2;
1009 else
1010 pk->is_disabled=1;
1012 leave:
1013 return disabled;
1016 void
1017 check_trustdb_stale(void)
1019 static int did_nextcheck=0;
1021 init_trustdb ();
1022 if (!did_nextcheck
1023 && (opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC))
1025 ulong scheduled;
1027 did_nextcheck = 1;
1028 scheduled = tdbio_read_nextcheck ();
1029 if (scheduled && scheduled <= make_timestamp ())
1031 if (opt.no_auto_check_trustdb)
1033 pending_check_trustdb = 1;
1034 log_info (_("please do a --check-trustdb\n"));
1036 else
1038 log_info (_("checking the trustdb\n"));
1039 validate_keys (0);
1046 * Return the validity information for PK. If the namehash is not
1047 * NULL, the validity of the corresponsing user ID is returned,
1048 * otherwise, a reasonable value for the entire key is returned.
1050 unsigned int
1051 get_validity (PKT_public_key *pk, PKT_user_id *uid)
1053 TRUSTREC trec, vrec;
1054 int rc;
1055 ulong recno;
1056 unsigned int validity;
1057 u32 kid[2];
1058 PKT_public_key *main_pk;
1060 if(uid)
1061 namehash_from_uid(uid);
1063 init_trustdb ();
1064 check_trustdb_stale();
1066 keyid_from_pk (pk, kid);
1067 if (pk->main_keyid[0] != kid[0] || pk->main_keyid[1] != kid[1])
1068 { /* this is a subkey - get the mainkey */
1069 main_pk = xmalloc_clear (sizeof *main_pk);
1070 rc = get_pubkey (main_pk, pk->main_keyid);
1071 if (rc)
1073 char *tempkeystr=xstrdup(keystr(pk->main_keyid));
1074 log_error ("error getting main key %s of subkey %s: %s\n",
1075 tempkeystr, keystr(kid), g10_errstr(rc));
1076 xfree(tempkeystr);
1077 validity = TRUST_UNKNOWN;
1078 goto leave;
1081 else
1082 main_pk = pk;
1084 if(opt.trust_model==TM_DIRECT)
1086 /* Note that this happens BEFORE any user ID stuff is checked.
1087 The direct trust model applies to keys as a whole. */
1088 validity=get_ownertrust(main_pk);
1089 goto leave;
1092 rc = read_trust_record (main_pk, &trec);
1093 if (rc && rc != -1)
1095 tdbio_invalid ();
1096 return 0;
1098 if (rc == -1) /* no record found */
1100 validity = TRUST_UNKNOWN;
1101 goto leave;
1104 /* loop over all user IDs */
1105 recno = trec.r.trust.validlist;
1106 validity = 0;
1107 while (recno)
1109 read_record (recno, &vrec, RECTYPE_VALID);
1111 if(uid)
1113 /* If a user ID is given we return the validity for that
1114 user ID ONLY. If the namehash is not found, then there
1115 is no validity at all (i.e. the user ID wasn't
1116 signed). */
1117 if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1119 validity=(vrec.r.valid.validity & TRUST_MASK);
1120 break;
1123 else
1125 /* If no namehash is given, we take the maximum validity
1126 over all user IDs */
1127 if ( validity < (vrec.r.valid.validity & TRUST_MASK) )
1128 validity = (vrec.r.valid.validity & TRUST_MASK);
1131 recno = vrec.r.valid.next;
1134 if ( (trec.r.trust.ownertrust & TRUST_FLAG_DISABLED) )
1136 validity |= TRUST_FLAG_DISABLED;
1137 pk->is_disabled=2;
1139 else
1140 pk->is_disabled=1;
1142 leave:
1143 /* set some flags direct from the key */
1144 if (main_pk->is_revoked)
1145 validity |= TRUST_FLAG_REVOKED;
1146 if (main_pk != pk && pk->is_revoked)
1147 validity |= TRUST_FLAG_SUB_REVOKED;
1148 /* Note: expiration is a trust value and not a flag - don't know why
1149 * I initially designed it that way */
1150 if (main_pk->has_expired || pk->has_expired)
1151 validity = (validity & ~TRUST_MASK) | TRUST_EXPIRED;
1153 if (pending_check_trustdb)
1154 validity |= TRUST_FLAG_PENDING_CHECK;
1156 if (main_pk != pk)
1157 free_public_key (main_pk);
1158 return validity;
1162 get_validity_info (PKT_public_key *pk, PKT_user_id *uid)
1164 int trustlevel;
1166 trustlevel = get_validity (pk, uid);
1167 if( trustlevel & TRUST_FLAG_REVOKED )
1168 return 'r';
1169 return trust_letter ( trustlevel );
1172 const char *
1173 get_validity_string (PKT_public_key *pk, PKT_user_id *uid)
1175 int trustlevel;
1177 trustlevel = get_validity (pk, uid);
1178 if( trustlevel & TRUST_FLAG_REVOKED )
1179 return _("revoked");
1180 return trust_value_to_string(trustlevel);
1183 static void
1184 get_validity_counts (PKT_public_key *pk, PKT_user_id *uid)
1186 TRUSTREC trec, vrec;
1187 ulong recno;
1189 if(pk==NULL || uid==NULL)
1190 BUG();
1192 namehash_from_uid(uid);
1194 uid->help_marginal_count=uid->help_full_count=0;
1196 init_trustdb ();
1198 if(read_trust_record (pk, &trec)!=0)
1199 return;
1201 /* loop over all user IDs */
1202 recno = trec.r.trust.validlist;
1203 while (recno)
1205 read_record (recno, &vrec, RECTYPE_VALID);
1207 if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1209 uid->help_marginal_count=vrec.r.valid.marginal_count;
1210 uid->help_full_count=vrec.r.valid.full_count;
1211 /* printf("Fetched marginal %d, full %d\n",uid->help_marginal_count,uid->help_full_count); */
1212 break;
1215 recno = vrec.r.valid.next;
1219 void
1220 list_trust_path( const char *username )
1224 /****************
1225 * Enumerate all keys, which are needed to build all trust paths for
1226 * the given key. This function does not return the key itself or
1227 * the ultimate key (the last point in cerificate chain). Only
1228 * certificate chains which ends up at an ultimately trusted key
1229 * are listed. If ownertrust or validity is not NULL, the corresponding
1230 * value for the returned LID is also returned in these variable(s).
1232 * 1) create a void pointer and initialize it to NULL
1233 * 2) pass this void pointer by reference to this function.
1234 * Set lid to the key you want to enumerate and pass it by reference.
1235 * 3) call this function as long as it does not return -1
1236 * to indicate EOF. LID does contain the next key used to build the web
1237 * 4) Always call this function a last time with LID set to NULL,
1238 * so that it can free its context.
1240 * Returns: -1 on EOF or the level of the returned LID
1243 enum_cert_paths( void **context, ulong *lid,
1244 unsigned *ownertrust, unsigned *validity )
1246 return -1;
1250 /****************
1251 * Print the current path
1253 void
1254 enum_cert_paths_print( void **context, FILE *fp,
1255 int refresh, ulong selected_lid )
1257 return;
1262 /****************************************
1263 *********** NEW NEW NEW ****************
1264 ****************************************/
1266 static int
1267 ask_ownertrust (u32 *kid,int minimum)
1269 PKT_public_key *pk;
1270 int rc;
1271 int ot;
1273 pk = xmalloc_clear (sizeof *pk);
1274 rc = get_pubkey (pk, kid);
1275 if (rc)
1277 log_error (_("public key %s not found: %s\n"),
1278 keystr(kid), g10_errstr(rc) );
1279 return TRUST_UNKNOWN;
1282 if(opt.force_ownertrust)
1284 log_info("force trust for key %s to %s\n",
1285 keystr(kid),trust_value_to_string(opt.force_ownertrust));
1286 update_ownertrust(pk,opt.force_ownertrust);
1287 ot=opt.force_ownertrust;
1289 else
1291 ot=edit_ownertrust(pk,0);
1292 if(ot>0)
1293 ot = get_ownertrust (pk);
1294 else if(ot==0)
1295 ot = minimum?minimum:TRUST_UNDEFINED;
1296 else
1297 ot = -1; /* quit */
1300 free_public_key( pk );
1302 return ot;
1306 static void
1307 mark_keyblock_seen (KeyHashTable tbl, KBNODE node)
1309 for ( ;node; node = node->next )
1310 if (node->pkt->pkttype == PKT_PUBLIC_KEY
1311 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1313 u32 aki[2];
1315 keyid_from_pk (node->pkt->pkt.public_key, aki);
1316 add_key_hash_table (tbl, aki);
1321 static void
1322 dump_key_array (int depth, struct key_array *keys)
1324 struct key_array *kar;
1326 for (kar=keys; kar->keyblock; kar++)
1328 KBNODE node = kar->keyblock;
1329 u32 kid[2];
1331 keyid_from_pk(node->pkt->pkt.public_key, kid);
1332 printf ("%d:%08lX%08lX:K::%c::::\n",
1333 depth, (ulong)kid[0], (ulong)kid[1], '?');
1335 for (; node; node = node->next)
1337 if (node->pkt->pkttype == PKT_USER_ID)
1339 int len = node->pkt->pkt.user_id->len;
1341 if (len > 30)
1342 len = 30;
1343 printf ("%d:%08lX%08lX:U:::%c:::",
1344 depth, (ulong)kid[0], (ulong)kid[1],
1345 (node->flag & 4)? 'f':
1346 (node->flag & 2)? 'm':
1347 (node->flag & 1)? 'q':'-');
1348 print_string (stdout, node->pkt->pkt.user_id->name, len, ':');
1349 putchar (':');
1350 putchar ('\n');
1357 static void
1358 store_validation_status (int depth, KBNODE keyblock, KeyHashTable stored)
1360 KBNODE node;
1361 int status;
1362 int any = 0;
1364 for (node=keyblock; node; node = node->next)
1366 if (node->pkt->pkttype == PKT_USER_ID)
1368 PKT_user_id *uid = node->pkt->pkt.user_id;
1369 if (node->flag & 4)
1370 status = TRUST_FULLY;
1371 else if (node->flag & 2)
1372 status = TRUST_MARGINAL;
1373 else if (node->flag & 1)
1374 status = TRUST_UNDEFINED;
1375 else
1376 status = 0;
1378 if (status)
1380 update_validity (keyblock->pkt->pkt.public_key,
1381 uid, depth, status);
1383 mark_keyblock_seen(stored,keyblock);
1385 any = 1;
1390 if (any)
1391 do_sync ();
1395 * check whether the signature sig is in the klist k
1397 static struct key_item *
1398 is_in_klist (struct key_item *k, PKT_signature *sig)
1400 for (; k; k = k->next)
1402 if (k->kid[0] == sig->keyid[0] && k->kid[1] == sig->keyid[1])
1403 return k;
1405 return NULL;
1409 * Mark the signature of the given UID which are used to certify it.
1410 * To do this, we first revmove all signatures which are not valid and
1411 * from the remain ones we look for the latest one. If this is not a
1412 * certification revocation signature we mark the signature by setting
1413 * node flag bit 8. Revocations are marked with flag 11, and sigs
1414 * from unavailable keys are marked with flag 12. Note that flag bits
1415 * 9 and 10 are used for internal purposes.
1417 static void
1418 mark_usable_uid_certs (KBNODE keyblock, KBNODE uidnode,
1419 u32 *main_kid, struct key_item *klist,
1420 u32 curtime, u32 *next_expire)
1422 KBNODE node;
1423 PKT_signature *sig;
1425 /* first check all signatures */
1426 for (node=uidnode->next; node; node = node->next)
1428 int rc;
1430 node->flag &= ~(1<<8 | 1<<9 | 1<<10 | 1<<11 | 1<<12);
1431 if (node->pkt->pkttype == PKT_USER_ID
1432 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1433 break; /* ready */
1434 if (node->pkt->pkttype != PKT_SIGNATURE)
1435 continue;
1436 sig = node->pkt->pkt.signature;
1437 if (main_kid
1438 && sig->keyid[0] == main_kid[0] && sig->keyid[1] == main_kid[1])
1439 continue; /* ignore self-signatures if we pass in a main_kid */
1440 if (!IS_UID_SIG(sig) && !IS_UID_REV(sig))
1441 continue; /* we only look at these signature classes */
1442 if(sig->sig_class>=0x11 && sig->sig_class<=0x13 &&
1443 sig->sig_class-0x10<opt.min_cert_level)
1444 continue; /* treat anything under our min_cert_level as an
1445 invalid signature */
1446 if (klist && !is_in_klist (klist, sig))
1447 continue; /* no need to check it then */
1448 if ((rc=check_key_signature (keyblock, node, NULL)))
1450 /* we ignore anything that won't verify, but tag the
1451 no_pubkey case */
1452 if(rc==G10ERR_NO_PUBKEY)
1453 node->flag |= 1<<12;
1454 continue;
1456 node->flag |= 1<<9;
1458 /* reset the remaining flags */
1459 for (; node; node = node->next)
1460 node->flag &= ~(1<<8 | 1<<9 | 1<<10 | 1<<11 | 1<<12);
1462 /* kbnode flag usage: bit 9 is here set for signatures to consider,
1463 * bit 10 will be set by the loop to keep track of keyIDs already
1464 * processed, bit 8 will be set for the usable signatures, and bit
1465 * 11 will be set for usable revocations. */
1467 /* for each cert figure out the latest valid one */
1468 for (node=uidnode->next; node; node = node->next)
1470 KBNODE n, signode;
1471 u32 kid[2];
1472 u32 sigdate;
1474 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1475 break;
1476 if ( !(node->flag & (1<<9)) )
1477 continue; /* not a node to look at */
1478 if ( (node->flag & (1<<10)) )
1479 continue; /* signature with a keyID already processed */
1480 node->flag |= (1<<10); /* mark this node as processed */
1481 sig = node->pkt->pkt.signature;
1482 signode = node;
1483 sigdate = sig->timestamp;
1484 kid[0] = sig->keyid[0]; kid[1] = sig->keyid[1];
1486 /* Now find the latest and greatest signature */
1487 for (n=uidnode->next; n; n = n->next)
1489 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1490 break;
1491 if ( !(n->flag & (1<<9)) )
1492 continue;
1493 if ( (n->flag & (1<<10)) )
1494 continue; /* shortcut already processed signatures */
1495 sig = n->pkt->pkt.signature;
1496 if (kid[0] != sig->keyid[0] || kid[1] != sig->keyid[1])
1497 continue;
1498 n->flag |= (1<<10); /* mark this node as processed */
1500 /* If signode is nonrevocable and unexpired and n isn't,
1501 then take signode (skip). It doesn't matter which is
1502 older: if signode was older then we don't want to take n
1503 as signode is nonrevocable. If n was older then we're
1504 automatically fine. */
1506 if(((IS_UID_SIG(signode->pkt->pkt.signature) &&
1507 !signode->pkt->pkt.signature->flags.revocable &&
1508 (signode->pkt->pkt.signature->expiredate==0 ||
1509 signode->pkt->pkt.signature->expiredate>curtime))) &&
1510 (!(IS_UID_SIG(n->pkt->pkt.signature) &&
1511 !n->pkt->pkt.signature->flags.revocable &&
1512 (n->pkt->pkt.signature->expiredate==0 ||
1513 n->pkt->pkt.signature->expiredate>curtime))))
1514 continue;
1516 /* If n is nonrevocable and unexpired and signode isn't,
1517 then take n. Again, it doesn't matter which is older: if
1518 n was older then we don't want to take signode as n is
1519 nonrevocable. If signode was older then we're
1520 automatically fine. */
1522 if((!(IS_UID_SIG(signode->pkt->pkt.signature) &&
1523 !signode->pkt->pkt.signature->flags.revocable &&
1524 (signode->pkt->pkt.signature->expiredate==0 ||
1525 signode->pkt->pkt.signature->expiredate>curtime))) &&
1526 ((IS_UID_SIG(n->pkt->pkt.signature) &&
1527 !n->pkt->pkt.signature->flags.revocable &&
1528 (n->pkt->pkt.signature->expiredate==0 ||
1529 n->pkt->pkt.signature->expiredate>curtime))))
1531 signode = n;
1532 sigdate = sig->timestamp;
1533 continue;
1536 /* At this point, if it's newer, it goes in as the only
1537 remaining possibilities are signode and n are both either
1538 revocable or expired or both nonrevocable and unexpired.
1539 If the timestamps are equal take the later ordered
1540 packet, presuming that the key packets are hopefully in
1541 their original order. */
1543 if (sig->timestamp >= sigdate)
1545 signode = n;
1546 sigdate = sig->timestamp;
1550 sig = signode->pkt->pkt.signature;
1551 if (IS_UID_SIG (sig))
1552 { /* this seems to be a usable one which is not revoked.
1553 * Just need to check whether there is an expiration time,
1554 * We do the expired certification after finding a suitable
1555 * certification, the assumption is that a signator does not
1556 * want that after the expiration of his certificate the
1557 * system falls back to an older certification which has a
1558 * different expiration time */
1559 const byte *p;
1560 u32 expire;
1562 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_EXPIRE, NULL );
1563 expire = p? sig->timestamp + buffer_to_u32(p) : 0;
1565 if (expire==0 || expire > curtime )
1567 signode->flag |= (1<<8); /* yeah, found a good cert */
1568 if (next_expire && expire && expire < *next_expire)
1569 *next_expire = expire;
1572 else
1573 signode->flag |= (1<<11);
1577 static int
1578 clean_sigs_from_uid(KBNODE keyblock,KBNODE uidnode,int noisy,int self_only)
1580 int deleted=0;
1581 KBNODE node;
1582 u32 keyid[2];
1584 assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY);
1586 keyid_from_pk(keyblock->pkt->pkt.public_key,keyid);
1588 /* Passing in a 0 for current time here means that we'll never weed
1589 out an expired sig. This is correct behavior since we want to
1590 keep the most recent expired sig in a series. */
1591 mark_usable_uid_certs(keyblock,uidnode,NULL,NULL,0,NULL);
1593 /* What we want to do here is remove signatures that are not
1594 considered as part of the trust calculations. Thus, all invalid
1595 signatures are out, as are any signatures that aren't the last of
1596 a series of uid sigs or revocations It breaks down like this:
1597 coming out of mark_usable_uid_certs, if a sig is unflagged, it is
1598 not even a candidate. If a sig has flag 9 or 10, that means it
1599 was selected as a candidate and vetted. If a sig has flag 8 it
1600 is a usable signature. If a sig has flag 11 it is a usable
1601 revocation. If a sig has flag 12 it was issued by an unavailable
1602 key. "Usable" here means the most recent valid
1603 signature/revocation in a series from a particular signer.
1605 Delete everything that isn't a usable uid sig (which might be
1606 expired), a usable revocation, or a sig from an unavailable
1607 key. */
1609 for(node=uidnode->next;
1610 node && node->pkt->pkttype==PKT_SIGNATURE;
1611 node=node->next)
1613 int keep=self_only?(node->pkt->pkt.signature->keyid[0]==keyid[0]
1614 && node->pkt->pkt.signature->keyid[1]==keyid[1]):1;
1616 /* Keep usable uid sigs ... */
1617 if((node->flag & (1<<8)) && keep)
1618 continue;
1620 /* ... and usable revocations... */
1621 if((node->flag & (1<<11)) && keep)
1622 continue;
1624 /* ... and sigs from unavailable keys. */
1625 /* disabled for now since more people seem to want sigs from
1626 unavailable keys removed altogether. */
1628 if(node->flag & (1<<12))
1629 continue;
1632 /* Everything else we delete */
1634 /* At this point, if 12 is set, the signing key was unavailable.
1635 If 9 or 10 is set, it's superceded. Otherwise, it's
1636 invalid. */
1638 if(noisy)
1639 log_info("removing signature from key %s on user ID \"%s\": %s\n",
1640 keystr(node->pkt->pkt.signature->keyid),
1641 uidnode->pkt->pkt.user_id->name,
1642 node->flag&(1<<12)?"key unavailable":
1643 node->flag&(1<<9)?"signature superceded":"invalid signature");
1645 delete_kbnode(node);
1646 deleted++;
1649 return deleted;
1652 /* This is substantially easier than clean_sigs_from_uid since we just
1653 have to establish if the uid has a valid self-sig, is not revoked,
1654 and is not expired. Note that this does not take into account
1655 whether the uid has a trust path to it - just whether the keyholder
1656 themselves has certified the uid. Returns true if the uid was
1657 compacted. To "compact" a user ID, we simply remove ALL signatures
1658 except the self-sig that caused the user ID to be remove-worthy.
1659 We don't actually remove the user ID packet itself since it might
1660 be ressurected in a later merge. Note that this function requires
1661 that the caller has already done a merge_keys_and_selfsig().
1663 TODO: change the import code to allow importing a uid with only a
1664 revocation if the uid already exists on the keyring. */
1666 static int
1667 clean_uid_from_key(KBNODE keyblock,KBNODE uidnode,int noisy)
1669 KBNODE node;
1670 PKT_user_id *uid=uidnode->pkt->pkt.user_id;
1671 int deleted=0;
1673 assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY);
1674 assert(uidnode->pkt->pkttype==PKT_USER_ID);
1676 /* Skip valid user IDs, compacted user IDs, and non-self-signed user
1677 IDs if --allow-non-selfsigned-uid is set. */
1678 if(uid->created || uid->flags.compacted
1679 || (!uid->is_expired && !uid->is_revoked
1680 && opt.allow_non_selfsigned_uid))
1681 return 0;
1683 for(node=uidnode->next;
1684 node && node->pkt->pkttype==PKT_SIGNATURE;
1685 node=node->next)
1686 if(!node->pkt->pkt.signature->flags.chosen_selfsig)
1688 delete_kbnode(node);
1689 deleted=1;
1690 uidnode->pkt->pkt.user_id->flags.compacted=1;
1693 if(noisy)
1695 const char *reason;
1696 char *user=utf8_to_native(uid->name,uid->len,0);
1698 if(uid->is_revoked)
1699 reason=_("revoked");
1700 else if(uid->is_expired)
1701 reason=_("expired");
1702 else
1703 reason=_("invalid");
1705 log_info("compacting user ID \"%s\" on key %s: %s\n",
1706 user,keystr_from_pk(keyblock->pkt->pkt.public_key),
1707 reason);
1709 xfree(user);
1712 return deleted;
1715 /* Needs to be called after a merge_keys_and_selfsig() */
1716 void
1717 clean_one_uid(KBNODE keyblock,KBNODE uidnode,int noisy,int self_only,
1718 int *uids_cleaned,int *sigs_cleaned)
1720 int dummy;
1722 assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY);
1723 assert(uidnode->pkt->pkttype==PKT_USER_ID);
1725 if(!uids_cleaned)
1726 uids_cleaned=&dummy;
1728 if(!sigs_cleaned)
1729 sigs_cleaned=&dummy;
1731 /* Do clean_uid_from_key first since if it fires off, we don't
1732 have to bother with the other */
1733 *uids_cleaned+=clean_uid_from_key(keyblock,uidnode,noisy);
1734 if(!uidnode->pkt->pkt.user_id->flags.compacted)
1735 *sigs_cleaned+=clean_sigs_from_uid(keyblock,uidnode,noisy,self_only);
1738 void
1739 clean_key(KBNODE keyblock,int noisy,int self_only,
1740 int *uids_cleaned,int *sigs_cleaned)
1742 KBNODE uidnode;
1744 merge_keys_and_selfsig(keyblock);
1746 for(uidnode=keyblock->next;
1747 uidnode && uidnode->pkt->pkttype!=PKT_PUBLIC_SUBKEY;
1748 uidnode=uidnode->next)
1749 if(uidnode->pkt->pkttype==PKT_USER_ID)
1750 clean_one_uid(keyblock,uidnode,noisy,self_only,
1751 uids_cleaned,sigs_cleaned);
1754 /* Used by validate_one_keyblock to confirm a regexp within a trust
1755 signature. Returns 1 for match, and 0 for no match or regex
1756 error. */
1757 static int
1758 check_regexp(const char *expr,const char *string)
1760 #ifdef DISABLE_REGEX
1761 /* When DISABLE_REGEX is defined, assume all regexps do not
1762 match. */
1763 return 0;
1764 #elif defined(__riscos__)
1765 return riscos_check_regexp(expr, string, DBG_TRUST);
1766 #else
1767 int ret;
1768 regex_t pat;
1770 if(regcomp(&pat,expr,REG_ICASE|REG_NOSUB|REG_EXTENDED)!=0)
1771 return 0;
1773 ret=regexec(&pat,string,0,NULL,0);
1775 regfree(&pat);
1777 if(DBG_TRUST)
1778 log_debug("regexp `%s' on `%s': %s\n",expr,string,ret==0?"YES":"NO");
1780 return (ret==0);
1781 #endif
1785 * Return true if the key is signed by one of the keys in the given
1786 * key ID list. User IDs with a valid signature are marked by node
1787 * flags as follows:
1788 * flag bit 0: There is at least one signature
1789 * 1: There is marginal confidence that this is a legitimate uid
1790 * 2: There is full confidence that this is a legitimate uid.
1791 * 8: Used for internal purposes.
1792 * 9: Ditto (in mark_usable_uid_certs())
1793 * 10: Ditto (ditto)
1794 * This function assumes that all kbnode flags are cleared on entry.
1796 static int
1797 validate_one_keyblock (KBNODE kb, struct key_item *klist,
1798 u32 curtime, u32 *next_expire)
1800 struct key_item *kr;
1801 KBNODE node, uidnode=NULL;
1802 PKT_user_id *uid=NULL;
1803 PKT_public_key *pk = kb->pkt->pkt.public_key;
1804 u32 main_kid[2];
1805 int issigned=0, any_signed = 0;
1807 keyid_from_pk(pk, main_kid);
1808 for (node=kb; node; node = node->next)
1810 /* A bit of discussion here: is it better for the web of trust
1811 to be built among only self-signed uids? On the one hand, a
1812 self-signed uid is a statement that the key owner definitely
1813 intended that uid to be there, but on the other hand, a
1814 signed (but not self-signed) uid does carry trust, of a sort,
1815 even if it is a statement being made by people other than the
1816 key owner "through" the uids on the key owner's key. I'm
1817 going with the latter. However, if the user ID was
1818 explicitly revoked, or passively allowed to expire, that
1819 should stop validity through the user ID until it is
1820 resigned. -dshaw */
1822 if (node->pkt->pkttype == PKT_USER_ID
1823 && !node->pkt->pkt.user_id->is_revoked
1824 && !node->pkt->pkt.user_id->is_expired)
1826 if (uidnode && issigned)
1828 if (uid->help_full_count >= opt.completes_needed
1829 || uid->help_marginal_count >= opt.marginals_needed )
1830 uidnode->flag |= 4;
1831 else if (uid->help_full_count || uid->help_marginal_count)
1832 uidnode->flag |= 2;
1833 uidnode->flag |= 1;
1834 any_signed = 1;
1836 uidnode = node;
1837 uid=uidnode->pkt->pkt.user_id;
1839 /* If the selfsig is going to expire... */
1840 if(uid->expiredate && uid->expiredate<*next_expire)
1841 *next_expire = uid->expiredate;
1843 issigned = 0;
1844 get_validity_counts(pk,uid);
1845 mark_usable_uid_certs (kb, uidnode, main_kid, klist,
1846 curtime, next_expire);
1848 else if (node->pkt->pkttype == PKT_SIGNATURE
1849 && (node->flag & (1<<8)) && uid)
1851 /* Note that we are only seeing unrevoked sigs here */
1852 PKT_signature *sig = node->pkt->pkt.signature;
1854 kr = is_in_klist (klist, sig);
1855 /* If the trust_regexp does not match, it's as if the sig
1856 did not exist. This is safe for non-trust sigs as well
1857 since we don't accept a regexp on the sig unless it's a
1858 trust sig. */
1859 if (kr && (kr->trust_regexp==NULL || opt.trust_model!=TM_PGP ||
1860 (uidnode && check_regexp(kr->trust_regexp,
1861 uidnode->pkt->pkt.user_id->name))))
1863 if(DBG_TRUST && opt.trust_model==TM_PGP && sig->trust_depth)
1864 log_debug("trust sig on %s, sig depth is %d, kr depth is %d\n",
1865 uidnode->pkt->pkt.user_id->name,sig->trust_depth,
1866 kr->trust_depth);
1868 /* Are we part of a trust sig chain? We always favor
1869 the latest trust sig, rather than the greater or
1870 lesser trust sig or value. I could make a decent
1871 argument for any of these cases, but this seems to be
1872 what PGP does, and I'd like to be compatible. -dms */
1873 if(opt.trust_model==TM_PGP && sig->trust_depth
1874 && pk->trust_timestamp<=sig->timestamp
1875 && (sig->trust_depth<=kr->trust_depth
1876 || kr->ownertrust==TRUST_ULTIMATE))
1878 /* If we got here, we know that:
1880 this is a trust sig.
1882 it's a newer trust sig than any previous trust
1883 sig on this key (not uid).
1885 it is legal in that it was either generated by an
1886 ultimate key, or a key that was part of a trust
1887 chain, and the depth does not violate the
1888 original trust sig.
1890 if there is a regexp attached, it matched
1891 successfully.
1894 if(DBG_TRUST)
1895 log_debug("replacing trust value %d with %d and "
1896 "depth %d with %d\n",
1897 pk->trust_value,sig->trust_value,
1898 pk->trust_depth,sig->trust_depth);
1900 pk->trust_value=sig->trust_value;
1901 pk->trust_depth=sig->trust_depth-1;
1903 /* If the trust sig contains a regexp, record it
1904 on the pk for the next round. */
1905 if(sig->trust_regexp)
1906 pk->trust_regexp=sig->trust_regexp;
1909 if (kr->ownertrust == TRUST_ULTIMATE)
1910 uid->help_full_count = opt.completes_needed;
1911 else if (kr->ownertrust == TRUST_FULLY)
1912 uid->help_full_count++;
1913 else if (kr->ownertrust == TRUST_MARGINAL)
1914 uid->help_marginal_count++;
1915 issigned = 1;
1920 if (uidnode && issigned)
1922 if (uid->help_full_count >= opt.completes_needed
1923 || uid->help_marginal_count >= opt.marginals_needed )
1924 uidnode->flag |= 4;
1925 else if (uid->help_full_count || uid->help_marginal_count)
1926 uidnode->flag |= 2;
1927 uidnode->flag |= 1;
1928 any_signed = 1;
1931 return any_signed;
1935 static int
1936 search_skipfnc (void *opaque, u32 *kid, PKT_user_id *dummy)
1938 return test_key_hash_table ((KeyHashTable)opaque, kid);
1943 * Scan all keys and return a key_array of all suitable keys from
1944 * kllist. The caller has to pass keydb handle so that we don't use
1945 * to create our own. Returns either a key_array or NULL in case of
1946 * an error. No results found are indicated by an empty array.
1947 * Caller hast to release the returned array.
1949 static struct key_array *
1950 validate_key_list (KEYDB_HANDLE hd, KeyHashTable full_trust,
1951 struct key_item *klist, u32 curtime, u32 *next_expire)
1953 KBNODE keyblock = NULL;
1954 struct key_array *keys = NULL;
1955 size_t nkeys, maxkeys;
1956 int rc;
1957 KEYDB_SEARCH_DESC desc;
1959 maxkeys = 1000;
1960 keys = xmalloc ((maxkeys+1) * sizeof *keys);
1961 nkeys = 0;
1963 rc = keydb_search_reset (hd);
1964 if (rc)
1966 log_error ("keydb_search_reset failed: %s\n", g10_errstr(rc));
1967 xfree (keys);
1968 return NULL;
1971 memset (&desc, 0, sizeof desc);
1972 desc.mode = KEYDB_SEARCH_MODE_FIRST;
1973 desc.skipfnc = search_skipfnc;
1974 desc.skipfncvalue = full_trust;
1975 rc = keydb_search (hd, &desc, 1);
1976 if (rc == -1)
1978 keys[nkeys].keyblock = NULL;
1979 return keys;
1981 if (rc)
1983 log_error ("keydb_search_first failed: %s\n", g10_errstr(rc));
1984 xfree (keys);
1985 return NULL;
1988 desc.mode = KEYDB_SEARCH_MODE_NEXT; /* change mode */
1991 PKT_public_key *pk;
1993 rc = keydb_get_keyblock (hd, &keyblock);
1994 if (rc)
1996 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
1997 xfree (keys);
1998 return NULL;
2001 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2003 log_debug ("ooops: invalid pkttype %d encountered\n",
2004 keyblock->pkt->pkttype);
2005 dump_kbnode (keyblock);
2006 release_kbnode(keyblock);
2007 continue;
2010 /* prepare the keyblock for further processing */
2011 merge_keys_and_selfsig (keyblock);
2012 clear_kbnode_flags (keyblock);
2013 pk = keyblock->pkt->pkt.public_key;
2014 if (pk->has_expired || pk->is_revoked)
2016 /* it does not make sense to look further at those keys */
2017 mark_keyblock_seen (full_trust, keyblock);
2019 else if (validate_one_keyblock (keyblock, klist, curtime, next_expire))
2021 KBNODE node;
2023 if (pk->expiredate && pk->expiredate >= curtime
2024 && pk->expiredate < *next_expire)
2025 *next_expire = pk->expiredate;
2027 if (nkeys == maxkeys) {
2028 maxkeys += 1000;
2029 keys = xrealloc (keys, (maxkeys+1) * sizeof *keys);
2031 keys[nkeys++].keyblock = keyblock;
2033 /* Optimization - if all uids are fully trusted, then we
2034 never need to consider this key as a candidate again. */
2036 for (node=keyblock; node; node = node->next)
2037 if (node->pkt->pkttype == PKT_USER_ID && !(node->flag & 4))
2038 break;
2040 if(node==NULL)
2041 mark_keyblock_seen (full_trust, keyblock);
2043 keyblock = NULL;
2046 release_kbnode (keyblock);
2047 keyblock = NULL;
2049 while ( !(rc = keydb_search (hd, &desc, 1)) );
2050 if (rc && rc != -1)
2052 log_error ("keydb_search_next failed: %s\n", g10_errstr(rc));
2053 xfree (keys);
2054 return NULL;
2057 keys[nkeys].keyblock = NULL;
2058 return keys;
2061 /* Caller must sync */
2062 static void
2063 reset_trust_records(void)
2065 TRUSTREC rec;
2066 ulong recnum;
2067 int count = 0, nreset = 0;
2069 for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
2071 if(rec.rectype==RECTYPE_TRUST)
2073 count++;
2074 if(rec.r.trust.min_ownertrust)
2076 rec.r.trust.min_ownertrust=0;
2077 write_record(&rec);
2081 else if(rec.rectype==RECTYPE_VALID
2082 && ((rec.r.valid.validity&TRUST_MASK)
2083 || rec.r.valid.marginal_count
2084 || rec.r.valid.full_count))
2086 rec.r.valid.validity &= ~TRUST_MASK;
2087 rec.r.valid.marginal_count=rec.r.valid.full_count=0;
2088 nreset++;
2089 write_record(&rec);
2094 if (opt.verbose)
2095 log_info (_("%d keys processed (%d validity counts cleared)\n"),
2096 count, nreset);
2100 * Run the key validation procedure.
2102 * This works this way:
2103 * Step 1: Find all ultimately trusted keys (UTK).
2104 * mark them all as seen and put them into klist.
2105 * Step 2: loop max_cert_times
2106 * Step 3: if OWNERTRUST of any key in klist is undefined
2107 * ask user to assign ownertrust
2108 * Step 4: Loop over all keys in the keyDB which are not marked seen
2109 * Step 5: if key is revoked or expired
2110 * mark key as seen
2111 * continue loop at Step 4
2112 * Step 6: For each user ID of that key signed by a key in klist
2113 * Calculate validity by counting trusted signatures.
2114 * Set validity of user ID
2115 * Step 7: If any signed user ID was found
2116 * mark key as seen
2117 * End Loop
2118 * Step 8: Build a new klist from all fully trusted keys from step 6
2119 * End Loop
2120 * Ready
2123 static int
2124 validate_keys (int interactive)
2126 int rc = 0;
2127 int quit=0;
2128 struct key_item *klist = NULL;
2129 struct key_item *k;
2130 struct key_array *keys = NULL;
2131 struct key_array *kar;
2132 KEYDB_HANDLE kdb = NULL;
2133 KBNODE node;
2134 int depth;
2135 int ot_unknown, ot_undefined, ot_never, ot_marginal, ot_full, ot_ultimate;
2136 KeyHashTable stored,used,full_trust;
2137 u32 start_time, next_expire;
2139 /* Make sure we have all sigs cached. TODO: This is going to
2140 require some architectual re-thinking, as it is agonizingly slow.
2141 Perhaps combine this with reset_trust_records(), or only check
2142 the caches on keys that are actually involved in the web of
2143 trust. */
2144 keydb_rebuild_caches(0);
2146 start_time = make_timestamp ();
2147 next_expire = 0xffffffff; /* set next expire to the year 2106 */
2148 stored = new_key_hash_table ();
2149 used = new_key_hash_table ();
2150 full_trust = new_key_hash_table ();
2152 kdb = keydb_new (0);
2153 reset_trust_records();
2155 /* Fixme: Instead of always building a UTK list, we could just build it
2156 * here when needed */
2157 if (!utk_list)
2159 if (!opt.quiet)
2160 log_info (_("no ultimately trusted keys found\n"));
2161 goto leave;
2164 /* mark all UTKs as used and fully_trusted and set validity to
2165 ultimate */
2166 for (k=utk_list; k; k = k->next)
2168 KBNODE keyblock;
2169 PKT_public_key *pk;
2171 keyblock = get_pubkeyblock (k->kid);
2172 if (!keyblock)
2174 log_error (_("public key of ultimately"
2175 " trusted key %s not found\n"), keystr(k->kid));
2176 continue;
2178 mark_keyblock_seen (used, keyblock);
2179 mark_keyblock_seen (stored, keyblock);
2180 mark_keyblock_seen (full_trust, keyblock);
2181 pk = keyblock->pkt->pkt.public_key;
2182 for (node=keyblock; node; node = node->next)
2184 if (node->pkt->pkttype == PKT_USER_ID)
2185 update_validity (pk, node->pkt->pkt.user_id, 0, TRUST_ULTIMATE);
2187 if ( pk->expiredate && pk->expiredate >= start_time
2188 && pk->expiredate < next_expire)
2189 next_expire = pk->expiredate;
2191 release_kbnode (keyblock);
2192 do_sync ();
2195 klist = utk_list;
2197 log_info(_("%d marginal(s) needed, %d complete(s) needed, %s trust model\n"),
2198 opt.marginals_needed,opt.completes_needed,trust_model_string());
2200 for (depth=0; depth < opt.max_cert_depth; depth++)
2202 int valids=0,key_count;
2203 /* See whether we should assign ownertrust values to the keys in
2204 klist. */
2205 ot_unknown = ot_undefined = ot_never = 0;
2206 ot_marginal = ot_full = ot_ultimate = 0;
2207 for (k=klist; k; k = k->next)
2209 int min=0;
2211 /* 120 and 60 are as per RFC2440 */
2212 if(k->trust_value>=120)
2213 min=TRUST_FULLY;
2214 else if(k->trust_value>=60)
2215 min=TRUST_MARGINAL;
2217 if(min!=k->min_ownertrust)
2218 update_min_ownertrust(k->kid,min);
2220 if (interactive && k->ownertrust == TRUST_UNKNOWN)
2222 k->ownertrust = ask_ownertrust (k->kid,min);
2224 if (k->ownertrust == -1)
2226 quit=1;
2227 goto leave;
2231 /* This can happen during transition from an old trustdb
2232 before trust sigs. It can also happen if a user uses two
2233 different versions of GnuPG or changes the --trust-model
2234 setting. */
2235 if(k->ownertrust<min)
2237 if(DBG_TRUST)
2238 log_debug("key %08lX%08lX:"
2239 " overriding ownertrust `%s' with `%s'\n",
2240 (ulong)k->kid[0],(ulong)k->kid[1],
2241 trust_value_to_string(k->ownertrust),
2242 trust_value_to_string(min));
2244 k->ownertrust=min;
2247 if (k->ownertrust == TRUST_UNKNOWN)
2248 ot_unknown++;
2249 else if (k->ownertrust == TRUST_UNDEFINED)
2250 ot_undefined++;
2251 else if (k->ownertrust == TRUST_NEVER)
2252 ot_never++;
2253 else if (k->ownertrust == TRUST_MARGINAL)
2254 ot_marginal++;
2255 else if (k->ownertrust == TRUST_FULLY)
2256 ot_full++;
2257 else if (k->ownertrust == TRUST_ULTIMATE)
2258 ot_ultimate++;
2260 valids++;
2263 /* Find all keys which are signed by a key in kdlist */
2264 keys = validate_key_list (kdb, full_trust, klist,
2265 start_time, &next_expire);
2266 if (!keys)
2268 log_error ("validate_key_list failed\n");
2269 rc = G10ERR_GENERAL;
2270 goto leave;
2273 for (key_count=0, kar=keys; kar->keyblock; kar++, key_count++)
2276 /* Store the calculated valididation status somewhere */
2277 if (opt.verbose > 1)
2278 dump_key_array (depth, keys);
2280 for (kar=keys; kar->keyblock; kar++)
2281 store_validation_status (depth, kar->keyblock, stored);
2283 log_info (_("depth: %d valid: %3d signed: %3d"
2284 " trust: %d-, %dq, %dn, %dm, %df, %du\n"),
2285 depth, valids, key_count, ot_unknown, ot_undefined,
2286 ot_never, ot_marginal, ot_full, ot_ultimate );
2288 /* Build a new kdlist from all fully valid keys in KEYS */
2289 if (klist != utk_list)
2290 release_key_items (klist);
2291 klist = NULL;
2292 for (kar=keys; kar->keyblock; kar++)
2294 for (node=kar->keyblock; node; node = node->next)
2296 if (node->pkt->pkttype == PKT_USER_ID && (node->flag & 4))
2298 u32 kid[2];
2300 /* have we used this key already? */
2301 keyid_from_pk (kar->keyblock->pkt->pkt.public_key, kid);
2302 if(test_key_hash_table(used,kid)==0)
2304 /* Normally we add both the primary and subkey
2305 ids to the hash via mark_keyblock_seen, but
2306 since we aren't using this hash as a skipfnc,
2307 that doesn't matter here. */
2308 add_key_hash_table (used,kid);
2309 k = new_key_item ();
2310 k->kid[0]=kid[0];
2311 k->kid[1]=kid[1];
2312 k->ownertrust =
2313 (get_ownertrust (kar->keyblock->pkt->pkt.public_key)
2314 & TRUST_MASK);
2315 k->min_ownertrust =
2316 get_min_ownertrust(kar->keyblock->pkt->pkt.public_key);
2317 k->trust_depth=
2318 kar->keyblock->pkt->pkt.public_key->trust_depth;
2319 k->trust_value=
2320 kar->keyblock->pkt->pkt.public_key->trust_value;
2321 if(kar->keyblock->pkt->pkt.public_key->trust_regexp)
2322 k->trust_regexp=
2323 xstrdup(kar->keyblock->pkt->
2324 pkt.public_key->trust_regexp);
2325 k->next = klist;
2326 klist = k;
2327 break;
2332 release_key_array (keys);
2333 keys = NULL;
2334 if (!klist)
2335 break; /* no need to dive in deeper */
2338 leave:
2339 keydb_release (kdb);
2340 release_key_array (keys);
2341 release_key_items (klist);
2342 release_key_hash_table (full_trust);
2343 release_key_hash_table (used);
2344 release_key_hash_table (stored);
2345 if (!rc && !quit) /* mark trustDB as checked */
2347 if (next_expire == 0xffffffff || next_expire < start_time )
2348 tdbio_write_nextcheck (0);
2349 else
2351 tdbio_write_nextcheck (next_expire);
2352 log_info (_("next trustdb check due at %s\n"),
2353 strtimestamp (next_expire));
2356 if(tdbio_update_version_record()!=0)
2358 log_error(_("unable to update trustdb version record: "
2359 "write failed: %s\n"), g10_errstr(rc));
2360 tdbio_invalid();
2363 do_sync ();
2364 pending_check_trustdb = 0;
2367 return rc;