2007-07-05 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / trustdb.c
blob4630967116db7bb863bab4a44d443c2907f72e2f
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 3 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, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <assert.h>
27 #ifndef DISABLE_REGEX
28 #include <sys/types.h>
29 #ifdef USE_INTERNAL_REGEX
30 #include "_regex.h"
31 #else
32 #include <regex.h>
33 #endif
34 #endif /* !DISABLE_REGEX */
36 #include "gpg.h"
37 #include "errors.h"
38 #include "iobuf.h"
39 #include "keydb.h"
40 #include "util.h"
41 #include "options.h"
42 #include "packet.h"
43 #include "main.h"
44 #include "i18n.h"
45 #include "tdbio.h"
46 #include "trustdb.h"
50 * A structure to store key identification as well as some stuff needed
51 * for validation
53 struct key_item {
54 struct key_item *next;
55 unsigned int ownertrust,min_ownertrust;
56 byte trust_depth;
57 byte trust_value;
58 char *trust_regexp;
59 u32 kid[2];
63 typedef struct key_item **KeyHashTable; /* see new_key_hash_table() */
66 * Structure to keep track of keys, this is used as an array wherre
67 * the item right after the last one has a keyblock set to NULL.
68 * Maybe we can drop this thing and replace it by key_item
70 struct key_array {
71 KBNODE keyblock;
75 /* control information for the trust DB */
76 static struct {
77 int init;
78 int level;
79 char *dbname;
80 } trustdb_args;
82 /* some globals */
83 static struct key_item *user_utk_list; /* temp. used to store --trusted-keys */
84 static struct key_item *utk_list; /* all ultimately trusted keys */
86 static int pending_check_trustdb;
88 static int validate_keys (int interactive);
91 /**********************************************
92 ************* some helpers *******************
93 **********************************************/
95 static struct key_item *
96 new_key_item (void)
98 struct key_item *k;
100 k = xmalloc_clear (sizeof *k);
101 return k;
104 static void
105 release_key_items (struct key_item *k)
107 struct key_item *k2;
109 for (; k; k = k2)
111 k2 = k->next;
112 xfree (k->trust_regexp);
113 xfree (k);
118 * For fast keylook up we need a hash table. Each byte of a KeyIDs
119 * should be distributed equally over the 256 possible values (except
120 * for v3 keyIDs but we consider them as not important here). So we
121 * can just use 10 bits to index a table of 1024 key items.
122 * Possible optimization: Don not use key_items but other hash_table when the
123 * duplicates lists gets too large.
125 static KeyHashTable
126 new_key_hash_table (void)
128 struct key_item **tbl;
130 tbl = xmalloc_clear (1024 * sizeof *tbl);
131 return tbl;
134 static void
135 release_key_hash_table (KeyHashTable tbl)
137 int i;
139 if (!tbl)
140 return;
141 for (i=0; i < 1024; i++)
142 release_key_items (tbl[i]);
143 xfree (tbl);
147 * Returns: True if the keyID is in the given hash table
149 static int
150 test_key_hash_table (KeyHashTable tbl, u32 *kid)
152 struct key_item *k;
154 for (k = tbl[(kid[1] & 0x03ff)]; k; k = k->next)
155 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
156 return 1;
157 return 0;
161 * Add a new key to the hash table. The key is identified by its key ID.
163 static void
164 add_key_hash_table (KeyHashTable tbl, u32 *kid)
166 struct key_item *k, *kk;
168 for (k = tbl[(kid[1] & 0x03ff)]; k; k = k->next)
169 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
170 return; /* already in table */
172 kk = new_key_item ();
173 kk->kid[0] = kid[0];
174 kk->kid[1] = kid[1];
175 kk->next = tbl[(kid[1] & 0x03ff)];
176 tbl[(kid[1] & 0x03ff)] = kk;
180 * Release a key_array
182 static void
183 release_key_array ( struct key_array *keys )
185 struct key_array *k;
187 if (keys) {
188 for (k=keys; k->keyblock; k++)
189 release_kbnode (k->keyblock);
190 xfree (keys);
195 /*********************************************
196 ********** Initialization *****************
197 *********************************************/
202 * Used to register extra ultimately trusted keys - this has to be done
203 * before initializing the validation module.
204 * FIXME: Should be replaced by a function to add those keys to the trustdb.
206 void
207 register_trusted_keyid(u32 *keyid)
209 struct key_item *k;
211 k = new_key_item ();
212 k->kid[0] = keyid[0];
213 k->kid[1] = keyid[1];
214 k->next = user_utk_list;
215 user_utk_list = k;
218 void
219 register_trusted_key( const char *string )
221 KEYDB_SEARCH_DESC desc;
223 if (classify_user_id (string, &desc) != KEYDB_SEARCH_MODE_LONG_KID )
225 log_error(_("`%s' is not a valid long keyID\n"), string );
226 return;
229 register_trusted_keyid(desc.u.kid);
233 * Helper to add a key to the global list of ultimately trusted keys.
234 * Retruns: true = inserted, false = already in in list.
236 static int
237 add_utk (u32 *kid)
239 struct key_item *k;
241 for (k = utk_list; k; k = k->next)
243 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
245 return 0;
249 k = new_key_item ();
250 k->kid[0] = kid[0];
251 k->kid[1] = kid[1];
252 k->ownertrust = TRUST_ULTIMATE;
253 k->next = utk_list;
254 utk_list = k;
255 if( opt.verbose > 1 )
256 log_info(_("key %s: accepted as trusted key\n"), keystr(kid));
257 return 1;
261 /****************
262 * Verify that all our secret keys are usable and put them into the utk_list.
264 static void
265 verify_own_keys(void)
267 TRUSTREC rec;
268 ulong recnum;
269 int rc;
270 struct key_item *k;
272 if (utk_list)
273 return;
275 /* scan the trustdb to find all ultimately trusted keys */
276 for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
278 if ( rec.rectype == RECTYPE_TRUST
279 && (rec.r.trust.ownertrust & TRUST_MASK) == TRUST_ULTIMATE)
281 byte *fpr = rec.r.trust.fingerprint;
282 int fprlen;
283 u32 kid[2];
285 /* Problem: We do only use fingerprints in the trustdb but
286 * we need the keyID here to indetify the key; we can only
287 * use that ugly hack to distinguish between 16 and 20
288 * butes fpr - it does not work always so we better change
289 * the whole validation code to only work with
290 * fingerprints */
291 fprlen = (!fpr[16] && !fpr[17] && !fpr[18] && !fpr[19])? 16:20;
292 keyid_from_fingerprint (fpr, fprlen, kid);
293 if (!add_utk (kid))
294 log_info(_("key %s occurs more than once in the trustdb\n"),
295 keystr(kid));
299 /* Put any --trusted-key keys into the trustdb */
300 for (k = user_utk_list; k; k = k->next)
302 if ( add_utk (k->kid) )
303 { /* not yet in trustDB as ultimately trusted */
304 PKT_public_key pk;
306 memset (&pk, 0, sizeof pk);
307 rc = get_pubkey (&pk, k->kid);
308 if (rc)
309 log_info(_("key %s: no public key for trusted key - skipped\n"),
310 keystr(k->kid));
311 else
313 update_ownertrust (&pk,
314 ((get_ownertrust (&pk) & ~TRUST_MASK)
315 | TRUST_ULTIMATE ));
316 release_public_key_parts (&pk);
319 log_info (_("key %s marked as ultimately trusted\n"),keystr(k->kid));
323 /* release the helper table table */
324 release_key_items (user_utk_list);
325 user_utk_list = NULL;
326 return;
330 /*********************************************
331 *********** TrustDB stuff *******************
332 *********************************************/
335 * Read a record but die if it does not exist
337 static void
338 read_record (ulong recno, TRUSTREC *rec, int rectype )
340 int rc = tdbio_read_record (recno, rec, rectype);
341 if (rc)
343 log_error(_("trust record %lu, req type %d: read failed: %s\n"),
344 recno, rec->rectype, g10_errstr(rc) );
345 tdbio_invalid();
347 if (rectype != rec->rectype)
349 log_error(_("trust record %lu is not of requested type %d\n"),
350 rec->recnum, rectype);
351 tdbio_invalid();
356 * Write a record and die on error
358 static void
359 write_record (TRUSTREC *rec)
361 int rc = tdbio_write_record (rec);
362 if (rc)
364 log_error(_("trust record %lu, type %d: write failed: %s\n"),
365 rec->recnum, rec->rectype, g10_errstr(rc) );
366 tdbio_invalid();
371 * sync the TrustDb and die on error
373 static void
374 do_sync(void)
376 int rc = tdbio_sync ();
377 if(rc)
379 log_error (_("trustdb: sync failed: %s\n"), g10_errstr(rc) );
380 g10_exit(2);
384 static const char *
385 trust_model_string(void)
387 switch(opt.trust_model)
389 case TM_CLASSIC: return "classic";
390 case TM_PGP: return "PGP";
391 case TM_EXTERNAL: return "external";
392 case TM_ALWAYS: return "always";
393 case TM_DIRECT: return "direct";
394 default: return "unknown";
398 /****************
399 * Perform some checks over the trustdb
400 * level 0: only open the db
401 * 1: used for initial program startup
404 setup_trustdb( int level, const char *dbname )
406 /* just store the args */
407 if( trustdb_args.init )
408 return 0;
409 trustdb_args.level = level;
410 trustdb_args.dbname = dbname? xstrdup(dbname): NULL;
411 return 0;
414 void
415 init_trustdb()
417 int level = trustdb_args.level;
418 const char* dbname = trustdb_args.dbname;
420 if( trustdb_args.init )
421 return;
423 trustdb_args.init = 1;
425 if(level==0 || level==1)
427 int rc = tdbio_set_dbname( dbname, !!level );
428 if( rc )
429 log_fatal("can't init trustdb: %s\n", g10_errstr(rc) );
431 else
432 BUG();
434 if(opt.trust_model==TM_AUTO)
436 /* Try and set the trust model off of whatever the trustdb says
437 it is. */
438 opt.trust_model=tdbio_read_model();
440 /* Sanity check this ;) */
441 if(opt.trust_model!=TM_CLASSIC
442 && opt.trust_model!=TM_PGP
443 && opt.trust_model!=TM_EXTERNAL)
445 log_info(_("unable to use unknown trust model (%d) - "
446 "assuming %s trust model\n"),opt.trust_model,"PGP");
447 opt.trust_model=TM_PGP;
450 if(opt.verbose)
451 log_info(_("using %s trust model\n"),trust_model_string());
454 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
456 /* Verify the list of ultimately trusted keys and move the
457 --trusted-keys list there as well. */
458 if(level==1)
459 verify_own_keys();
461 if(!tdbio_db_matches_options())
462 pending_check_trustdb=1;
467 /***********************************************
468 ************* Print helpers ****************
469 ***********************************************/
471 /****************
472 * This function returns a letter for a trustvalue Trust flags
473 * are ignore.
475 static int
476 trust_letter (unsigned int value)
478 switch( (value & TRUST_MASK) )
480 case TRUST_UNKNOWN: return '-';
481 case TRUST_EXPIRED: return 'e';
482 case TRUST_UNDEFINED: return 'q';
483 case TRUST_NEVER: return 'n';
484 case TRUST_MARGINAL: return 'm';
485 case TRUST_FULLY: return 'f';
486 case TRUST_ULTIMATE: return 'u';
487 default: return '?';
491 /* NOTE TO TRANSLATOR: these strings are similar to those in
492 trust_value_to_string(), but are a fixed length. This is needed to
493 make attractive information listings where columns line up
494 properly. The value "10" should be the length of the strings you
495 choose to translate to. This is the length in printable columns.
496 It gets passed to atoi() so everything after the number is
497 essentially a comment and need not be translated. Either key and
498 uid are both NULL, or neither are NULL. */
499 const char *
500 uid_trust_string_fixed(PKT_public_key *key,PKT_user_id *uid)
502 if(!key && !uid)
503 return _("10 translator see trustdb.c:uid_trust_string_fixed");
504 else if(uid->is_revoked || (key && key->is_revoked))
505 return _("[ revoked]");
506 else if(uid->is_expired)
507 return _("[ expired]");
508 else if(key)
509 switch(get_validity(key,uid)&TRUST_MASK)
511 case TRUST_UNKNOWN: return _("[ unknown]");
512 case TRUST_EXPIRED: return _("[ expired]");
513 case TRUST_UNDEFINED: return _("[ undef ]");
514 case TRUST_MARGINAL: return _("[marginal]");
515 case TRUST_FULLY: return _("[ full ]");
516 case TRUST_ULTIMATE: return _("[ultimate]");
519 return "err";
522 /* The strings here are similar to those in
523 pkclist.c:do_edit_ownertrust() */
524 const char *
525 trust_value_to_string (unsigned int value)
527 switch( (value & TRUST_MASK) )
529 case TRUST_UNKNOWN: return _("unknown");
530 case TRUST_EXPIRED: return _("expired");
531 case TRUST_UNDEFINED: return _("undefined");
532 case TRUST_NEVER: return _("never");
533 case TRUST_MARGINAL: return _("marginal");
534 case TRUST_FULLY: return _("full");
535 case TRUST_ULTIMATE: return _("ultimate");
536 default: return "err";
541 string_to_trust_value (const char *str)
543 if(ascii_strcasecmp(str,"undefined")==0)
544 return TRUST_UNDEFINED;
545 else if(ascii_strcasecmp(str,"never")==0)
546 return TRUST_NEVER;
547 else if(ascii_strcasecmp(str,"marginal")==0)
548 return TRUST_MARGINAL;
549 else if(ascii_strcasecmp(str,"full")==0)
550 return TRUST_FULLY;
551 else if(ascii_strcasecmp(str,"ultimate")==0)
552 return TRUST_ULTIMATE;
553 else
554 return -1;
557 /****************
558 * Recreate the WoT but do not ask for new ownertrusts. Special
559 * feature: In batch mode and without a forced yes, this is only done
560 * when a check is due. This can be used to run the check from a crontab
562 void
563 check_trustdb ()
565 init_trustdb();
566 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
568 if (opt.batch && !opt.answer_yes)
570 ulong scheduled;
572 scheduled = tdbio_read_nextcheck ();
573 if (!scheduled)
575 log_info (_("no need for a trustdb check\n"));
576 return;
579 if (scheduled > make_timestamp ())
581 log_info (_("next trustdb check due at %s\n"),
582 strtimestamp (scheduled));
583 return;
587 validate_keys (0);
589 else
590 log_info (_("no need for a trustdb check with `%s' trust model\n"),
591 trust_model_string());
596 * Recreate the WoT.
598 void
599 update_trustdb()
601 init_trustdb();
602 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
603 validate_keys (1);
604 else
605 log_info (_("no need for a trustdb update with `%s' trust model\n"),
606 trust_model_string());
609 void
610 revalidation_mark (void)
612 init_trustdb();
613 /* we simply set the time for the next check to 1 (far back in 1970)
614 * so that a --update-trustdb will be scheduled */
615 if (tdbio_write_nextcheck (1))
616 do_sync ();
617 pending_check_trustdb = 1;
621 trustdb_pending_check(void)
623 return pending_check_trustdb;
626 /* If the trustdb is dirty, and we're interactive, update it.
627 Otherwise, check it unless no-auto-check-trustdb is set. */
628 void
629 trustdb_check_or_update(void)
631 if(trustdb_pending_check())
633 if(opt.interactive)
634 update_trustdb();
635 else if(!opt.no_auto_check_trustdb)
636 check_trustdb();
640 void
641 read_trust_options(byte *trust_model,ulong *created,ulong *nextcheck,
642 byte *marginals,byte *completes,byte *cert_depth)
644 TRUSTREC opts;
646 init_trustdb();
648 read_record(0,&opts,RECTYPE_VER);
650 if(trust_model)
651 *trust_model=opts.r.ver.trust_model;
652 if(created)
653 *created=opts.r.ver.created;
654 if(nextcheck)
655 *nextcheck=opts.r.ver.nextcheck;
656 if(marginals)
657 *marginals=opts.r.ver.marginals;
658 if(completes)
659 *completes=opts.r.ver.completes;
660 if(cert_depth)
661 *cert_depth=opts.r.ver.cert_depth;
664 /***********************************************
665 *********** Ownertrust et al. ****************
666 ***********************************************/
668 static int
669 read_trust_record (PKT_public_key *pk, TRUSTREC *rec)
671 int rc;
673 init_trustdb();
674 rc = tdbio_search_trust_bypk (pk, rec);
675 if (rc == -1)
676 return -1; /* no record yet */
677 if (rc)
679 log_error ("trustdb: searching trust record failed: %s\n",
680 g10_errstr (rc));
681 return rc;
684 if (rec->rectype != RECTYPE_TRUST)
686 log_error ("trustdb: record %lu is not a trust record\n",
687 rec->recnum);
688 return G10ERR_TRUSTDB;
691 return 0;
694 /****************
695 * Return the assigned ownertrust value for the given public key.
696 * The key should be the primary key.
698 unsigned int
699 get_ownertrust ( PKT_public_key *pk)
701 TRUSTREC rec;
702 int rc;
704 rc = read_trust_record (pk, &rec);
705 if (rc == -1)
706 return TRUST_UNKNOWN; /* no record yet */
707 if (rc)
709 tdbio_invalid ();
710 return rc; /* actually never reached */
713 return rec.r.trust.ownertrust;
716 unsigned int
717 get_min_ownertrust (PKT_public_key *pk)
719 TRUSTREC rec;
720 int rc;
722 rc = read_trust_record (pk, &rec);
723 if (rc == -1)
724 return TRUST_UNKNOWN; /* no record yet */
725 if (rc)
727 tdbio_invalid ();
728 return rc; /* actually never reached */
731 return rec.r.trust.min_ownertrust;
735 * Same as get_ownertrust but this takes the minimum ownertrust value
736 * into into account, and will bump up the value as needed.
738 static int
739 get_ownertrust_with_min (PKT_public_key *pk)
741 unsigned int otrust,otrust_min;
743 otrust = (get_ownertrust (pk) & TRUST_MASK);
744 otrust_min = get_min_ownertrust (pk);
745 if(otrust<otrust_min)
747 /* If the trust that the user has set is less than the trust
748 that was calculated from a trust signature chain, use the
749 higher of the two. We do this here and not in
750 get_ownertrust since the underlying ownertrust should not
751 really be set - just the appearance of the ownertrust. */
753 otrust=otrust_min;
756 return otrust;
760 * Same as get_ownertrust but return a trust letter instead of an
761 * value. This takes the minimum ownertrust value into account.
764 get_ownertrust_info (PKT_public_key *pk)
766 return trust_letter(get_ownertrust_with_min(pk));
770 * Same as get_ownertrust but return a trust string instead of an
771 * value. This takes the minimum ownertrust value into account.
773 const char *
774 get_ownertrust_string (PKT_public_key *pk)
776 return trust_value_to_string(get_ownertrust_with_min(pk));
780 * Set the trust value of the given public key to the new value.
781 * The key should be a primary one.
783 void
784 update_ownertrust (PKT_public_key *pk, unsigned int new_trust )
786 TRUSTREC rec;
787 int rc;
789 rc = read_trust_record (pk, &rec);
790 if (!rc)
792 if (DBG_TRUST)
793 log_debug ("update ownertrust from %u to %u\n",
794 (unsigned int)rec.r.trust.ownertrust, new_trust );
795 if (rec.r.trust.ownertrust != new_trust)
797 rec.r.trust.ownertrust = new_trust;
798 write_record( &rec );
799 revalidation_mark ();
800 do_sync ();
803 else if (rc == -1)
804 { /* no record yet - create a new one */
805 size_t dummy;
807 if (DBG_TRUST)
808 log_debug ("insert ownertrust %u\n", new_trust );
810 memset (&rec, 0, sizeof rec);
811 rec.recnum = tdbio_new_recnum ();
812 rec.rectype = RECTYPE_TRUST;
813 fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
814 rec.r.trust.ownertrust = new_trust;
815 write_record (&rec);
816 revalidation_mark ();
817 do_sync ();
818 rc = 0;
820 else
822 tdbio_invalid ();
826 static void
827 update_min_ownertrust (u32 *kid, unsigned int new_trust )
829 PKT_public_key *pk;
830 TRUSTREC rec;
831 int rc;
833 pk = xmalloc_clear (sizeof *pk);
834 rc = get_pubkey (pk, kid);
835 if (rc)
837 log_error(_("public key %s not found: %s\n"),keystr(kid),g10_errstr(rc));
838 return;
841 rc = read_trust_record (pk, &rec);
842 if (!rc)
844 if (DBG_TRUST)
845 log_debug ("key %08lX%08lX: update min_ownertrust from %u to %u\n",
846 (ulong)kid[0],(ulong)kid[1],
847 (unsigned int)rec.r.trust.min_ownertrust,
848 new_trust );
849 if (rec.r.trust.min_ownertrust != new_trust)
851 rec.r.trust.min_ownertrust = new_trust;
852 write_record( &rec );
853 revalidation_mark ();
854 do_sync ();
857 else if (rc == -1)
858 { /* no record yet - create a new one */
859 size_t dummy;
861 if (DBG_TRUST)
862 log_debug ("insert min_ownertrust %u\n", new_trust );
864 memset (&rec, 0, sizeof rec);
865 rec.recnum = tdbio_new_recnum ();
866 rec.rectype = RECTYPE_TRUST;
867 fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
868 rec.r.trust.min_ownertrust = new_trust;
869 write_record (&rec);
870 revalidation_mark ();
871 do_sync ();
872 rc = 0;
874 else
876 tdbio_invalid ();
880 /* Clear the ownertrust and min_ownertrust values. Return true if a
881 change actually happened. */
883 clear_ownertrusts (PKT_public_key *pk)
885 TRUSTREC rec;
886 int rc;
888 rc = read_trust_record (pk, &rec);
889 if (!rc)
891 if (DBG_TRUST)
893 log_debug ("clearing ownertrust (old value %u)\n",
894 (unsigned int)rec.r.trust.ownertrust);
895 log_debug ("clearing min_ownertrust (old value %u)\n",
896 (unsigned int)rec.r.trust.min_ownertrust);
898 if (rec.r.trust.ownertrust || rec.r.trust.min_ownertrust)
900 rec.r.trust.ownertrust = 0;
901 rec.r.trust.min_ownertrust = 0;
902 write_record( &rec );
903 revalidation_mark ();
904 do_sync ();
905 return 1;
908 else if (rc != -1)
910 tdbio_invalid ();
912 return 0;
916 * Note: Caller has to do a sync
918 static void
919 update_validity (PKT_public_key *pk, PKT_user_id *uid,
920 int depth, int validity)
922 TRUSTREC trec, vrec;
923 int rc;
924 ulong recno;
926 namehash_from_uid(uid);
928 rc = read_trust_record (pk, &trec);
929 if (rc && rc != -1)
931 tdbio_invalid ();
932 return;
934 if (rc == -1) /* no record yet - create a new one */
936 size_t dummy;
938 rc = 0;
939 memset (&trec, 0, sizeof trec);
940 trec.recnum = tdbio_new_recnum ();
941 trec.rectype = RECTYPE_TRUST;
942 fingerprint_from_pk (pk, trec.r.trust.fingerprint, &dummy);
943 trec.r.trust.ownertrust = 0;
946 /* locate an existing one */
947 recno = trec.r.trust.validlist;
948 while (recno)
950 read_record (recno, &vrec, RECTYPE_VALID);
951 if ( !memcmp (vrec.r.valid.namehash, uid->namehash, 20) )
952 break;
953 recno = vrec.r.valid.next;
956 if (!recno) /* insert a new validity record */
958 memset (&vrec, 0, sizeof vrec);
959 vrec.recnum = tdbio_new_recnum ();
960 vrec.rectype = RECTYPE_VALID;
961 memcpy (vrec.r.valid.namehash, uid->namehash, 20);
962 vrec.r.valid.next = trec.r.trust.validlist;
963 trec.r.trust.validlist = vrec.recnum;
965 vrec.r.valid.validity = validity;
966 vrec.r.valid.full_count = uid->help_full_count;
967 vrec.r.valid.marginal_count = uid->help_marginal_count;
968 write_record (&vrec);
969 trec.r.trust.depth = depth;
970 write_record (&trec);
974 /***********************************************
975 ********* Query trustdb values **************
976 ***********************************************/
978 /* Return true if key is disabled */
980 cache_disabled_value(PKT_public_key *pk)
982 int rc;
983 TRUSTREC trec;
984 int disabled=0;
986 if(pk->is_disabled)
987 return (pk->is_disabled==2);
989 init_trustdb();
991 rc = read_trust_record (pk, &trec);
992 if (rc && rc != -1)
994 tdbio_invalid ();
995 goto leave;
997 if (rc == -1) /* no record found, so assume not disabled */
998 goto leave;
1000 if(trec.r.trust.ownertrust & TRUST_FLAG_DISABLED)
1001 disabled=1;
1003 /* Cache it for later so we don't need to look at the trustdb every
1004 time */
1005 if(disabled)
1006 pk->is_disabled=2;
1007 else
1008 pk->is_disabled=1;
1010 leave:
1011 return disabled;
1014 void
1015 check_trustdb_stale(void)
1017 static int did_nextcheck=0;
1019 init_trustdb ();
1020 if (!did_nextcheck
1021 && (opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC))
1023 ulong scheduled;
1025 did_nextcheck = 1;
1026 scheduled = tdbio_read_nextcheck ();
1027 if (scheduled && scheduled <= make_timestamp ())
1029 if (opt.no_auto_check_trustdb)
1031 pending_check_trustdb = 1;
1032 log_info (_("please do a --check-trustdb\n"));
1034 else
1036 log_info (_("checking the trustdb\n"));
1037 validate_keys (0);
1044 * Return the validity information for PK. If the namehash is not
1045 * NULL, the validity of the corresponsing user ID is returned,
1046 * otherwise, a reasonable value for the entire key is returned.
1048 unsigned int
1049 get_validity (PKT_public_key *pk, PKT_user_id *uid)
1051 TRUSTREC trec, vrec;
1052 int rc;
1053 ulong recno;
1054 unsigned int validity;
1055 u32 kid[2];
1056 PKT_public_key *main_pk;
1058 if(uid)
1059 namehash_from_uid(uid);
1061 init_trustdb ();
1062 check_trustdb_stale();
1064 keyid_from_pk (pk, kid);
1065 if (pk->main_keyid[0] != kid[0] || pk->main_keyid[1] != kid[1])
1066 { /* this is a subkey - get the mainkey */
1067 main_pk = xmalloc_clear (sizeof *main_pk);
1068 rc = get_pubkey (main_pk, pk->main_keyid);
1069 if (rc)
1071 char *tempkeystr=xstrdup(keystr(pk->main_keyid));
1072 log_error ("error getting main key %s of subkey %s: %s\n",
1073 tempkeystr, keystr(kid), g10_errstr(rc));
1074 xfree(tempkeystr);
1075 validity = TRUST_UNKNOWN;
1076 goto leave;
1079 else
1080 main_pk = pk;
1082 if(opt.trust_model==TM_DIRECT)
1084 /* Note that this happens BEFORE any user ID stuff is checked.
1085 The direct trust model applies to keys as a whole. */
1086 validity=get_ownertrust(main_pk);
1087 goto leave;
1090 rc = read_trust_record (main_pk, &trec);
1091 if (rc && rc != -1)
1093 tdbio_invalid ();
1094 return 0;
1096 if (rc == -1) /* no record found */
1098 validity = TRUST_UNKNOWN;
1099 goto leave;
1102 /* loop over all user IDs */
1103 recno = trec.r.trust.validlist;
1104 validity = 0;
1105 while (recno)
1107 read_record (recno, &vrec, RECTYPE_VALID);
1109 if(uid)
1111 /* If a user ID is given we return the validity for that
1112 user ID ONLY. If the namehash is not found, then there
1113 is no validity at all (i.e. the user ID wasn't
1114 signed). */
1115 if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1117 validity=(vrec.r.valid.validity & TRUST_MASK);
1118 break;
1121 else
1123 /* If no namehash is given, we take the maximum validity
1124 over all user IDs */
1125 if ( validity < (vrec.r.valid.validity & TRUST_MASK) )
1126 validity = (vrec.r.valid.validity & TRUST_MASK);
1129 recno = vrec.r.valid.next;
1132 if ( (trec.r.trust.ownertrust & TRUST_FLAG_DISABLED) )
1134 validity |= TRUST_FLAG_DISABLED;
1135 pk->is_disabled=2;
1137 else
1138 pk->is_disabled=1;
1140 leave:
1141 /* set some flags direct from the key */
1142 if (main_pk->is_revoked)
1143 validity |= TRUST_FLAG_REVOKED;
1144 if (main_pk != pk && pk->is_revoked)
1145 validity |= TRUST_FLAG_SUB_REVOKED;
1146 /* Note: expiration is a trust value and not a flag - don't know why
1147 * I initially designed it that way */
1148 if (main_pk->has_expired || pk->has_expired)
1149 validity = (validity & ~TRUST_MASK) | TRUST_EXPIRED;
1151 if (pending_check_trustdb)
1152 validity |= TRUST_FLAG_PENDING_CHECK;
1154 if (main_pk != pk)
1155 free_public_key (main_pk);
1156 return validity;
1160 get_validity_info (PKT_public_key *pk, PKT_user_id *uid)
1162 int trustlevel;
1164 trustlevel = get_validity (pk, uid);
1165 if( trustlevel & TRUST_FLAG_REVOKED )
1166 return 'r';
1167 return trust_letter ( trustlevel );
1170 const char *
1171 get_validity_string (PKT_public_key *pk, PKT_user_id *uid)
1173 int trustlevel;
1175 trustlevel = get_validity (pk, uid);
1176 if( trustlevel & TRUST_FLAG_REVOKED )
1177 return _("revoked");
1178 return trust_value_to_string(trustlevel);
1181 static void
1182 get_validity_counts (PKT_public_key *pk, PKT_user_id *uid)
1184 TRUSTREC trec, vrec;
1185 ulong recno;
1187 if(pk==NULL || uid==NULL)
1188 BUG();
1190 namehash_from_uid(uid);
1192 uid->help_marginal_count=uid->help_full_count=0;
1194 init_trustdb ();
1196 if(read_trust_record (pk, &trec)!=0)
1197 return;
1199 /* loop over all user IDs */
1200 recno = trec.r.trust.validlist;
1201 while (recno)
1203 read_record (recno, &vrec, RECTYPE_VALID);
1205 if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1207 uid->help_marginal_count=vrec.r.valid.marginal_count;
1208 uid->help_full_count=vrec.r.valid.full_count;
1209 /* printf("Fetched marginal %d, full %d\n",uid->help_marginal_count,uid->help_full_count); */
1210 break;
1213 recno = vrec.r.valid.next;
1217 void
1218 list_trust_path( const char *username )
1222 /****************
1223 * Enumerate all keys, which are needed to build all trust paths for
1224 * the given key. This function does not return the key itself or
1225 * the ultimate key (the last point in cerificate chain). Only
1226 * certificate chains which ends up at an ultimately trusted key
1227 * are listed. If ownertrust or validity is not NULL, the corresponding
1228 * value for the returned LID is also returned in these variable(s).
1230 * 1) create a void pointer and initialize it to NULL
1231 * 2) pass this void pointer by reference to this function.
1232 * Set lid to the key you want to enumerate and pass it by reference.
1233 * 3) call this function as long as it does not return -1
1234 * to indicate EOF. LID does contain the next key used to build the web
1235 * 4) Always call this function a last time with LID set to NULL,
1236 * so that it can free its context.
1238 * Returns: -1 on EOF or the level of the returned LID
1241 enum_cert_paths( void **context, ulong *lid,
1242 unsigned *ownertrust, unsigned *validity )
1244 return -1;
1248 /****************
1249 * Print the current path
1251 void
1252 enum_cert_paths_print( void **context, FILE *fp,
1253 int refresh, ulong selected_lid )
1255 return;
1260 /****************************************
1261 *********** NEW NEW NEW ****************
1262 ****************************************/
1264 static int
1265 ask_ownertrust (u32 *kid,int minimum)
1267 PKT_public_key *pk;
1268 int rc;
1269 int ot;
1271 pk = xmalloc_clear (sizeof *pk);
1272 rc = get_pubkey (pk, kid);
1273 if (rc)
1275 log_error (_("public key %s not found: %s\n"),
1276 keystr(kid), g10_errstr(rc) );
1277 return TRUST_UNKNOWN;
1280 if(opt.force_ownertrust)
1282 log_info("force trust for key %s to %s\n",
1283 keystr(kid),trust_value_to_string(opt.force_ownertrust));
1284 update_ownertrust(pk,opt.force_ownertrust);
1285 ot=opt.force_ownertrust;
1287 else
1289 ot=edit_ownertrust(pk,0);
1290 if(ot>0)
1291 ot = get_ownertrust (pk);
1292 else if(ot==0)
1293 ot = minimum?minimum:TRUST_UNDEFINED;
1294 else
1295 ot = -1; /* quit */
1298 free_public_key( pk );
1300 return ot;
1304 static void
1305 mark_keyblock_seen (KeyHashTable tbl, KBNODE node)
1307 for ( ;node; node = node->next )
1308 if (node->pkt->pkttype == PKT_PUBLIC_KEY
1309 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1311 u32 aki[2];
1313 keyid_from_pk (node->pkt->pkt.public_key, aki);
1314 add_key_hash_table (tbl, aki);
1319 static void
1320 dump_key_array (int depth, struct key_array *keys)
1322 struct key_array *kar;
1324 for (kar=keys; kar->keyblock; kar++)
1326 KBNODE node = kar->keyblock;
1327 u32 kid[2];
1329 keyid_from_pk(node->pkt->pkt.public_key, kid);
1330 printf ("%d:%08lX%08lX:K::%c::::\n",
1331 depth, (ulong)kid[0], (ulong)kid[1], '?');
1333 for (; node; node = node->next)
1335 if (node->pkt->pkttype == PKT_USER_ID)
1337 int len = node->pkt->pkt.user_id->len;
1339 if (len > 30)
1340 len = 30;
1341 printf ("%d:%08lX%08lX:U:::%c:::",
1342 depth, (ulong)kid[0], (ulong)kid[1],
1343 (node->flag & 4)? 'f':
1344 (node->flag & 2)? 'm':
1345 (node->flag & 1)? 'q':'-');
1346 print_string (stdout, node->pkt->pkt.user_id->name, len, ':');
1347 putchar (':');
1348 putchar ('\n');
1355 static void
1356 store_validation_status (int depth, KBNODE keyblock, KeyHashTable stored)
1358 KBNODE node;
1359 int status;
1360 int any = 0;
1362 for (node=keyblock; node; node = node->next)
1364 if (node->pkt->pkttype == PKT_USER_ID)
1366 PKT_user_id *uid = node->pkt->pkt.user_id;
1367 if (node->flag & 4)
1368 status = TRUST_FULLY;
1369 else if (node->flag & 2)
1370 status = TRUST_MARGINAL;
1371 else if (node->flag & 1)
1372 status = TRUST_UNDEFINED;
1373 else
1374 status = 0;
1376 if (status)
1378 update_validity (keyblock->pkt->pkt.public_key,
1379 uid, depth, status);
1381 mark_keyblock_seen(stored,keyblock);
1383 any = 1;
1388 if (any)
1389 do_sync ();
1393 * check whether the signature sig is in the klist k
1395 static struct key_item *
1396 is_in_klist (struct key_item *k, PKT_signature *sig)
1398 for (; k; k = k->next)
1400 if (k->kid[0] == sig->keyid[0] && k->kid[1] == sig->keyid[1])
1401 return k;
1403 return NULL;
1407 * Mark the signature of the given UID which are used to certify it.
1408 * To do this, we first revmove all signatures which are not valid and
1409 * from the remain ones we look for the latest one. If this is not a
1410 * certification revocation signature we mark the signature by setting
1411 * node flag bit 8. Revocations are marked with flag 11, and sigs
1412 * from unavailable keys are marked with flag 12. Note that flag bits
1413 * 9 and 10 are used for internal purposes.
1415 static void
1416 mark_usable_uid_certs (KBNODE keyblock, KBNODE uidnode,
1417 u32 *main_kid, struct key_item *klist,
1418 u32 curtime, u32 *next_expire)
1420 KBNODE node;
1421 PKT_signature *sig;
1423 /* first check all signatures */
1424 for (node=uidnode->next; node; node = node->next)
1426 int rc;
1428 node->flag &= ~(1<<8 | 1<<9 | 1<<10 | 1<<11 | 1<<12);
1429 if (node->pkt->pkttype == PKT_USER_ID
1430 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1431 break; /* ready */
1432 if (node->pkt->pkttype != PKT_SIGNATURE)
1433 continue;
1434 sig = node->pkt->pkt.signature;
1435 if (main_kid
1436 && sig->keyid[0] == main_kid[0] && sig->keyid[1] == main_kid[1])
1437 continue; /* ignore self-signatures if we pass in a main_kid */
1438 if (!IS_UID_SIG(sig) && !IS_UID_REV(sig))
1439 continue; /* we only look at these signature classes */
1440 if(sig->sig_class>=0x11 && sig->sig_class<=0x13 &&
1441 sig->sig_class-0x10<opt.min_cert_level)
1442 continue; /* treat anything under our min_cert_level as an
1443 invalid signature */
1444 if (klist && !is_in_klist (klist, sig))
1445 continue; /* no need to check it then */
1446 if ((rc=check_key_signature (keyblock, node, NULL)))
1448 /* we ignore anything that won't verify, but tag the
1449 no_pubkey case */
1450 if(rc==G10ERR_NO_PUBKEY)
1451 node->flag |= 1<<12;
1452 continue;
1454 node->flag |= 1<<9;
1456 /* reset the remaining flags */
1457 for (; node; node = node->next)
1458 node->flag &= ~(1<<8 | 1<<9 | 1<<10 | 1<<11 | 1<<12);
1460 /* kbnode flag usage: bit 9 is here set for signatures to consider,
1461 * bit 10 will be set by the loop to keep track of keyIDs already
1462 * processed, bit 8 will be set for the usable signatures, and bit
1463 * 11 will be set for usable revocations. */
1465 /* for each cert figure out the latest valid one */
1466 for (node=uidnode->next; node; node = node->next)
1468 KBNODE n, signode;
1469 u32 kid[2];
1470 u32 sigdate;
1472 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1473 break;
1474 if ( !(node->flag & (1<<9)) )
1475 continue; /* not a node to look at */
1476 if ( (node->flag & (1<<10)) )
1477 continue; /* signature with a keyID already processed */
1478 node->flag |= (1<<10); /* mark this node as processed */
1479 sig = node->pkt->pkt.signature;
1480 signode = node;
1481 sigdate = sig->timestamp;
1482 kid[0] = sig->keyid[0]; kid[1] = sig->keyid[1];
1484 /* Now find the latest and greatest signature */
1485 for (n=uidnode->next; n; n = n->next)
1487 if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1488 break;
1489 if ( !(n->flag & (1<<9)) )
1490 continue;
1491 if ( (n->flag & (1<<10)) )
1492 continue; /* shortcut already processed signatures */
1493 sig = n->pkt->pkt.signature;
1494 if (kid[0] != sig->keyid[0] || kid[1] != sig->keyid[1])
1495 continue;
1496 n->flag |= (1<<10); /* mark this node as processed */
1498 /* If signode is nonrevocable and unexpired and n isn't,
1499 then take signode (skip). It doesn't matter which is
1500 older: if signode was older then we don't want to take n
1501 as signode is nonrevocable. If n was older then we're
1502 automatically fine. */
1504 if(((IS_UID_SIG(signode->pkt->pkt.signature) &&
1505 !signode->pkt->pkt.signature->flags.revocable &&
1506 (signode->pkt->pkt.signature->expiredate==0 ||
1507 signode->pkt->pkt.signature->expiredate>curtime))) &&
1508 (!(IS_UID_SIG(n->pkt->pkt.signature) &&
1509 !n->pkt->pkt.signature->flags.revocable &&
1510 (n->pkt->pkt.signature->expiredate==0 ||
1511 n->pkt->pkt.signature->expiredate>curtime))))
1512 continue;
1514 /* If n is nonrevocable and unexpired and signode isn't,
1515 then take n. Again, it doesn't matter which is older: if
1516 n was older then we don't want to take signode as n is
1517 nonrevocable. If signode was older then we're
1518 automatically fine. */
1520 if((!(IS_UID_SIG(signode->pkt->pkt.signature) &&
1521 !signode->pkt->pkt.signature->flags.revocable &&
1522 (signode->pkt->pkt.signature->expiredate==0 ||
1523 signode->pkt->pkt.signature->expiredate>curtime))) &&
1524 ((IS_UID_SIG(n->pkt->pkt.signature) &&
1525 !n->pkt->pkt.signature->flags.revocable &&
1526 (n->pkt->pkt.signature->expiredate==0 ||
1527 n->pkt->pkt.signature->expiredate>curtime))))
1529 signode = n;
1530 sigdate = sig->timestamp;
1531 continue;
1534 /* At this point, if it's newer, it goes in as the only
1535 remaining possibilities are signode and n are both either
1536 revocable or expired or both nonrevocable and unexpired.
1537 If the timestamps are equal take the later ordered
1538 packet, presuming that the key packets are hopefully in
1539 their original order. */
1541 if (sig->timestamp >= sigdate)
1543 signode = n;
1544 sigdate = sig->timestamp;
1548 sig = signode->pkt->pkt.signature;
1549 if (IS_UID_SIG (sig))
1550 { /* this seems to be a usable one which is not revoked.
1551 * Just need to check whether there is an expiration time,
1552 * We do the expired certification after finding a suitable
1553 * certification, the assumption is that a signator does not
1554 * want that after the expiration of his certificate the
1555 * system falls back to an older certification which has a
1556 * different expiration time */
1557 const byte *p;
1558 u32 expire;
1560 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_EXPIRE, NULL );
1561 expire = p? sig->timestamp + buffer_to_u32(p) : 0;
1563 if (expire==0 || expire > curtime )
1565 signode->flag |= (1<<8); /* yeah, found a good cert */
1566 if (next_expire && expire && expire < *next_expire)
1567 *next_expire = expire;
1570 else
1571 signode->flag |= (1<<11);
1575 static int
1576 clean_sigs_from_uid(KBNODE keyblock,KBNODE uidnode,int noisy,int self_only)
1578 int deleted=0;
1579 KBNODE node;
1580 u32 keyid[2];
1582 assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY);
1584 keyid_from_pk(keyblock->pkt->pkt.public_key,keyid);
1586 /* Passing in a 0 for current time here means that we'll never weed
1587 out an expired sig. This is correct behavior since we want to
1588 keep the most recent expired sig in a series. */
1589 mark_usable_uid_certs(keyblock,uidnode,NULL,NULL,0,NULL);
1591 /* What we want to do here is remove signatures that are not
1592 considered as part of the trust calculations. Thus, all invalid
1593 signatures are out, as are any signatures that aren't the last of
1594 a series of uid sigs or revocations It breaks down like this:
1595 coming out of mark_usable_uid_certs, if a sig is unflagged, it is
1596 not even a candidate. If a sig has flag 9 or 10, that means it
1597 was selected as a candidate and vetted. If a sig has flag 8 it
1598 is a usable signature. If a sig has flag 11 it is a usable
1599 revocation. If a sig has flag 12 it was issued by an unavailable
1600 key. "Usable" here means the most recent valid
1601 signature/revocation in a series from a particular signer.
1603 Delete everything that isn't a usable uid sig (which might be
1604 expired), a usable revocation, or a sig from an unavailable
1605 key. */
1607 for(node=uidnode->next;
1608 node && node->pkt->pkttype==PKT_SIGNATURE;
1609 node=node->next)
1611 int keep=self_only?(node->pkt->pkt.signature->keyid[0]==keyid[0]
1612 && node->pkt->pkt.signature->keyid[1]==keyid[1]):1;
1614 /* Keep usable uid sigs ... */
1615 if((node->flag & (1<<8)) && keep)
1616 continue;
1618 /* ... and usable revocations... */
1619 if((node->flag & (1<<11)) && keep)
1620 continue;
1622 /* ... and sigs from unavailable keys. */
1623 /* disabled for now since more people seem to want sigs from
1624 unavailable keys removed altogether. */
1626 if(node->flag & (1<<12))
1627 continue;
1630 /* Everything else we delete */
1632 /* At this point, if 12 is set, the signing key was unavailable.
1633 If 9 or 10 is set, it's superceded. Otherwise, it's
1634 invalid. */
1636 if(noisy)
1637 log_info("removing signature from key %s on user ID \"%s\": %s\n",
1638 keystr(node->pkt->pkt.signature->keyid),
1639 uidnode->pkt->pkt.user_id->name,
1640 node->flag&(1<<12)?"key unavailable":
1641 node->flag&(1<<9)?"signature superceded":"invalid signature");
1643 delete_kbnode(node);
1644 deleted++;
1647 return deleted;
1650 /* This is substantially easier than clean_sigs_from_uid since we just
1651 have to establish if the uid has a valid self-sig, is not revoked,
1652 and is not expired. Note that this does not take into account
1653 whether the uid has a trust path to it - just whether the keyholder
1654 themselves has certified the uid. Returns true if the uid was
1655 compacted. To "compact" a user ID, we simply remove ALL signatures
1656 except the self-sig that caused the user ID to be remove-worthy.
1657 We don't actually remove the user ID packet itself since it might
1658 be ressurected in a later merge. Note that this function requires
1659 that the caller has already done a merge_keys_and_selfsig().
1661 TODO: change the import code to allow importing a uid with only a
1662 revocation if the uid already exists on the keyring. */
1664 static int
1665 clean_uid_from_key(KBNODE keyblock,KBNODE uidnode,int noisy)
1667 KBNODE node;
1668 PKT_user_id *uid=uidnode->pkt->pkt.user_id;
1669 int deleted=0;
1671 assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY);
1672 assert(uidnode->pkt->pkttype==PKT_USER_ID);
1674 /* Skip valid user IDs, compacted user IDs, and non-self-signed user
1675 IDs if --allow-non-selfsigned-uid is set. */
1676 if(uid->created || uid->flags.compacted
1677 || (!uid->is_expired && !uid->is_revoked
1678 && opt.allow_non_selfsigned_uid))
1679 return 0;
1681 for(node=uidnode->next;
1682 node && node->pkt->pkttype==PKT_SIGNATURE;
1683 node=node->next)
1684 if(!node->pkt->pkt.signature->flags.chosen_selfsig)
1686 delete_kbnode(node);
1687 deleted=1;
1688 uidnode->pkt->pkt.user_id->flags.compacted=1;
1691 if(noisy)
1693 const char *reason;
1694 char *user=utf8_to_native(uid->name,uid->len,0);
1696 if(uid->is_revoked)
1697 reason=_("revoked");
1698 else if(uid->is_expired)
1699 reason=_("expired");
1700 else
1701 reason=_("invalid");
1703 log_info("compacting user ID \"%s\" on key %s: %s\n",
1704 user,keystr_from_pk(keyblock->pkt->pkt.public_key),
1705 reason);
1707 xfree(user);
1710 return deleted;
1713 /* Needs to be called after a merge_keys_and_selfsig() */
1714 void
1715 clean_one_uid(KBNODE keyblock,KBNODE uidnode,int noisy,int self_only,
1716 int *uids_cleaned,int *sigs_cleaned)
1718 int dummy;
1720 assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY);
1721 assert(uidnode->pkt->pkttype==PKT_USER_ID);
1723 if(!uids_cleaned)
1724 uids_cleaned=&dummy;
1726 if(!sigs_cleaned)
1727 sigs_cleaned=&dummy;
1729 /* Do clean_uid_from_key first since if it fires off, we don't
1730 have to bother with the other */
1731 *uids_cleaned+=clean_uid_from_key(keyblock,uidnode,noisy);
1732 if(!uidnode->pkt->pkt.user_id->flags.compacted)
1733 *sigs_cleaned+=clean_sigs_from_uid(keyblock,uidnode,noisy,self_only);
1736 void
1737 clean_key(KBNODE keyblock,int noisy,int self_only,
1738 int *uids_cleaned,int *sigs_cleaned)
1740 KBNODE uidnode;
1742 merge_keys_and_selfsig(keyblock);
1744 for(uidnode=keyblock->next;
1745 uidnode && uidnode->pkt->pkttype!=PKT_PUBLIC_SUBKEY;
1746 uidnode=uidnode->next)
1747 if(uidnode->pkt->pkttype==PKT_USER_ID)
1748 clean_one_uid(keyblock,uidnode,noisy,self_only,
1749 uids_cleaned,sigs_cleaned);
1752 /* Used by validate_one_keyblock to confirm a regexp within a trust
1753 signature. Returns 1 for match, and 0 for no match or regex
1754 error. */
1755 static int
1756 check_regexp(const char *expr,const char *string)
1758 #ifdef DISABLE_REGEX
1759 /* When DISABLE_REGEX is defined, assume all regexps do not
1760 match. */
1761 return 0;
1762 #elif defined(__riscos__)
1763 return riscos_check_regexp(expr, string, DBG_TRUST);
1764 #else
1765 int ret;
1766 regex_t pat;
1768 if(regcomp(&pat,expr,REG_ICASE|REG_NOSUB|REG_EXTENDED)!=0)
1769 return 0;
1771 ret=regexec(&pat,string,0,NULL,0);
1773 regfree(&pat);
1775 if(DBG_TRUST)
1776 log_debug("regexp `%s' on `%s': %s\n",expr,string,ret==0?"YES":"NO");
1778 return (ret==0);
1779 #endif
1783 * Return true if the key is signed by one of the keys in the given
1784 * key ID list. User IDs with a valid signature are marked by node
1785 * flags as follows:
1786 * flag bit 0: There is at least one signature
1787 * 1: There is marginal confidence that this is a legitimate uid
1788 * 2: There is full confidence that this is a legitimate uid.
1789 * 8: Used for internal purposes.
1790 * 9: Ditto (in mark_usable_uid_certs())
1791 * 10: Ditto (ditto)
1792 * This function assumes that all kbnode flags are cleared on entry.
1794 static int
1795 validate_one_keyblock (KBNODE kb, struct key_item *klist,
1796 u32 curtime, u32 *next_expire)
1798 struct key_item *kr;
1799 KBNODE node, uidnode=NULL;
1800 PKT_user_id *uid=NULL;
1801 PKT_public_key *pk = kb->pkt->pkt.public_key;
1802 u32 main_kid[2];
1803 int issigned=0, any_signed = 0;
1805 keyid_from_pk(pk, main_kid);
1806 for (node=kb; node; node = node->next)
1808 /* A bit of discussion here: is it better for the web of trust
1809 to be built among only self-signed uids? On the one hand, a
1810 self-signed uid is a statement that the key owner definitely
1811 intended that uid to be there, but on the other hand, a
1812 signed (but not self-signed) uid does carry trust, of a sort,
1813 even if it is a statement being made by people other than the
1814 key owner "through" the uids on the key owner's key. I'm
1815 going with the latter. However, if the user ID was
1816 explicitly revoked, or passively allowed to expire, that
1817 should stop validity through the user ID until it is
1818 resigned. -dshaw */
1820 if (node->pkt->pkttype == PKT_USER_ID
1821 && !node->pkt->pkt.user_id->is_revoked
1822 && !node->pkt->pkt.user_id->is_expired)
1824 if (uidnode && issigned)
1826 if (uid->help_full_count >= opt.completes_needed
1827 || uid->help_marginal_count >= opt.marginals_needed )
1828 uidnode->flag |= 4;
1829 else if (uid->help_full_count || uid->help_marginal_count)
1830 uidnode->flag |= 2;
1831 uidnode->flag |= 1;
1832 any_signed = 1;
1834 uidnode = node;
1835 uid=uidnode->pkt->pkt.user_id;
1837 /* If the selfsig is going to expire... */
1838 if(uid->expiredate && uid->expiredate<*next_expire)
1839 *next_expire = uid->expiredate;
1841 issigned = 0;
1842 get_validity_counts(pk,uid);
1843 mark_usable_uid_certs (kb, uidnode, main_kid, klist,
1844 curtime, next_expire);
1846 else if (node->pkt->pkttype == PKT_SIGNATURE
1847 && (node->flag & (1<<8)) && uid)
1849 /* Note that we are only seeing unrevoked sigs here */
1850 PKT_signature *sig = node->pkt->pkt.signature;
1852 kr = is_in_klist (klist, sig);
1853 /* If the trust_regexp does not match, it's as if the sig
1854 did not exist. This is safe for non-trust sigs as well
1855 since we don't accept a regexp on the sig unless it's a
1856 trust sig. */
1857 if (kr && (kr->trust_regexp==NULL || opt.trust_model!=TM_PGP ||
1858 (uidnode && check_regexp(kr->trust_regexp,
1859 uidnode->pkt->pkt.user_id->name))))
1861 if(DBG_TRUST && opt.trust_model==TM_PGP && sig->trust_depth)
1862 log_debug("trust sig on %s, sig depth is %d, kr depth is %d\n",
1863 uidnode->pkt->pkt.user_id->name,sig->trust_depth,
1864 kr->trust_depth);
1866 /* Are we part of a trust sig chain? We always favor
1867 the latest trust sig, rather than the greater or
1868 lesser trust sig or value. I could make a decent
1869 argument for any of these cases, but this seems to be
1870 what PGP does, and I'd like to be compatible. -dms */
1871 if(opt.trust_model==TM_PGP && sig->trust_depth
1872 && pk->trust_timestamp<=sig->timestamp
1873 && (sig->trust_depth<=kr->trust_depth
1874 || kr->ownertrust==TRUST_ULTIMATE))
1876 /* If we got here, we know that:
1878 this is a trust sig.
1880 it's a newer trust sig than any previous trust
1881 sig on this key (not uid).
1883 it is legal in that it was either generated by an
1884 ultimate key, or a key that was part of a trust
1885 chain, and the depth does not violate the
1886 original trust sig.
1888 if there is a regexp attached, it matched
1889 successfully.
1892 if(DBG_TRUST)
1893 log_debug("replacing trust value %d with %d and "
1894 "depth %d with %d\n",
1895 pk->trust_value,sig->trust_value,
1896 pk->trust_depth,sig->trust_depth);
1898 pk->trust_value=sig->trust_value;
1899 pk->trust_depth=sig->trust_depth-1;
1901 /* If the trust sig contains a regexp, record it
1902 on the pk for the next round. */
1903 if(sig->trust_regexp)
1904 pk->trust_regexp=sig->trust_regexp;
1907 if (kr->ownertrust == TRUST_ULTIMATE)
1908 uid->help_full_count = opt.completes_needed;
1909 else if (kr->ownertrust == TRUST_FULLY)
1910 uid->help_full_count++;
1911 else if (kr->ownertrust == TRUST_MARGINAL)
1912 uid->help_marginal_count++;
1913 issigned = 1;
1918 if (uidnode && issigned)
1920 if (uid->help_full_count >= opt.completes_needed
1921 || uid->help_marginal_count >= opt.marginals_needed )
1922 uidnode->flag |= 4;
1923 else if (uid->help_full_count || uid->help_marginal_count)
1924 uidnode->flag |= 2;
1925 uidnode->flag |= 1;
1926 any_signed = 1;
1929 return any_signed;
1933 static int
1934 search_skipfnc (void *opaque, u32 *kid, PKT_user_id *dummy)
1936 return test_key_hash_table ((KeyHashTable)opaque, kid);
1941 * Scan all keys and return a key_array of all suitable keys from
1942 * kllist. The caller has to pass keydb handle so that we don't use
1943 * to create our own. Returns either a key_array or NULL in case of
1944 * an error. No results found are indicated by an empty array.
1945 * Caller hast to release the returned array.
1947 static struct key_array *
1948 validate_key_list (KEYDB_HANDLE hd, KeyHashTable full_trust,
1949 struct key_item *klist, u32 curtime, u32 *next_expire)
1951 KBNODE keyblock = NULL;
1952 struct key_array *keys = NULL;
1953 size_t nkeys, maxkeys;
1954 int rc;
1955 KEYDB_SEARCH_DESC desc;
1957 maxkeys = 1000;
1958 keys = xmalloc ((maxkeys+1) * sizeof *keys);
1959 nkeys = 0;
1961 rc = keydb_search_reset (hd);
1962 if (rc)
1964 log_error ("keydb_search_reset failed: %s\n", g10_errstr(rc));
1965 xfree (keys);
1966 return NULL;
1969 memset (&desc, 0, sizeof desc);
1970 desc.mode = KEYDB_SEARCH_MODE_FIRST;
1971 desc.skipfnc = search_skipfnc;
1972 desc.skipfncvalue = full_trust;
1973 rc = keydb_search (hd, &desc, 1);
1974 if (rc == -1)
1976 keys[nkeys].keyblock = NULL;
1977 return keys;
1979 if (rc)
1981 log_error ("keydb_search_first failed: %s\n", g10_errstr(rc));
1982 xfree (keys);
1983 return NULL;
1986 desc.mode = KEYDB_SEARCH_MODE_NEXT; /* change mode */
1989 PKT_public_key *pk;
1991 rc = keydb_get_keyblock (hd, &keyblock);
1992 if (rc)
1994 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
1995 xfree (keys);
1996 return NULL;
1999 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2001 log_debug ("ooops: invalid pkttype %d encountered\n",
2002 keyblock->pkt->pkttype);
2003 dump_kbnode (keyblock);
2004 release_kbnode(keyblock);
2005 continue;
2008 /* prepare the keyblock for further processing */
2009 merge_keys_and_selfsig (keyblock);
2010 clear_kbnode_flags (keyblock);
2011 pk = keyblock->pkt->pkt.public_key;
2012 if (pk->has_expired || pk->is_revoked)
2014 /* it does not make sense to look further at those keys */
2015 mark_keyblock_seen (full_trust, keyblock);
2017 else if (validate_one_keyblock (keyblock, klist, curtime, next_expire))
2019 KBNODE node;
2021 if (pk->expiredate && pk->expiredate >= curtime
2022 && pk->expiredate < *next_expire)
2023 *next_expire = pk->expiredate;
2025 if (nkeys == maxkeys) {
2026 maxkeys += 1000;
2027 keys = xrealloc (keys, (maxkeys+1) * sizeof *keys);
2029 keys[nkeys++].keyblock = keyblock;
2031 /* Optimization - if all uids are fully trusted, then we
2032 never need to consider this key as a candidate again. */
2034 for (node=keyblock; node; node = node->next)
2035 if (node->pkt->pkttype == PKT_USER_ID && !(node->flag & 4))
2036 break;
2038 if(node==NULL)
2039 mark_keyblock_seen (full_trust, keyblock);
2041 keyblock = NULL;
2044 release_kbnode (keyblock);
2045 keyblock = NULL;
2047 while ( !(rc = keydb_search (hd, &desc, 1)) );
2048 if (rc && rc != -1)
2050 log_error ("keydb_search_next failed: %s\n", g10_errstr(rc));
2051 xfree (keys);
2052 return NULL;
2055 keys[nkeys].keyblock = NULL;
2056 return keys;
2059 /* Caller must sync */
2060 static void
2061 reset_trust_records(void)
2063 TRUSTREC rec;
2064 ulong recnum;
2065 int count = 0, nreset = 0;
2067 for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
2069 if(rec.rectype==RECTYPE_TRUST)
2071 count++;
2072 if(rec.r.trust.min_ownertrust)
2074 rec.r.trust.min_ownertrust=0;
2075 write_record(&rec);
2079 else if(rec.rectype==RECTYPE_VALID
2080 && ((rec.r.valid.validity&TRUST_MASK)
2081 || rec.r.valid.marginal_count
2082 || rec.r.valid.full_count))
2084 rec.r.valid.validity &= ~TRUST_MASK;
2085 rec.r.valid.marginal_count=rec.r.valid.full_count=0;
2086 nreset++;
2087 write_record(&rec);
2092 if (opt.verbose)
2093 log_info (_("%d keys processed (%d validity counts cleared)\n"),
2094 count, nreset);
2098 * Run the key validation procedure.
2100 * This works this way:
2101 * Step 1: Find all ultimately trusted keys (UTK).
2102 * mark them all as seen and put them into klist.
2103 * Step 2: loop max_cert_times
2104 * Step 3: if OWNERTRUST of any key in klist is undefined
2105 * ask user to assign ownertrust
2106 * Step 4: Loop over all keys in the keyDB which are not marked seen
2107 * Step 5: if key is revoked or expired
2108 * mark key as seen
2109 * continue loop at Step 4
2110 * Step 6: For each user ID of that key signed by a key in klist
2111 * Calculate validity by counting trusted signatures.
2112 * Set validity of user ID
2113 * Step 7: If any signed user ID was found
2114 * mark key as seen
2115 * End Loop
2116 * Step 8: Build a new klist from all fully trusted keys from step 6
2117 * End Loop
2118 * Ready
2121 static int
2122 validate_keys (int interactive)
2124 int rc = 0;
2125 int quit=0;
2126 struct key_item *klist = NULL;
2127 struct key_item *k;
2128 struct key_array *keys = NULL;
2129 struct key_array *kar;
2130 KEYDB_HANDLE kdb = NULL;
2131 KBNODE node;
2132 int depth;
2133 int ot_unknown, ot_undefined, ot_never, ot_marginal, ot_full, ot_ultimate;
2134 KeyHashTable stored,used,full_trust;
2135 u32 start_time, next_expire;
2137 /* Make sure we have all sigs cached. TODO: This is going to
2138 require some architectual re-thinking, as it is agonizingly slow.
2139 Perhaps combine this with reset_trust_records(), or only check
2140 the caches on keys that are actually involved in the web of
2141 trust. */
2142 keydb_rebuild_caches(0);
2144 start_time = make_timestamp ();
2145 next_expire = 0xffffffff; /* set next expire to the year 2106 */
2146 stored = new_key_hash_table ();
2147 used = new_key_hash_table ();
2148 full_trust = new_key_hash_table ();
2150 kdb = keydb_new (0);
2151 reset_trust_records();
2153 /* Fixme: Instead of always building a UTK list, we could just build it
2154 * here when needed */
2155 if (!utk_list)
2157 if (!opt.quiet)
2158 log_info (_("no ultimately trusted keys found\n"));
2159 goto leave;
2162 /* mark all UTKs as used and fully_trusted and set validity to
2163 ultimate */
2164 for (k=utk_list; k; k = k->next)
2166 KBNODE keyblock;
2167 PKT_public_key *pk;
2169 keyblock = get_pubkeyblock (k->kid);
2170 if (!keyblock)
2172 log_error (_("public key of ultimately"
2173 " trusted key %s not found\n"), keystr(k->kid));
2174 continue;
2176 mark_keyblock_seen (used, keyblock);
2177 mark_keyblock_seen (stored, keyblock);
2178 mark_keyblock_seen (full_trust, keyblock);
2179 pk = keyblock->pkt->pkt.public_key;
2180 for (node=keyblock; node; node = node->next)
2182 if (node->pkt->pkttype == PKT_USER_ID)
2183 update_validity (pk, node->pkt->pkt.user_id, 0, TRUST_ULTIMATE);
2185 if ( pk->expiredate && pk->expiredate >= start_time
2186 && pk->expiredate < next_expire)
2187 next_expire = pk->expiredate;
2189 release_kbnode (keyblock);
2190 do_sync ();
2193 klist = utk_list;
2195 log_info(_("%d marginal(s) needed, %d complete(s) needed, %s trust model\n"),
2196 opt.marginals_needed,opt.completes_needed,trust_model_string());
2198 for (depth=0; depth < opt.max_cert_depth; depth++)
2200 int valids=0,key_count;
2201 /* See whether we should assign ownertrust values to the keys in
2202 klist. */
2203 ot_unknown = ot_undefined = ot_never = 0;
2204 ot_marginal = ot_full = ot_ultimate = 0;
2205 for (k=klist; k; k = k->next)
2207 int min=0;
2209 /* 120 and 60 are as per RFC2440 */
2210 if(k->trust_value>=120)
2211 min=TRUST_FULLY;
2212 else if(k->trust_value>=60)
2213 min=TRUST_MARGINAL;
2215 if(min!=k->min_ownertrust)
2216 update_min_ownertrust(k->kid,min);
2218 if (interactive && k->ownertrust == TRUST_UNKNOWN)
2220 k->ownertrust = ask_ownertrust (k->kid,min);
2222 if (k->ownertrust == -1)
2224 quit=1;
2225 goto leave;
2229 /* This can happen during transition from an old trustdb
2230 before trust sigs. It can also happen if a user uses two
2231 different versions of GnuPG or changes the --trust-model
2232 setting. */
2233 if(k->ownertrust<min)
2235 if(DBG_TRUST)
2236 log_debug("key %08lX%08lX:"
2237 " overriding ownertrust `%s' with `%s'\n",
2238 (ulong)k->kid[0],(ulong)k->kid[1],
2239 trust_value_to_string(k->ownertrust),
2240 trust_value_to_string(min));
2242 k->ownertrust=min;
2245 if (k->ownertrust == TRUST_UNKNOWN)
2246 ot_unknown++;
2247 else if (k->ownertrust == TRUST_UNDEFINED)
2248 ot_undefined++;
2249 else if (k->ownertrust == TRUST_NEVER)
2250 ot_never++;
2251 else if (k->ownertrust == TRUST_MARGINAL)
2252 ot_marginal++;
2253 else if (k->ownertrust == TRUST_FULLY)
2254 ot_full++;
2255 else if (k->ownertrust == TRUST_ULTIMATE)
2256 ot_ultimate++;
2258 valids++;
2261 /* Find all keys which are signed by a key in kdlist */
2262 keys = validate_key_list (kdb, full_trust, klist,
2263 start_time, &next_expire);
2264 if (!keys)
2266 log_error ("validate_key_list failed\n");
2267 rc = G10ERR_GENERAL;
2268 goto leave;
2271 for (key_count=0, kar=keys; kar->keyblock; kar++, key_count++)
2274 /* Store the calculated valididation status somewhere */
2275 if (opt.verbose > 1)
2276 dump_key_array (depth, keys);
2278 for (kar=keys; kar->keyblock; kar++)
2279 store_validation_status (depth, kar->keyblock, stored);
2281 log_info (_("depth: %d valid: %3d signed: %3d"
2282 " trust: %d-, %dq, %dn, %dm, %df, %du\n"),
2283 depth, valids, key_count, ot_unknown, ot_undefined,
2284 ot_never, ot_marginal, ot_full, ot_ultimate );
2286 /* Build a new kdlist from all fully valid keys in KEYS */
2287 if (klist != utk_list)
2288 release_key_items (klist);
2289 klist = NULL;
2290 for (kar=keys; kar->keyblock; kar++)
2292 for (node=kar->keyblock; node; node = node->next)
2294 if (node->pkt->pkttype == PKT_USER_ID && (node->flag & 4))
2296 u32 kid[2];
2298 /* have we used this key already? */
2299 keyid_from_pk (kar->keyblock->pkt->pkt.public_key, kid);
2300 if(test_key_hash_table(used,kid)==0)
2302 /* Normally we add both the primary and subkey
2303 ids to the hash via mark_keyblock_seen, but
2304 since we aren't using this hash as a skipfnc,
2305 that doesn't matter here. */
2306 add_key_hash_table (used,kid);
2307 k = new_key_item ();
2308 k->kid[0]=kid[0];
2309 k->kid[1]=kid[1];
2310 k->ownertrust =
2311 (get_ownertrust (kar->keyblock->pkt->pkt.public_key)
2312 & TRUST_MASK);
2313 k->min_ownertrust =
2314 get_min_ownertrust(kar->keyblock->pkt->pkt.public_key);
2315 k->trust_depth=
2316 kar->keyblock->pkt->pkt.public_key->trust_depth;
2317 k->trust_value=
2318 kar->keyblock->pkt->pkt.public_key->trust_value;
2319 if(kar->keyblock->pkt->pkt.public_key->trust_regexp)
2320 k->trust_regexp=
2321 xstrdup(kar->keyblock->pkt->
2322 pkt.public_key->trust_regexp);
2323 k->next = klist;
2324 klist = k;
2325 break;
2330 release_key_array (keys);
2331 keys = NULL;
2332 if (!klist)
2333 break; /* no need to dive in deeper */
2336 leave:
2337 keydb_release (kdb);
2338 release_key_array (keys);
2339 release_key_items (klist);
2340 release_key_hash_table (full_trust);
2341 release_key_hash_table (used);
2342 release_key_hash_table (stored);
2343 if (!rc && !quit) /* mark trustDB as checked */
2345 if (next_expire == 0xffffffff || next_expire < start_time )
2346 tdbio_write_nextcheck (0);
2347 else
2349 tdbio_write_nextcheck (next_expire);
2350 log_info (_("next trustdb check due at %s\n"),
2351 strtimestamp (next_expire));
2354 if(tdbio_update_version_record()!=0)
2356 log_error(_("unable to update trustdb version record: "
2357 "write failed: %s\n"), g10_errstr(rc));
2358 tdbio_invalid();
2361 do_sync ();
2362 pending_check_trustdb = 0;
2365 return rc;