2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3 * 2008, 2012 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/>.
28 #include <sys/types.h>
30 #endif /* !DISABLE_REGEX */
45 typedef struct key_item **KeyHashTable; /* see new_key_hash_table() */
48 * Structure to keep track of keys, this is used as an array wherre
49 * the item right after the last one has a keyblock set to NULL.
50 * Maybe we can drop this thing and replace it by key_item
58 /* Control information for the trust DB. */
68 static struct key_item *user_utk_list; /* temp. used to store --trusted-keys */
69 static struct key_item *utk_list; /* all ultimately trusted keys */
71 static int pending_check_trustdb;
73 static int validate_keys (int interactive);
76 /**********************************************
77 ************* some helpers *******************
78 **********************************************/
80 static struct key_item *
85 k = xmalloc_clear (sizeof *k);
90 release_key_items (struct key_item *k)
97 xfree (k->trust_regexp);
102 #define KEY_HASH_TABLE_SIZE 1024
105 * For fast keylook up we need a hash table. Each byte of a KeyID
106 * should be distributed equally over the 256 possible values (except
107 * for v3 keyIDs but we consider them as not important here). So we
108 * can just use 10 bits to index a table of KEY_HASH_TABLE_SIZE key items.
109 * Possible optimization: Do not use key_items but other hash_table when the
110 * duplicates lists get too large.
113 new_key_hash_table (void)
115 struct key_item **tbl;
117 tbl = xmalloc_clear (KEY_HASH_TABLE_SIZE * sizeof *tbl);
122 release_key_hash_table (KeyHashTable tbl)
128 for (i=0; i < KEY_HASH_TABLE_SIZE; i++)
129 release_key_items (tbl[i]);
134 * Returns: True if the keyID is in the given hash table
137 test_key_hash_table (KeyHashTable tbl, u32 *kid)
141 for (k = tbl[(kid[1] % KEY_HASH_TABLE_SIZE)]; k; k = k->next)
142 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
148 * Add a new key to the hash table. The key is identified by its key ID.
151 add_key_hash_table (KeyHashTable tbl, u32 *kid)
153 int i = kid[1] % KEY_HASH_TABLE_SIZE;
154 struct key_item *k, *kk;
156 for (k = tbl[i]; k; k = k->next)
157 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
158 return; /* already in table */
160 kk = new_key_item ();
168 * Release a key_array
171 release_key_array ( struct key_array *keys )
176 for (k=keys; k->keyblock; k++)
177 release_kbnode (k->keyblock);
183 /*********************************************
184 ********** Initialization *****************
185 *********************************************/
190 * Used to register extra ultimately trusted keys - this has to be done
191 * before initializing the validation module.
192 * FIXME: Should be replaced by a function to add those keys to the trustdb.
195 tdb_register_trusted_keyid (u32 *keyid)
200 k->kid[0] = keyid[0];
201 k->kid[1] = keyid[1];
202 k->next = user_utk_list;
207 tdb_register_trusted_key( const char *string )
210 KEYDB_SEARCH_DESC desc;
212 err = classify_user_id (string, &desc, 1);
213 if (err || desc.mode != KEYDB_SEARCH_MODE_LONG_KID )
215 log_error(_("'%s' is not a valid long keyID\n"), string );
219 register_trusted_keyid(desc.u.kid);
223 * Helper to add a key to the global list of ultimately trusted keys.
224 * Retruns: true = inserted, false = already in in list.
231 for (k = utk_list; k; k = k->next)
233 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
242 k->ownertrust = TRUST_ULTIMATE;
245 if( opt.verbose > 1 )
246 log_info(_("key %s: accepted as trusted key\n"), keystr(kid));
252 * Verify that all our secret keys are usable and put them into the utk_list.
255 verify_own_keys(void)
265 /* scan the trustdb to find all ultimately trusted keys */
266 for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
268 if ( rec.rectype == RECTYPE_TRUST
269 && (rec.r.trust.ownertrust & TRUST_MASK) == TRUST_ULTIMATE)
271 byte *fpr = rec.r.trust.fingerprint;
275 /* Problem: We do only use fingerprints in the trustdb but
276 * we need the keyID here to indetify the key; we can only
277 * use that ugly hack to distinguish between 16 and 20
278 * butes fpr - it does not work always so we better change
279 * the whole validation code to only work with
281 fprlen = (!fpr[16] && !fpr[17] && !fpr[18] && !fpr[19])? 16:20;
282 keyid_from_fingerprint (fpr, fprlen, kid);
284 log_info(_("key %s occurs more than once in the trustdb\n"),
289 /* Put any --trusted-key keys into the trustdb */
290 for (k = user_utk_list; k; k = k->next)
292 if ( add_utk (k->kid) )
293 { /* not yet in trustDB as ultimately trusted */
296 memset (&pk, 0, sizeof pk);
297 rc = get_pubkey (&pk, k->kid);
299 log_info(_("key %s: no public key for trusted key - skipped\n"),
303 tdb_update_ownertrust (&pk,
304 ((tdb_get_ownertrust (&pk) & ~TRUST_MASK)
306 release_public_key_parts (&pk);
309 log_info (_("key %s marked as ultimately trusted\n"),keystr(k->kid));
313 /* release the helper table table */
314 release_key_items (user_utk_list);
315 user_utk_list = NULL;
320 /*********************************************
321 *********** TrustDB stuff *******************
322 *********************************************/
325 * Read a record but die if it does not exist
328 read_record (ulong recno, TRUSTREC *rec, int rectype )
330 int rc = tdbio_read_record (recno, rec, rectype);
333 log_error(_("trust record %lu, req type %d: read failed: %s\n"),
334 recno, rec->rectype, gpg_strerror (rc) );
337 if (rectype != rec->rectype)
339 log_error(_("trust record %lu is not of requested type %d\n"),
340 rec->recnum, rectype);
346 * Write a record and die on error
349 write_record (TRUSTREC *rec)
351 int rc = tdbio_write_record (rec);
354 log_error(_("trust record %lu, type %d: write failed: %s\n"),
355 rec->recnum, rec->rectype, gpg_strerror (rc) );
361 * sync the TrustDb and die on error
366 int rc = tdbio_sync ();
369 log_error (_("trustdb: sync failed: %s\n"), gpg_strerror (rc) );
375 trust_model_string(void)
377 switch(opt.trust_model)
379 case TM_CLASSIC: return "classic";
380 case TM_PGP: return "PGP";
381 case TM_EXTERNAL: return "external";
382 case TM_ALWAYS: return "always";
383 case TM_DIRECT: return "direct";
384 default: return "unknown";
389 * Perform some checks over the trustdb
390 * level 0: only open the db
391 * 1: used for initial program startup
394 setup_trustdb( int level, const char *dbname )
396 /* just store the args */
397 if( trustdb_args.init )
399 trustdb_args.level = level;
400 trustdb_args.dbname = dbname? xstrdup(dbname): NULL;
405 how_to_fix_the_trustdb ()
407 const char *name = trustdb_args.dbname;
410 name = "trustdb.gpg";
412 log_info (_("You may try to re-create the trustdb using the commands:\n"));
413 log_info (" cd %s\n", default_homedir ());
414 log_info (" gpg2 --export-ownertrust > otrust.tmp\n");
415 #ifdef HAVE_W32_SYSTEM
416 log_info (" del %s\n", name);
418 log_info (" rm %s\n", name);
420 log_info (" gpg2 --import-ownertrust < otrust.tmp\n");
421 log_info (_("If that does not work, please consult the manual\n"));
428 int level = trustdb_args.level;
429 const char* dbname = trustdb_args.dbname;
431 if( trustdb_args.init )
434 trustdb_args.init = 1;
436 if(level==0 || level==1)
438 int rc = tdbio_set_dbname( dbname, !!level, &trustdb_args.no_trustdb);
440 log_fatal("can't init trustdb: %s\n", gpg_strerror (rc) );
445 if(opt.trust_model==TM_AUTO)
447 /* Try and set the trust model off of whatever the trustdb says
449 opt.trust_model=tdbio_read_model();
451 /* Sanity check this ;) */
452 if(opt.trust_model!=TM_CLASSIC
453 && opt.trust_model!=TM_PGP
454 && opt.trust_model!=TM_EXTERNAL)
456 log_info(_("unable to use unknown trust model (%d) - "
457 "assuming %s trust model\n"),opt.trust_model,"PGP");
458 opt.trust_model=TM_PGP;
462 log_info(_("using %s trust model\n"),trust_model_string());
465 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
467 /* Verify the list of ultimately trusted keys and move the
468 --trusted-keys list there as well. */
472 if(!tdbio_db_matches_options())
473 pending_check_trustdb=1;
479 * Recreate the WoT but do not ask for new ownertrusts. Special
480 * feature: In batch mode and without a forced yes, this is only done
481 * when a check is due. This can be used to run the check from a crontab
487 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
489 if (opt.batch && !opt.answer_yes)
493 scheduled = tdbio_read_nextcheck ();
496 log_info (_("no need for a trustdb check\n"));
500 if (scheduled > make_timestamp ())
502 log_info (_("next trustdb check due at %s\n"),
503 strtimestamp (scheduled));
511 log_info (_("no need for a trustdb check with '%s' trust model\n"),
512 trust_model_string());
523 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
526 log_info (_("no need for a trustdb update with '%s' trust model\n"),
527 trust_model_string());
531 tdb_revalidation_mark (void)
534 if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
537 /* We simply set the time for the next check to 1 (far back in 1970)
538 so that a --update-trustdb will be scheduled. */
539 if (tdbio_write_nextcheck (1))
541 pending_check_trustdb = 1;
545 trustdb_pending_check(void)
547 return pending_check_trustdb;
550 /* If the trustdb is dirty, and we're interactive, update it.
551 Otherwise, check it unless no-auto-check-trustdb is set. */
553 tdb_check_or_update (void)
555 if(trustdb_pending_check())
559 else if(!opt.no_auto_check_trustdb)
565 read_trust_options(byte *trust_model,ulong *created,ulong *nextcheck,
566 byte *marginals,byte *completes,byte *cert_depth,
567 byte *min_cert_level)
572 if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
573 memset (&opts, 0, sizeof opts);
575 read_record (0, &opts, RECTYPE_VER);
578 *trust_model=opts.r.ver.trust_model;
580 *created=opts.r.ver.created;
582 *nextcheck=opts.r.ver.nextcheck;
584 *marginals=opts.r.ver.marginals;
586 *completes=opts.r.ver.completes;
588 *cert_depth=opts.r.ver.cert_depth;
590 *min_cert_level=opts.r.ver.min_cert_level;
593 /***********************************************
594 *********** Ownertrust et al. ****************
595 ***********************************************/
598 read_trust_record (PKT_public_key *pk, TRUSTREC *rec)
603 rc = tdbio_search_trust_bypk (pk, rec);
606 if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
607 log_error ("trustdb: searching trust record failed: %s\n",
612 if (rec->rectype != RECTYPE_TRUST)
614 log_error ("trustdb: record %lu is not a trust record\n",
616 return GPG_ERR_TRUSTDB;
623 * Return the assigned ownertrust value for the given public key.
624 * The key should be the primary key.
627 tdb_get_ownertrust ( PKT_public_key *pk)
632 if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
633 return TRUST_UNKNOWN;
635 err = read_trust_record (pk, &rec);
636 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
637 return TRUST_UNKNOWN; /* no record yet */
641 return TRUST_UNKNOWN; /* actually never reached */
644 return rec.r.trust.ownertrust;
649 tdb_get_min_ownertrust (PKT_public_key *pk)
654 if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
655 return TRUST_UNKNOWN;
657 err = read_trust_record (pk, &rec);
658 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
659 return TRUST_UNKNOWN; /* no record yet */
663 return TRUST_UNKNOWN; /* actually never reached */
666 return rec.r.trust.min_ownertrust;
671 * Set the trust value of the given public key to the new value.
672 * The key should be a primary one.
675 tdb_update_ownertrust (PKT_public_key *pk, unsigned int new_trust )
680 if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
683 err = read_trust_record (pk, &rec);
687 log_debug ("update ownertrust from %u to %u\n",
688 (unsigned int)rec.r.trust.ownertrust, new_trust );
689 if (rec.r.trust.ownertrust != new_trust)
691 rec.r.trust.ownertrust = new_trust;
692 write_record( &rec );
693 tdb_revalidation_mark ();
697 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
698 { /* no record yet - create a new one */
702 log_debug ("insert ownertrust %u\n", new_trust );
704 memset (&rec, 0, sizeof rec);
705 rec.recnum = tdbio_new_recnum ();
706 rec.rectype = RECTYPE_TRUST;
707 fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
708 rec.r.trust.ownertrust = new_trust;
710 tdb_revalidation_mark ();
721 update_min_ownertrust (u32 *kid, unsigned int new_trust )
727 if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
730 pk = xmalloc_clear (sizeof *pk);
731 err = get_pubkey (pk, kid);
734 log_error (_("public key %s not found: %s\n"),
735 keystr (kid), gpg_strerror (err));
739 err = read_trust_record (pk, &rec);
743 log_debug ("key %08lX%08lX: update min_ownertrust from %u to %u\n",
744 (ulong)kid[0],(ulong)kid[1],
745 (unsigned int)rec.r.trust.min_ownertrust,
747 if (rec.r.trust.min_ownertrust != new_trust)
749 rec.r.trust.min_ownertrust = new_trust;
750 write_record( &rec );
751 tdb_revalidation_mark ();
755 else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
756 { /* no record yet - create a new one */
760 log_debug ("insert min_ownertrust %u\n", new_trust );
762 memset (&rec, 0, sizeof rec);
763 rec.recnum = tdbio_new_recnum ();
764 rec.rectype = RECTYPE_TRUST;
765 fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
766 rec.r.trust.min_ownertrust = new_trust;
768 tdb_revalidation_mark ();
780 * Clear the ownertrust and min_ownertrust values.
782 * Return: True if a change actually happened.
785 tdb_clear_ownertrusts (PKT_public_key *pk)
792 if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
795 err = read_trust_record (pk, &rec);
800 log_debug ("clearing ownertrust (old value %u)\n",
801 (unsigned int)rec.r.trust.ownertrust);
802 log_debug ("clearing min_ownertrust (old value %u)\n",
803 (unsigned int)rec.r.trust.min_ownertrust);
805 if (rec.r.trust.ownertrust || rec.r.trust.min_ownertrust)
807 rec.r.trust.ownertrust = 0;
808 rec.r.trust.min_ownertrust = 0;
809 write_record( &rec );
810 tdb_revalidation_mark ();
815 else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
823 * Note: Caller has to do a sync
826 update_validity (PKT_public_key *pk, PKT_user_id *uid,
827 int depth, int validity)
833 namehash_from_uid(uid);
835 err = read_trust_record (pk, &trec);
836 if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
841 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
843 /* No record yet - create a new one. */
847 memset (&trec, 0, sizeof trec);
848 trec.recnum = tdbio_new_recnum ();
849 trec.rectype = RECTYPE_TRUST;
850 fingerprint_from_pk (pk, trec.r.trust.fingerprint, &dummy);
851 trec.r.trust.ownertrust = 0;
854 /* locate an existing one */
855 recno = trec.r.trust.validlist;
858 read_record (recno, &vrec, RECTYPE_VALID);
859 if ( !memcmp (vrec.r.valid.namehash, uid->namehash, 20) )
861 recno = vrec.r.valid.next;
864 if (!recno) /* insert a new validity record */
866 memset (&vrec, 0, sizeof vrec);
867 vrec.recnum = tdbio_new_recnum ();
868 vrec.rectype = RECTYPE_VALID;
869 memcpy (vrec.r.valid.namehash, uid->namehash, 20);
870 vrec.r.valid.next = trec.r.trust.validlist;
871 trec.r.trust.validlist = vrec.recnum;
873 vrec.r.valid.validity = validity;
874 vrec.r.valid.full_count = uid->help_full_count;
875 vrec.r.valid.marginal_count = uid->help_marginal_count;
876 write_record (&vrec);
877 trec.r.trust.depth = depth;
878 write_record (&trec);
882 /***********************************************
883 ********* Query trustdb values **************
884 ***********************************************/
886 /* Return true if key is disabled. Note that this is usually used via
887 the pk_is_disabled macro. */
889 tdb_cache_disabled_value (PKT_public_key *pk)
895 if (pk->flags.disabled_valid)
896 return pk->flags.disabled;
900 if (trustdb_args.no_trustdb)
901 return 0; /* No trustdb => not disabled. */
903 err = read_trust_record (pk, &trec);
904 if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
909 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
911 /* No record found, so assume not disabled. */
915 if ((trec.r.trust.ownertrust & TRUST_FLAG_DISABLED))
918 /* Cache it for later so we don't need to look at the trustdb every
920 pk->flags.disabled = disabled;
921 pk->flags.disabled_valid = 1;
929 tdb_check_trustdb_stale (void)
931 static int did_nextcheck=0;
935 if (trustdb_args.no_trustdb)
936 return; /* No trustdb => can't be stale. */
939 && (opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC))
944 scheduled = tdbio_read_nextcheck ();
945 if ((scheduled && scheduled <= make_timestamp ())
946 || pending_check_trustdb)
948 if (opt.no_auto_check_trustdb)
950 pending_check_trustdb = 1;
952 log_info (_("please do a --check-trustdb\n"));
957 log_info (_("checking the trustdb\n"));
965 * Return the validity information for PK. This is the core of
969 tdb_get_validity_core (PKT_public_key *pk, PKT_user_id *uid,
970 PKT_public_key *main_pk)
975 unsigned int validity;
979 /* If we have no trustdb (which also means it has not been created)
980 and the trust-model is always, we don't know the validity -
981 return immediately. If we won't do that the tdbio code would try
982 to open the trustdb and run into a fatal error. */
983 if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
984 return TRUST_UNKNOWN;
986 check_trustdb_stale();
988 if(opt.trust_model==TM_DIRECT)
990 /* Note that this happens BEFORE any user ID stuff is checked.
991 The direct trust model applies to keys as a whole. */
992 validity = tdb_get_ownertrust (main_pk);
996 err = read_trust_record (main_pk, &trec);
997 if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1002 if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1004 /* No record found. */
1005 validity = TRUST_UNKNOWN;
1009 /* Loop over all user IDs */
1010 recno = trec.r.trust.validlist;
1014 read_record (recno, &vrec, RECTYPE_VALID);
1018 /* If a user ID is given we return the validity for that
1019 user ID ONLY. If the namehash is not found, then there
1020 is no validity at all (i.e. the user ID wasn't
1022 if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1024 validity=(vrec.r.valid.validity & TRUST_MASK);
1030 /* If no namehash is given, we take the maximum validity
1031 over all user IDs */
1032 if ( validity < (vrec.r.valid.validity & TRUST_MASK) )
1033 validity = (vrec.r.valid.validity & TRUST_MASK);
1036 recno = vrec.r.valid.next;
1039 if ( (trec.r.trust.ownertrust & TRUST_FLAG_DISABLED) )
1041 validity |= TRUST_FLAG_DISABLED;
1042 pk->flags.disabled = 1;
1045 pk->flags.disabled = 0;
1046 pk->flags.disabled_valid = 1;
1049 if (pending_check_trustdb)
1050 validity |= TRUST_FLAG_PENDING_CHECK;
1057 get_validity_counts (PKT_public_key *pk, PKT_user_id *uid)
1059 TRUSTREC trec, vrec;
1062 if(pk==NULL || uid==NULL)
1065 namehash_from_uid(uid);
1067 uid->help_marginal_count=uid->help_full_count=0;
1071 if(read_trust_record (pk, &trec))
1074 /* loop over all user IDs */
1075 recno = trec.r.trust.validlist;
1078 read_record (recno, &vrec, RECTYPE_VALID);
1080 if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1082 uid->help_marginal_count=vrec.r.valid.marginal_count;
1083 uid->help_full_count=vrec.r.valid.full_count;
1084 /* es_printf("Fetched marginal %d, full %d\n",uid->help_marginal_count,uid->help_full_count); */
1088 recno = vrec.r.valid.next;
1093 list_trust_path( const char *username )
1099 * Enumerate all keys, which are needed to build all trust paths for
1100 * the given key. This function does not return the key itself or
1101 * the ultimate key (the last point in cerificate chain). Only
1102 * certificate chains which ends up at an ultimately trusted key
1103 * are listed. If ownertrust or validity is not NULL, the corresponding
1104 * value for the returned LID is also returned in these variable(s).
1106 * 1) create a void pointer and initialize it to NULL
1107 * 2) pass this void pointer by reference to this function.
1108 * Set lid to the key you want to enumerate and pass it by reference.
1109 * 3) call this function as long as it does not return -1
1110 * to indicate EOF. LID does contain the next key used to build the web
1111 * 4) Always call this function a last time with LID set to NULL,
1112 * so that it can free its context.
1114 * Returns: -1 on EOF or the level of the returned LID
1117 enum_cert_paths( void **context, ulong *lid,
1118 unsigned *ownertrust, unsigned *validity )
1129 * Print the current path
1132 enum_cert_paths_print (void **context, FILE *fp,
1133 int refresh, ulong selected_lid)
1143 /****************************************
1144 *********** NEW NEW NEW ****************
1145 ****************************************/
1148 ask_ownertrust (u32 *kid,int minimum)
1154 pk = xmalloc_clear (sizeof *pk);
1155 rc = get_pubkey (pk, kid);
1158 log_error (_("public key %s not found: %s\n"),
1159 keystr(kid), gpg_strerror (rc) );
1160 return TRUST_UNKNOWN;
1163 if(opt.force_ownertrust)
1165 log_info("force trust for key %s to %s\n",
1166 keystr(kid),trust_value_to_string(opt.force_ownertrust));
1167 tdb_update_ownertrust (pk, opt.force_ownertrust);
1168 ot=opt.force_ownertrust;
1172 ot=edit_ownertrust(pk,0);
1174 ot = tdb_get_ownertrust (pk);
1176 ot = minimum?minimum:TRUST_UNDEFINED;
1181 free_public_key( pk );
1188 mark_keyblock_seen (KeyHashTable tbl, KBNODE node)
1190 for ( ;node; node = node->next )
1191 if (node->pkt->pkttype == PKT_PUBLIC_KEY
1192 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1196 keyid_from_pk (node->pkt->pkt.public_key, aki);
1197 add_key_hash_table (tbl, aki);
1203 dump_key_array (int depth, struct key_array *keys)
1205 struct key_array *kar;
1207 for (kar=keys; kar->keyblock; kar++)
1209 KBNODE node = kar->keyblock;
1212 keyid_from_pk(node->pkt->pkt.public_key, kid);
1213 es_printf ("%d:%08lX%08lX:K::%c::::\n",
1214 depth, (ulong)kid[0], (ulong)kid[1], '?');
1216 for (; node; node = node->next)
1218 if (node->pkt->pkttype == PKT_USER_ID)
1220 int len = node->pkt->pkt.user_id->len;
1224 es_printf ("%d:%08lX%08lX:U:::%c:::",
1225 depth, (ulong)kid[0], (ulong)kid[1],
1226 (node->flag & 4)? 'f':
1227 (node->flag & 2)? 'm':
1228 (node->flag & 1)? 'q':'-');
1229 es_write_sanitized (es_stdout, node->pkt->pkt.user_id->name,
1231 es_putc (':', es_stdout);
1232 es_putc ('\n', es_stdout);
1240 store_validation_status (int depth, KBNODE keyblock, KeyHashTable stored)
1246 for (node=keyblock; node; node = node->next)
1248 if (node->pkt->pkttype == PKT_USER_ID)
1250 PKT_user_id *uid = node->pkt->pkt.user_id;
1252 status = TRUST_FULLY;
1253 else if (node->flag & 2)
1254 status = TRUST_MARGINAL;
1255 else if (node->flag & 1)
1256 status = TRUST_UNDEFINED;
1262 update_validity (keyblock->pkt->pkt.public_key,
1263 uid, depth, status);
1265 mark_keyblock_seen(stored,keyblock);
1277 /* Returns a sanitized copy of the regexp (which might be "", but not
1279 #ifndef DISABLE_REGEX
1281 sanitize_regexp(const char *old)
1283 size_t start=0,len=strlen(old),idx=0;
1284 int escaped=0,standard_bracket=0;
1285 char *new=xmalloc((len*2)+1); /* enough to \-escape everything if we
1288 /* There are basically two commonly-used regexps here. GPG and most
1289 versions of PGP use "<[^>]+[@.]example\.com>$" and PGP (9)
1290 command line uses "example.com" (i.e. whatever the user specfies,
1291 and we can't expect users know to use "\." instead of "."). So
1292 here are the rules: we're allowed to start with "<[^>]+[@.]" and
1293 end with ">$" or start and end with nothing. In between, the
1294 only legal regex character is ".", and everything else gets
1295 escaped. Part of the gotcha here is that some regex packages
1296 allow more than RFC-4880 requires. For example, 4880 has no "{}"
1297 operator, but GNU regex does. Commenting removes these operators
1298 from consideration. A possible future enhancement is to use
1299 commenting to effectively back off a given regex to the Henry
1300 Spencer syntax in 4880. -dshaw */
1302 /* Are we bracketed between "<[^>]+[@.]" and ">$" ? */
1303 if(len>=12 && strncmp(old,"<[^>]+[@.]",10)==0
1304 && old[len-2]=='>' && old[len-1]=='$')
1306 strcpy(new,"<[^>]+[@.]");
1313 /* Walk the remaining characters and ensure that everything that is
1314 left is not an operational regex character. */
1315 for(;start<len;start++)
1317 if(!escaped && old[start]=='\\')
1319 else if(!escaped && old[start]!='.')
1324 new[idx++]=old[start];
1329 /* Note that the (sub)string we look at might end with a bare "\".
1330 If it does, leave it that way. If the regexp actually ended with
1331 ">$", then it was escaping the ">" and is fine. If the regexp
1332 actually ended with the bare "\", then it's an illegal regexp and
1333 regcomp should kick it out. */
1335 if(standard_bracket)
1340 #endif /*!DISABLE_REGEX*/
1342 /* Used by validate_one_keyblock to confirm a regexp within a trust
1343 signature. Returns 1 for match, and 0 for no match or regex
1346 check_regexp(const char *expr,const char *string)
1348 #ifdef DISABLE_REGEX
1351 /* When DISABLE_REGEX is defined, assume all regexps do not
1358 regexp=sanitize_regexp(expr);
1361 ret=riscos_check_regexp(expr, string, DBG_TRUST);
1366 ret=regcomp(&pat,regexp,REG_ICASE|REG_NOSUB|REG_EXTENDED);
1369 ret=regexec(&pat,string,0,NULL,0);
1377 log_debug("regexp '%s' ('%s') on '%s': %s\n",
1378 regexp,expr,string,ret==0?"YES":"NO");
1387 * Return true if the key is signed by one of the keys in the given
1388 * key ID list. User IDs with a valid signature are marked by node
1390 * flag bit 0: There is at least one signature
1391 * 1: There is marginal confidence that this is a legitimate uid
1392 * 2: There is full confidence that this is a legitimate uid.
1393 * 8: Used for internal purposes.
1394 * 9: Ditto (in mark_usable_uid_certs())
1396 * This function assumes that all kbnode flags are cleared on entry.
1399 validate_one_keyblock (KBNODE kb, struct key_item *klist,
1400 u32 curtime, u32 *next_expire)
1402 struct key_item *kr;
1403 KBNODE node, uidnode=NULL;
1404 PKT_user_id *uid=NULL;
1405 PKT_public_key *pk = kb->pkt->pkt.public_key;
1407 int issigned=0, any_signed = 0;
1409 keyid_from_pk(pk, main_kid);
1410 for (node=kb; node; node = node->next)
1412 /* A bit of discussion here: is it better for the web of trust
1413 to be built among only self-signed uids? On the one hand, a
1414 self-signed uid is a statement that the key owner definitely
1415 intended that uid to be there, but on the other hand, a
1416 signed (but not self-signed) uid does carry trust, of a sort,
1417 even if it is a statement being made by people other than the
1418 key owner "through" the uids on the key owner's key. I'm
1419 going with the latter. However, if the user ID was
1420 explicitly revoked, or passively allowed to expire, that
1421 should stop validity through the user ID until it is
1424 if (node->pkt->pkttype == PKT_USER_ID
1425 && !node->pkt->pkt.user_id->is_revoked
1426 && !node->pkt->pkt.user_id->is_expired)
1428 if (uidnode && issigned)
1430 if (uid->help_full_count >= opt.completes_needed
1431 || uid->help_marginal_count >= opt.marginals_needed )
1433 else if (uid->help_full_count || uid->help_marginal_count)
1439 uid=uidnode->pkt->pkt.user_id;
1441 /* If the selfsig is going to expire... */
1442 if(uid->expiredate && uid->expiredate<*next_expire)
1443 *next_expire = uid->expiredate;
1446 get_validity_counts(pk,uid);
1447 mark_usable_uid_certs (kb, uidnode, main_kid, klist,
1448 curtime, next_expire);
1450 else if (node->pkt->pkttype == PKT_SIGNATURE
1451 && (node->flag & (1<<8)) && uid)
1453 /* Note that we are only seeing unrevoked sigs here */
1454 PKT_signature *sig = node->pkt->pkt.signature;
1456 kr = is_in_klist (klist, sig);
1457 /* If the trust_regexp does not match, it's as if the sig
1458 did not exist. This is safe for non-trust sigs as well
1459 since we don't accept a regexp on the sig unless it's a
1461 if (kr && (!kr->trust_regexp
1462 || opt.trust_model != TM_PGP
1464 && check_regexp(kr->trust_regexp,
1465 uidnode->pkt->pkt.user_id->name))))
1467 /* Are we part of a trust sig chain? We always favor
1468 the latest trust sig, rather than the greater or
1469 lesser trust sig or value. I could make a decent
1470 argument for any of these cases, but this seems to be
1471 what PGP does, and I'd like to be compatible. -dms */
1472 if (opt.trust_model == TM_PGP
1474 && pk->trust_timestamp <= sig->timestamp)
1476 unsigned char depth;
1478 /* If the depth on the signature is less than the
1479 chain currently has, then use the signature depth
1480 so we don't increase the depth beyond what the
1481 signer wanted. If the depth on the signature is
1482 more than the chain currently has, then use the
1483 chain depth so we use as much of the signature
1484 depth as the chain will permit. An ultimately
1485 trusted signature can restart the depth to
1486 whatever level it likes. */
1488 if (sig->trust_depth < kr->trust_depth
1489 || kr->ownertrust == TRUST_ULTIMATE)
1490 depth = sig->trust_depth;
1492 depth = kr->trust_depth;
1497 log_debug ("trust sig on %s, sig depth is %d,"
1498 " kr depth is %d\n",
1499 uidnode->pkt->pkt.user_id->name,
1503 /* If we got here, we know that:
1505 this is a trust sig.
1507 it's a newer trust sig than any previous trust
1508 sig on this key (not uid).
1510 it is legal in that it was either generated by an
1511 ultimate key, or a key that was part of a trust
1512 chain, and the depth does not violate the
1515 if there is a regexp attached, it matched
1520 log_debug ("replacing trust value %d with %d and "
1521 "depth %d with %d\n",
1522 pk->trust_value,sig->trust_value,
1523 pk->trust_depth,depth);
1525 pk->trust_value = sig->trust_value;
1526 pk->trust_depth = depth-1;
1528 /* If the trust sig contains a regexp, record it
1529 on the pk for the next round. */
1530 if (sig->trust_regexp)
1531 pk->trust_regexp = sig->trust_regexp;
1535 if (kr->ownertrust == TRUST_ULTIMATE)
1536 uid->help_full_count = opt.completes_needed;
1537 else if (kr->ownertrust == TRUST_FULLY)
1538 uid->help_full_count++;
1539 else if (kr->ownertrust == TRUST_MARGINAL)
1540 uid->help_marginal_count++;
1546 if (uidnode && issigned)
1548 if (uid->help_full_count >= opt.completes_needed
1549 || uid->help_marginal_count >= opt.marginals_needed )
1551 else if (uid->help_full_count || uid->help_marginal_count)
1562 search_skipfnc (void *opaque, u32 *kid, PKT_user_id *dummy)
1565 return test_key_hash_table ((KeyHashTable)opaque, kid);
1570 * Scan all keys and return a key_array of all suitable keys from
1571 * kllist. The caller has to pass keydb handle so that we don't use
1572 * to create our own. Returns either a key_array or NULL in case of
1573 * an error. No results found are indicated by an empty array.
1574 * Caller hast to release the returned array.
1576 static struct key_array *
1577 validate_key_list (KEYDB_HANDLE hd, KeyHashTable full_trust,
1578 struct key_item *klist, u32 curtime, u32 *next_expire)
1580 KBNODE keyblock = NULL;
1581 struct key_array *keys = NULL;
1582 size_t nkeys, maxkeys;
1584 KEYDB_SEARCH_DESC desc;
1587 keys = xmalloc ((maxkeys+1) * sizeof *keys);
1590 rc = keydb_search_reset (hd);
1593 log_error ("keydb_search_reset failed: %s\n", gpg_strerror (rc));
1598 memset (&desc, 0, sizeof desc);
1599 desc.mode = KEYDB_SEARCH_MODE_FIRST;
1600 desc.skipfnc = search_skipfnc;
1601 desc.skipfncvalue = full_trust;
1602 rc = keydb_search (hd, &desc, 1, NULL);
1603 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1605 keys[nkeys].keyblock = NULL;
1610 log_error ("keydb_search_first failed: %s\n", gpg_strerror (rc));
1615 desc.mode = KEYDB_SEARCH_MODE_NEXT; /* change mode */
1620 if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY)
1623 rc = keydb_get_keyblock (hd, &keyblock);
1626 log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1631 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1633 log_debug ("ooops: invalid pkttype %d encountered\n",
1634 keyblock->pkt->pkttype);
1635 dump_kbnode (keyblock);
1636 release_kbnode(keyblock);
1640 /* prepare the keyblock for further processing */
1641 merge_keys_and_selfsig (keyblock);
1642 clear_kbnode_flags (keyblock);
1643 pk = keyblock->pkt->pkt.public_key;
1644 if (pk->has_expired || pk->flags.revoked)
1646 /* it does not make sense to look further at those keys */
1647 mark_keyblock_seen (full_trust, keyblock);
1649 else if (validate_one_keyblock (keyblock, klist, curtime, next_expire))
1653 if (pk->expiredate && pk->expiredate >= curtime
1654 && pk->expiredate < *next_expire)
1655 *next_expire = pk->expiredate;
1657 if (nkeys == maxkeys) {
1659 keys = xrealloc (keys, (maxkeys+1) * sizeof *keys);
1661 keys[nkeys++].keyblock = keyblock;
1663 /* Optimization - if all uids are fully trusted, then we
1664 never need to consider this key as a candidate again. */
1666 for (node=keyblock; node; node = node->next)
1667 if (node->pkt->pkttype == PKT_USER_ID && !(node->flag & 4))
1671 mark_keyblock_seen (full_trust, keyblock);
1676 release_kbnode (keyblock);
1679 while (!(rc = keydb_search (hd, &desc, 1, NULL))
1680 || gpg_err_code (rc) == GPG_ERR_LEGACY_KEY);
1682 if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
1684 log_error ("keydb_search_next failed: %s\n", gpg_strerror (rc));
1689 keys[nkeys].keyblock = NULL;
1693 /* Caller must sync */
1695 reset_trust_records(void)
1699 int count = 0, nreset = 0;
1701 for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
1703 if(rec.rectype==RECTYPE_TRUST)
1706 if(rec.r.trust.min_ownertrust)
1708 rec.r.trust.min_ownertrust=0;
1713 else if(rec.rectype==RECTYPE_VALID
1714 && ((rec.r.valid.validity&TRUST_MASK)
1715 || rec.r.valid.marginal_count
1716 || rec.r.valid.full_count))
1718 rec.r.valid.validity &= ~TRUST_MASK;
1719 rec.r.valid.marginal_count=rec.r.valid.full_count=0;
1727 log_info (_("%d keys processed (%d validity counts cleared)\n"),
1732 * Run the key validation procedure.
1734 * This works this way:
1735 * Step 1: Find all ultimately trusted keys (UTK).
1736 * mark them all as seen and put them into klist.
1737 * Step 2: loop max_cert_times
1738 * Step 3: if OWNERTRUST of any key in klist is undefined
1739 * ask user to assign ownertrust
1740 * Step 4: Loop over all keys in the keyDB which are not marked seen
1741 * Step 5: if key is revoked or expired
1743 * continue loop at Step 4
1744 * Step 6: For each user ID of that key signed by a key in klist
1745 * Calculate validity by counting trusted signatures.
1746 * Set validity of user ID
1747 * Step 7: If any signed user ID was found
1750 * Step 8: Build a new klist from all fully trusted keys from step 6
1756 validate_keys (int interactive)
1760 struct key_item *klist = NULL;
1762 struct key_array *keys = NULL;
1763 struct key_array *kar;
1764 KEYDB_HANDLE kdb = NULL;
1767 int ot_unknown, ot_undefined, ot_never, ot_marginal, ot_full, ot_ultimate;
1768 KeyHashTable stored,used,full_trust;
1769 u32 start_time, next_expire;
1771 /* Make sure we have all sigs cached. TODO: This is going to
1772 require some architectual re-thinking, as it is agonizingly slow.
1773 Perhaps combine this with reset_trust_records(), or only check
1774 the caches on keys that are actually involved in the web of
1776 keydb_rebuild_caches(0);
1778 start_time = make_timestamp ();
1779 next_expire = 0xffffffff; /* set next expire to the year 2106 */
1780 stored = new_key_hash_table ();
1781 used = new_key_hash_table ();
1782 full_trust = new_key_hash_table ();
1785 reset_trust_records();
1787 /* Fixme: Instead of always building a UTK list, we could just build it
1788 * here when needed */
1792 log_info (_("no ultimately trusted keys found\n"));
1796 /* mark all UTKs as used and fully_trusted and set validity to
1798 for (k=utk_list; k; k = k->next)
1803 keyblock = get_pubkeyblock (k->kid);
1806 log_error (_("public key of ultimately"
1807 " trusted key %s not found\n"), keystr(k->kid));
1810 mark_keyblock_seen (used, keyblock);
1811 mark_keyblock_seen (stored, keyblock);
1812 mark_keyblock_seen (full_trust, keyblock);
1813 pk = keyblock->pkt->pkt.public_key;
1814 for (node=keyblock; node; node = node->next)
1816 if (node->pkt->pkttype == PKT_USER_ID)
1817 update_validity (pk, node->pkt->pkt.user_id, 0, TRUST_ULTIMATE);
1819 if ( pk->expiredate && pk->expiredate >= start_time
1820 && pk->expiredate < next_expire)
1821 next_expire = pk->expiredate;
1823 release_kbnode (keyblock);
1829 log_info(_("%d marginal(s) needed, %d complete(s) needed, %s trust model\n"),
1830 opt.marginals_needed,opt.completes_needed,trust_model_string());
1832 for (depth=0; depth < opt.max_cert_depth; depth++)
1834 int valids=0,key_count;
1835 /* See whether we should assign ownertrust values to the keys in
1837 ot_unknown = ot_undefined = ot_never = 0;
1838 ot_marginal = ot_full = ot_ultimate = 0;
1839 for (k=klist; k; k = k->next)
1843 /* 120 and 60 are as per RFC2440 */
1844 if(k->trust_value>=120)
1846 else if(k->trust_value>=60)
1849 if(min!=k->min_ownertrust)
1850 update_min_ownertrust(k->kid,min);
1852 if (interactive && k->ownertrust == TRUST_UNKNOWN)
1854 k->ownertrust = ask_ownertrust (k->kid,min);
1856 if (k->ownertrust == (unsigned int)(-1))
1863 /* This can happen during transition from an old trustdb
1864 before trust sigs. It can also happen if a user uses two
1865 different versions of GnuPG or changes the --trust-model
1867 if(k->ownertrust<min)
1870 log_debug("key %08lX%08lX:"
1871 " overriding ownertrust '%s' with '%s'\n",
1872 (ulong)k->kid[0],(ulong)k->kid[1],
1873 trust_value_to_string(k->ownertrust),
1874 trust_value_to_string(min));
1879 if (k->ownertrust == TRUST_UNKNOWN)
1881 else if (k->ownertrust == TRUST_UNDEFINED)
1883 else if (k->ownertrust == TRUST_NEVER)
1885 else if (k->ownertrust == TRUST_MARGINAL)
1887 else if (k->ownertrust == TRUST_FULLY)
1889 else if (k->ownertrust == TRUST_ULTIMATE)
1895 /* Find all keys which are signed by a key in kdlist */
1896 keys = validate_key_list (kdb, full_trust, klist,
1897 start_time, &next_expire);
1900 log_error ("validate_key_list failed\n");
1901 rc = GPG_ERR_GENERAL;
1905 for (key_count=0, kar=keys; kar->keyblock; kar++, key_count++)
1908 /* Store the calculated valididation status somewhere */
1909 if (opt.verbose > 1 && DBG_TRUST)
1910 dump_key_array (depth, keys);
1912 for (kar=keys; kar->keyblock; kar++)
1913 store_validation_status (depth, kar->keyblock, stored);
1915 log_info (_("depth: %d valid: %3d signed: %3d"
1916 " trust: %d-, %dq, %dn, %dm, %df, %du\n"),
1917 depth, valids, key_count, ot_unknown, ot_undefined,
1918 ot_never, ot_marginal, ot_full, ot_ultimate );
1920 /* Build a new kdlist from all fully valid keys in KEYS */
1921 if (klist != utk_list)
1922 release_key_items (klist);
1924 for (kar=keys; kar->keyblock; kar++)
1926 for (node=kar->keyblock; node; node = node->next)
1928 if (node->pkt->pkttype == PKT_USER_ID && (node->flag & 4))
1932 /* have we used this key already? */
1933 keyid_from_pk (kar->keyblock->pkt->pkt.public_key, kid);
1934 if(test_key_hash_table(used,kid)==0)
1936 /* Normally we add both the primary and subkey
1937 ids to the hash via mark_keyblock_seen, but
1938 since we aren't using this hash as a skipfnc,
1939 that doesn't matter here. */
1940 add_key_hash_table (used,kid);
1941 k = new_key_item ();
1946 (kar->keyblock->pkt->pkt.public_key) & TRUST_MASK);
1947 k->min_ownertrust = tdb_get_min_ownertrust
1948 (kar->keyblock->pkt->pkt.public_key);
1950 kar->keyblock->pkt->pkt.public_key->trust_depth;
1952 kar->keyblock->pkt->pkt.public_key->trust_value;
1953 if(kar->keyblock->pkt->pkt.public_key->trust_regexp)
1955 xstrdup(kar->keyblock->pkt->
1956 pkt.public_key->trust_regexp);
1964 release_key_array (keys);
1967 break; /* no need to dive in deeper */
1971 keydb_release (kdb);
1972 release_key_array (keys);
1973 release_key_items (klist);
1974 release_key_hash_table (full_trust);
1975 release_key_hash_table (used);
1976 release_key_hash_table (stored);
1977 if (!rc && !quit) /* mark trustDB as checked */
1979 if (next_expire == 0xffffffff || next_expire < start_time )
1980 tdbio_write_nextcheck (0);
1983 tdbio_write_nextcheck (next_expire);
1984 log_info (_("next trustdb check due at %s\n"),
1985 strtimestamp (next_expire));
1988 if(tdbio_update_version_record()!=0)
1990 log_error(_("unable to update trustdb version record: "
1991 "write failed: %s\n"), gpg_strerror (rc));
1996 pending_check_trustdb = 0;