1 /* tofu.c - TOFU trust model.
2 * Copyright (C) 2015, 2016 g10 Code GmbH
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <https://www.gnu.org/licenses/>.
22 - Format the fingerprints nicely when printing (similar to gpg
36 #include "stringhelp.h"
38 #include "mbox-util.h"
50 #define CONTROL_L ('L' - 'A' + 1)
52 /* Number of days with signed / ecnrypted messages required to
53 * indicate that enough history is available for basic trust. */
54 #define BASIC_TRUST_THRESHOLD 4
55 /* Number of days with signed / encrypted messages required to
56 * indicate that a lot of history is available. */
57 #define FULL_TRUST_THRESHOLD 21
60 /* A struct with data pertaining to the tofu DB. There is one such
61 struct per session and it is cached in session's ctrl structure.
62 To initialize this or get the current singleton, call opendbs().
63 There is no need to explicitly release it; cleanup is done when the
64 CTRL object is released. */
69 time_t want_lock_file_ctime;
73 sqlite3_stmt *savepoint_batch;
74 sqlite3_stmt *savepoint_batch_commit;
76 sqlite3_stmt *record_binding_get_old_policy;
77 sqlite3_stmt *record_binding_update;
78 sqlite3_stmt *get_policy_select_policy_and_conflict;
79 sqlite3_stmt *get_trust_bindings_with_this_email;
80 sqlite3_stmt *get_trust_gather_other_user_ids;
81 sqlite3_stmt *get_trust_gather_signature_stats;
82 sqlite3_stmt *get_trust_gather_encryption_stats;
83 sqlite3_stmt *register_already_seen;
84 sqlite3_stmt *register_signature;
85 sqlite3_stmt *register_encryption;
88 int in_batch_transaction;
90 time_t batch_update_started;
94 #define STRINGIFY(s) STRINGIFY2(s)
95 #define STRINGIFY2(s) #s
97 /* The grouping parameters when collecting signature statistics. */
99 /* If a message is signed a couple of hours in the future, just assume
101 #define TIME_AGO_FUTURE_IGNORE (2 * 60 * 60)
103 #define TIME_AGO_UNIT_SMALL (24 * 60 * 60)
104 #define TIME_AGO_SMALL_THRESHOLD (7 * TIME_AGO_UNIT_SMALL)
106 #define TIME_AGO_UNIT_MEDIUM (30 * 24 * 60 * 60)
107 #define TIME_AGO_MEDIUM_THRESHOLD (2 * TIME_AGO_UNIT_MEDIUM)
109 #define TIME_AGO_UNIT_LARGE (365 * 24 * 60 * 60)
110 #define TIME_AGO_LARGE_THRESHOLD (2 * TIME_AGO_UNIT_LARGE)
112 /* Local prototypes. */
113 static gpg_error_t end_transaction (ctrl_t ctrl, int only_batch);
114 static char *email_from_user_id (const char *user_id);
115 static int show_statistics (tofu_dbs_t dbs,
116 const char *fingerprint, const char *email,
117 enum tofu_policy policy,
118 estream_t outfp, int only_status_fd, time_t now);
121 tofu_policy_str (enum tofu_policy policy)
125 case TOFU_POLICY_NONE: return "none";
126 case TOFU_POLICY_AUTO: return "auto";
127 case TOFU_POLICY_GOOD: return "good";
128 case TOFU_POLICY_UNKNOWN: return "unknown";
129 case TOFU_POLICY_BAD: return "bad";
130 case TOFU_POLICY_ASK: return "ask";
131 default: return "???";
135 /* Convert a binding policy (e.g., TOFU_POLICY_BAD) to a trust level
136 (e.g., TRUST_BAD) in light of the current configuration. */
138 tofu_policy_to_trust_level (enum tofu_policy policy)
140 if (policy == TOFU_POLICY_AUTO)
141 /* If POLICY is AUTO, fallback to OPT.TOFU_DEFAULT_POLICY. */
142 policy = opt.tofu_default_policy;
146 case TOFU_POLICY_AUTO:
147 /* If POLICY and OPT.TOFU_DEFAULT_POLICY are both AUTO, default
148 to marginal trust. */
149 return TRUST_MARGINAL;
150 case TOFU_POLICY_GOOD:
152 case TOFU_POLICY_UNKNOWN:
153 return TRUST_UNKNOWN;
154 case TOFU_POLICY_BAD:
156 case TOFU_POLICY_ASK:
157 return TRUST_UNKNOWN;
159 log_bug ("Bad value for trust policy: %d\n",
160 opt.tofu_default_policy);
167 /* Start a transaction on DB. If ONLY_BATCH is set, then this will
168 start a batch transaction if we haven't started a batch transaction
169 and one has been requested. */
171 begin_transaction (ctrl_t ctrl, int only_batch)
173 tofu_dbs_t dbs = ctrl->tofu.dbs;
179 /* If we've been in batch update mode for a while (on average, more
180 * than 500 ms), to prevent starving other gpg processes, we drop
181 * and retake the batch lock.
183 * Note: gnupg_get_time has a one second resolution, if we wanted a
184 * higher resolution, we could use npth_clock_gettime. */
185 if (/* No real transactions. */
186 dbs->in_transaction == 0
187 /* There is an open batch transaction. */
188 && dbs->in_batch_transaction
189 /* And some time has gone by since it was started. */
190 && dbs->batch_update_started != gnupg_get_time ())
194 /* If we are in a batch update, then batch updates better have
196 log_assert (ctrl->tofu.batch_updated_wanted);
198 /* Check if another process wants to run. (We just ignore any
199 * stat failure. A waiter might have to wait a bit longer, but
200 * otherwise there should be no impact.) */
201 if (stat (dbs->want_lock_file, &statbuf) == 0
202 && statbuf.st_ctime != dbs->want_lock_file_ctime)
204 end_transaction (ctrl, 2);
206 /* Yield to allow another process a chance to run. Note:
207 * testing suggests that anything less than a 100ms tends to
208 * not result in the other process getting the lock. */
209 gnupg_usleep (100000);
212 dbs->batch_update_started = gnupg_get_time ();
215 if (/* We don't have an open batch transaction. */
216 !dbs->in_batch_transaction
217 && (/* Batch mode is enabled or we are starting a new transaction. */
218 ctrl->tofu.batch_updated_wanted || dbs->in_transaction == 0))
222 /* We are in batch mode, but we don't have an open batch
223 * transaction. Since the batch save point must be the outer
224 * save point, it must be taken before the inner save point. */
225 log_assert (dbs->in_transaction == 0);
227 rc = gpgsql_stepx (dbs->db, &dbs->s.savepoint_batch,
229 "begin immediate transaction;", GPGSQL_ARG_END);
232 log_error (_("error beginning transaction on TOFU database: %s\n"),
235 return gpg_error (GPG_ERR_GENERAL);
238 dbs->in_batch_transaction = 1;
239 dbs->batch_update_started = gnupg_get_time ();
241 if (stat (dbs->want_lock_file, &statbuf) == 0)
242 dbs->want_lock_file_ctime = statbuf.st_ctime;
248 log_assert (dbs->in_transaction >= 0);
249 dbs->in_transaction ++;
251 rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
252 "savepoint inner%d;",
253 dbs->in_transaction);
256 log_error (_("error beginning transaction on TOFU database: %s\n"),
259 return gpg_error (GPG_ERR_GENERAL);
266 /* Commit a transaction. If ONLY_BATCH is 1, then this only ends the
267 * batch transaction if we have left batch mode. If ONLY_BATCH is 2,
268 * this commits any open batch transaction even if we are still in
271 end_transaction (ctrl_t ctrl, int only_batch)
273 tofu_dbs_t dbs = ctrl->tofu.dbs;
277 if (only_batch || (! only_batch && dbs->in_transaction == 1))
280 return 0; /* Shortcut to allow for easier cleanup code. */
282 /* If we are releasing the batch transaction, then we better not
283 be in a normal transaction. */
285 log_assert (dbs->in_transaction == 0);
287 if (/* Batch mode disabled? */
288 (!ctrl->tofu.batch_updated_wanted || only_batch == 2)
289 /* But, we still have an open batch transaction? */
290 && dbs->in_batch_transaction)
292 /* The batch transaction is still in open, but we've left
294 dbs->in_batch_transaction = 0;
295 dbs->in_transaction = 0;
297 rc = gpgsql_stepx (dbs->db, &dbs->s.savepoint_batch_commit,
299 "commit transaction;", GPGSQL_ARG_END);
302 log_error (_("error committing transaction on TOFU database: %s\n"),
305 return gpg_error (GPG_ERR_GENERAL);
316 log_assert (dbs->in_transaction > 0);
318 rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
319 "release inner%d;", dbs->in_transaction);
321 dbs->in_transaction --;
325 log_error (_("error committing transaction on TOFU database: %s\n"),
328 return gpg_error (GPG_ERR_GENERAL);
336 rollback_transaction (ctrl_t ctrl)
338 tofu_dbs_t dbs = ctrl->tofu.dbs;
343 log_assert (dbs->in_transaction > 0);
345 /* Be careful to not undo any progress made by closed transactions in
347 rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
348 "rollback to inner%d;",
349 dbs->in_transaction);
351 dbs->in_transaction --;
355 log_error (_("error rolling back transaction on TOFU database: %s\n"),
358 return gpg_error (GPG_ERR_GENERAL);
365 tofu_begin_batch_update (ctrl_t ctrl)
367 ctrl->tofu.batch_updated_wanted ++;
371 tofu_end_batch_update (ctrl_t ctrl)
373 log_assert (ctrl->tofu.batch_updated_wanted > 0);
374 ctrl->tofu.batch_updated_wanted --;
375 end_transaction (ctrl, 1);
378 /* Suspend any extant batch transaction (it is safe to call this even
379 no batch transaction has been started). Note: you cannot suspend a
380 batch transaction if you are in a normal transaction. The batch
381 transaction can be resumed explicitly by calling
382 tofu_resume_batch_transaction or implicitly by starting a normal
385 tofu_suspend_batch_transaction (ctrl_t ctrl)
387 end_transaction (ctrl, 2);
390 /* Resume a batch transaction if there is no extant batch transaction
391 and one has been requested using tofu_begin_batch_transaction. */
393 tofu_resume_batch_transaction (ctrl_t ctrl)
395 begin_transaction (ctrl, 1);
400 /* Wrapper around strtol which prints a warning in case of a
401 * conversion error. On success the converted value is stored at
402 * R_VALUE and 0 is returned; on error FALLBACK is stored at R_VALUE
403 * and an error code is returned. */
405 string_to_long (long *r_value, const char *string, long fallback, int line)
410 gpg_err_set_errno (0);
411 *r_value = strtol (string, &tail, 0);
412 if (errno || !(!strcmp (tail, ".0") || !*tail))
414 err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
415 log_debug ("%s:%d: strtol failed for TOFU DB data; returned string"
416 " (string='%.10s%s'; tail='%.10s%s'): %s\n",
418 string, string && strlen(string) > 10 ? "..." : "",
419 tail, tail && strlen(tail) > 10 ? "..." : "",
430 /* Wrapper around strtoul which prints a warning in case of a
431 * conversion error. On success the converted value is stored at
432 * R_VALUE and 0 is returned; on error FALLBACK is stored at R_VALUE
433 * and an error code is returned. */
435 string_to_ulong (unsigned long *r_value, const char *string,
436 unsigned long fallback, int line)
441 gpg_err_set_errno (0);
442 *r_value = strtoul (string, &tail, 0);
443 if (errno || !(!strcmp (tail, ".0") || !*tail))
445 err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
446 log_debug ("%s:%d: strtoul failed for TOFU DB data; returned string"
447 " (string='%.10s%s'; tail='%.10s%s'): %s\n",
449 string, string && strlen(string) > 10 ? "..." : "",
450 tail, tail && strlen(tail) > 10 ? "..." : "",
462 /* Collect results of a select count (*) ...; style query. Aborts if
463 the argument is not a valid integer (or real of the form X.0). */
465 get_single_unsigned_long_cb (void *cookie, int argc, char **argv,
468 unsigned long int *count = cookie;
472 log_assert (argc == 1);
474 if (string_to_ulong (count, argv[0], 0, __LINE__))
475 return 1; /* Abort. */
480 get_single_unsigned_long_cb2 (void *cookie, int argc, char **argv,
481 char **azColName, sqlite3_stmt *stmt)
484 return get_single_unsigned_long_cb (cookie, argc, argv, azColName);
487 /* We expect a single integer column whose name is "version". COOKIE
488 must point to an int. This function always aborts. On error or a
489 if the version is bad, sets *VERSION to -1. */
491 version_check_cb (void *cookie, int argc, char **argv, char **azColName)
493 int *version = cookie;
495 if (argc != 1 || strcmp (azColName[0], "version") != 0)
501 if (strcmp (argv[0], "1") == 0)
505 log_error (_("unsupported TOFU database version: %s\n"), argv[0]);
509 /* Don't run again. */
514 check_utks (sqlite3 *db)
518 struct key_item *utks;
521 char *utks_string = NULL;
522 char keyid_str[16+1];
523 long utks_unchanged = 0;
525 /* An early version of the v1 format did not include the list of
526 * known ultimately trusted keys.
528 * This list is used to detect when the set of ultimately trusted
529 * keys changes. We need to detect this to invalidate the effective
530 * policy, which can change if an ultimately trusted key is added or
532 rc = sqlite3_exec (db,
533 "create table if not exists ultimately_trusted_keys"
538 log_error (_("error creating 'ultimately_trusted_keys' TOFU table: %s\n"),
546 for (ki = utks, utk_count = 0; ki; ki = ki->next, utk_count ++)
551 /* Build a list of keyids of the form "XXX","YYY","ZZZ". */
552 int len = (1 + 16 + 1 + 1) * utk_count;
555 utks_string = xmalloc (len);
557 for (ki = utks, utk_count = 0; ki; ki = ki->next, utk_count ++)
559 utks_string[o ++] = '\'';
560 format_keyid (ki->kid, KF_LONG,
561 keyid_str, sizeof (keyid_str));
562 memcpy (&utks_string[o], keyid_str, 16);
564 utks_string[o ++] = '\'';
565 utks_string[o ++] = ',';
567 utks_string[o - 1] = 0;
568 log_assert (o == len);
571 rc = gpgsql_exec_printf
572 (db, get_single_unsigned_long_cb, &utks_unchanged, &err,
574 /* Removed UTKs? (Known UTKs in current UTKs.) */
575 " ((select count(*) from ultimately_trusted_keys"
576 " where (keyid in (%s))) == %d)"
579 " ((select count(*) from ultimately_trusted_keys"
580 " where keyid not in (%s)) == 0);",
581 utks_string ? utks_string : "",
583 utks_string ? utks_string : "");
587 log_error (_("TOFU DB error"));
588 print_further_info ("checking if ultimately trusted keys changed: %s",
598 log_debug ("TOFU: ultimately trusted keys changed.\n");
600 /* Given that the set of ultimately trusted keys
601 * changed, clear any cached policies. */
602 rc = gpgsql_exec_printf
603 (db, NULL, NULL, &err,
604 "update bindings set effective_policy = %d;",
608 log_error (_("TOFU DB error"));
609 print_further_info ("clearing cached policies: %s", err);
614 /* Now, update the UTK table. */
615 rc = sqlite3_exec (db,
616 "drop table ultimately_trusted_keys;",
620 log_error (_("TOFU DB error"));
621 print_further_info ("dropping ultimately_trusted_keys: %s", err);
626 rc = sqlite3_exec (db,
627 "create table if not exists"
628 " ultimately_trusted_keys (keyid);\n",
632 log_error (_("TOFU DB error"));
633 print_further_info ("creating ultimately_trusted_keys: %s", err);
638 for (ki = utks; ki; ki = ki->next)
640 format_keyid (ki->kid, KF_LONG,
641 keyid_str, sizeof (keyid_str));
642 rc = gpgsql_exec_printf
643 (db, NULL, NULL, &err,
644 "insert into ultimately_trusted_keys values ('%s');",
648 log_error (_("TOFU DB error"));
649 print_further_info ("updating ultimately_trusted_keys: %s",
660 /* If the DB is new, initialize it. Otherwise, check the DB's
663 Return 0 if the database is okay and 1 otherwise. */
669 unsigned long int count;
672 rc = sqlite3_exec (db, "begin transaction;", NULL, NULL, &err);
675 log_error (_("error beginning transaction on TOFU database: %s\n"),
681 /* If the DB has no tables, then assume this is a new DB that needs
682 to be initialized. */
683 rc = sqlite3_exec (db,
684 "select count(*) from sqlite_master where type='table';",
685 get_single_unsigned_long_cb, &count, &err);
688 log_error (_("error reading TOFU database: %s\n"), err);
689 print_further_info ("query available tables");
694 /* Assume that the DB is already initialized. Make sure the
697 rc = sqlite3_exec (db, "select version from version;", version_check_cb,
699 if (rc == SQLITE_ABORT && version == 1)
700 /* Happy, happy, joy, joy. */
706 else if (rc == SQLITE_ABORT && version == -1)
707 /* Unsupported version. */
709 /* An error message was already displayed. */
716 log_error (_("error determining TOFU database's version: %s\n"), err);
722 /* Unexpected success. This can only happen if there are no
723 rows. (select returned 0, but expected ABORT.) */
724 log_error (_("error determining TOFU database's version: %s\n"),
725 gpg_strerror (GPG_ERR_NO_DATA));
731 /* Create the version table. */
732 rc = sqlite3_exec (db,
733 "create table version (version INTEGER);",
737 log_error (_("error initializing TOFU database: %s\n"), err);
738 print_further_info ("create version");
743 /* Initialize the version table, which contains a single integer
745 rc = sqlite3_exec (db,
746 "insert into version values (1);",
750 log_error (_("error initializing TOFU database: %s\n"), err);
751 print_further_info ("insert version");
756 /* The list of <fingerprint, email> bindings and auxiliary data.
758 * OID is a unique ID identifying this binding (and used by the
759 * signatures table, see below). Note: OIDs will never be
762 * FINGERPRINT: The key's fingerprint.
764 * EMAIL: The normalized email address.
766 * USER_ID: The unmodified user id from which EMAIL was extracted.
768 * TIME: The time this binding was first observed.
770 * POLICY: The trust policy (TOFU_POLICY_BAD, etc. as an integer).
772 * CONFLICT is either NULL or a fingerprint. Assume that we have
773 * a binding <0xdeadbeef, foo@example.com> and then we observe
774 * <0xbaddecaf, foo@example.com>. There two bindings conflict
775 * (they have the same email address). When we observe the
776 * latter binding, we warn the user about the conflict and ask
777 * for a policy decision about the new binding. We also change
778 * the old binding's policy to ask if it was auto. So that we
779 * know why this occurred, we also set conflict to 0xbaddecaf.
781 rc = gpgsql_exec_printf
782 (db, NULL, NULL, &err,
783 "create table bindings\n"
784 " (oid INTEGER PRIMARY KEY AUTOINCREMENT,\n"
785 " fingerprint TEXT, email TEXT, user_id TEXT, time INTEGER,\n"
786 " policy INTEGER CHECK (policy in (%d, %d, %d, %d, %d)),\n"
787 " conflict STRING,\n"
788 " unique (fingerprint, email));\n"
789 "create index bindings_fingerprint_email\n"
790 " on bindings (fingerprint, email);\n"
791 "create index bindings_email on bindings (email);\n",
792 TOFU_POLICY_AUTO, TOFU_POLICY_GOOD, TOFU_POLICY_UNKNOWN,
793 TOFU_POLICY_BAD, TOFU_POLICY_ASK);
796 log_error (_("error initializing TOFU database: %s\n"), err);
797 print_further_info ("create bindings");
802 /* The signatures that we have observed.
804 * BINDING refers to a record in the bindings table, which
805 * describes the binding (i.e., this is a foreign key that
806 * references bindings.oid).
808 * SIG_DIGEST is the digest stored in the signature.
810 * SIG_TIME is the timestamp stored in the signature.
812 * ORIGIN is a free-form string that describes who fed this
813 * signature to GnuPG (e.g., email:claws).
815 * TIME is the time this signature was registered. */
816 rc = sqlite3_exec (db,
817 "create table signatures "
818 " (binding INTEGER NOT NULL, sig_digest TEXT,"
819 " origin TEXT, sig_time INTEGER, time INTEGER,"
820 " primary key (binding, sig_digest, origin));",
824 log_error (_("error initializing TOFU database: %s\n"), err);
825 print_further_info ("create signatures");
833 /* Early version of the v1 format did not include the encryption
835 rc = sqlite3_exec (db,
836 "create table if not exists encryptions"
837 " (binding INTEGER NOT NULL,"
839 "create index if not exists encryptions_binding"
840 " on encryptions (binding);\n",
844 log_error (_("error creating 'encryptions' TOFU table: %s\n"),
851 /* The effective policy for a binding. If a key is ultimately
852 * trusted, then the effective policy of all of its bindings is
853 * good. Likewise if a key is signed by an ultimately trusted
854 * key, etc. If the effective policy is NONE, then we need to
855 * recompute the effective policy. Otherwise, the effective
856 * policy is considered to be up to date, i.e., effective_policy
857 * is a cache of the computed policy. */
858 rc = gpgsql_exec_printf
859 (db, NULL, NULL, &err,
860 "alter table bindings"
861 " add column effective_policy INTEGER"
863 " CHECK (effective_policy in (%d, %d, %d, %d, %d, %d));",
865 TOFU_POLICY_NONE, TOFU_POLICY_AUTO, TOFU_POLICY_GOOD,
866 TOFU_POLICY_UNKNOWN, TOFU_POLICY_BAD, TOFU_POLICY_ASK);
869 if (rc == SQLITE_ERROR)
870 /* Almost certainly "duplicate column name", which we can
874 log_error (_("adding column effective_policy to bindings DB: %s\n"),
881 rc = check_utks (db);
885 rc = sqlite3_exec (db, "rollback;", NULL, NULL, &err);
888 log_error (_("error rolling back transaction on TOFU database: %s\n"),
896 rc = sqlite3_exec (db, "end transaction;", NULL, NULL, &err);
899 log_error (_("error committing transaction on TOFU database: %s\n"),
909 busy_handler (void *cookie, int call_count)
911 ctrl_t ctrl = cookie;
912 tofu_dbs_t dbs = ctrl->tofu.dbs;
916 /* Update the want-lock-file time stamp (specifically, the ctime) so
917 * that the current owner knows that we (well, someone) want the
921 /* Note: we don't fail if we can't create the lock file: this
922 * process will have to wait a bit longer, but otherwise nothing
923 * horrible should happen. */
927 fp = es_fopen (dbs->want_lock_file, "w");
929 log_debug ("TOFU: Error opening '%s': %s\n",
930 dbs->want_lock_file, strerror (errno));
939 /* Create a new DB handle. Returns NULL on error. */
940 /* FIXME: Change to return an error code for better reporting by the
943 opendbs (ctrl_t ctrl)
951 filename = make_filename (gnupg_homedir (), "tofu.db", NULL);
953 rc = sqlite3_open (filename, &db);
956 log_error (_("error opening TOFU database '%s': %s\n"),
957 filename, sqlite3_errmsg (db));
958 /* Even if an error occurs, DB is guaranteed to be valid. */
963 /* If a DB is locked wait up to 5 seconds for the lock to be cleared
967 sqlite3_busy_timeout (db, 5 * 1000);
968 sqlite3_busy_handler (db, busy_handler, ctrl);
971 if (db && initdb (db))
979 ctrl->tofu.dbs = xmalloc_clear (sizeof *ctrl->tofu.dbs);
980 ctrl->tofu.dbs->db = db;
981 ctrl->tofu.dbs->want_lock_file = xasprintf ("%s-want-lock", filename);
987 log_assert (ctrl->tofu.dbs->db);
989 return ctrl->tofu.dbs;
993 /* Release all of the resources associated with the DB handle. */
995 tofu_closedbs (ctrl_t ctrl)
998 sqlite3_stmt **statements;
1000 dbs = ctrl->tofu.dbs;
1002 return; /* Not initialized. */
1004 log_assert (dbs->in_transaction == 0);
1006 end_transaction (ctrl, 2);
1008 /* Arghh, that is a surprising use of the struct. */
1009 for (statements = (void *) &dbs->s;
1010 (void *) statements < (void *) &(&dbs->s)[1];
1012 sqlite3_finalize (*statements);
1014 sqlite3_close (dbs->db);
1015 xfree (dbs->want_lock_file);
1017 ctrl->tofu.dbs = NULL;
1021 /* Collect results of a select min (foo) ...; style query. Aborts if
1022 the argument is not a valid integer (or real of the form X.0). */
1024 get_single_long_cb (void *cookie, int argc, char **argv, char **azColName)
1026 long *count = cookie;
1030 log_assert (argc == 1);
1032 if (string_to_long (count, argv[0], 0, __LINE__))
1033 return 1; /* Abort. */
1039 get_single_long_cb2 (void *cookie, int argc, char **argv, char **azColName,
1043 return get_single_long_cb (cookie, argc, argv, azColName);
1046 /* Record (or update) a trust policy about a (possibly new)
1049 If SHOW_OLD is set, the binding's old policy is displayed. */
1051 record_binding (tofu_dbs_t dbs, const char *fingerprint, const char *email,
1052 const char *user_id,
1053 enum tofu_policy policy, enum tofu_policy effective_policy,
1054 const char *conflict, int set_conflict,
1055 int show_old, time_t now)
1057 char *fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
1061 if (! (policy == TOFU_POLICY_AUTO
1062 || policy == TOFU_POLICY_GOOD
1063 || policy == TOFU_POLICY_UNKNOWN
1064 || policy == TOFU_POLICY_BAD
1065 || policy == TOFU_POLICY_ASK))
1066 log_bug ("%s: Bad value for policy (%d)!\n", __func__, policy);
1069 if (DBG_TRUST || show_old)
1071 /* Get the old policy. Since this is just for informational
1072 * purposes, there is no need to start a transaction or to die
1073 * if there is a failure. */
1075 /* policy_old needs to be a long and not an enum tofu_policy,
1076 because we pass it by reference to get_single_long_cb2, which
1078 long policy_old = TOFU_POLICY_NONE;
1081 (dbs->db, &dbs->s.record_binding_get_old_policy,
1082 get_single_long_cb2, &policy_old, &err,
1083 "select policy from bindings where fingerprint = ? and email = ?",
1084 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1088 log_debug ("TOFU: Error reading from binding database"
1089 " (reading policy for <key: %s, user id: %s>): %s\n",
1090 fingerprint, email, err);
1094 if (policy_old != TOFU_POLICY_NONE)
1095 (show_old ? log_info : log_debug)
1096 ("Changing TOFU trust policy for binding"
1097 " <key: %s, user id: %s> from %s to %s.\n",
1098 fingerprint, show_old ? user_id : email,
1099 tofu_policy_str (policy_old),
1100 tofu_policy_str (policy));
1102 (show_old ? log_info : log_debug)
1103 ("Setting TOFU trust policy for new binding"
1104 " <key: %s, user id: %s> to %s.\n",
1105 fingerprint, show_old ? user_id : email,
1106 tofu_policy_str (policy));
1111 log_info ("TOFU database update skipped due to --dry-run\n");
1117 (dbs->db, &dbs->s.record_binding_update, NULL, NULL, &err,
1118 "insert or replace into bindings\n"
1119 " (oid, fingerprint, email, user_id, time,"
1120 " policy, conflict, effective_policy)\n"
1122 /* If we don't explicitly reuse the OID, then SQLite will
1123 * reallocate a new one. We just need to search for the OID
1124 * based on the fingerprint and email since they are unique. */
1125 " (select oid from bindings where fingerprint = ? and email = ?),\n"
1127 /* If SET_CONFLICT is 0, then preserve conflict's current value. */
1130 " (select conflict from bindings where fingerprint = ? and email = ?)"
1135 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1136 /* values 2 through 6. */
1137 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1138 GPGSQL_ARG_STRING, user_id,
1139 GPGSQL_ARG_LONG_LONG, (long long) now,
1140 GPGSQL_ARG_INT, (int) policy,
1141 /* conflict subquery. */
1142 GPGSQL_ARG_INT, set_conflict ? 1 : 0,
1143 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1144 GPGSQL_ARG_STRING, conflict ? conflict : "",
1145 GPGSQL_ARG_INT, (int) effective_policy,
1149 log_error (_("error updating TOFU database: %s\n"), err);
1150 print_further_info (" insert bindings <key: %s, user id: %s> = %s",
1151 fingerprint, email, tofu_policy_str (policy));
1157 xfree (fingerprint_pp);
1162 /* Collect the strings returned by a query in a simple string list.
1163 Any NULL values are converted to the empty string.
1165 If a result has 3 rows and each row contains two columns, then the
1166 results are added to the list as follows (the value is parentheses
1167 is the 1-based index in the final list):
1176 This is because add_to_strlist pushes the results onto the front of
1177 the list. The end result is that the rows are backwards, but the
1178 columns are in the expected order. */
1180 strings_collect_cb (void *cookie, int argc, char **argv, char **azColName)
1183 strlist_t *strlist = cookie;
1187 for (i = argc - 1; i >= 0; i --)
1188 add_to_strlist (strlist, argv[i] ? argv[i] : "");
1194 strings_collect_cb2 (void *cookie, int argc, char **argv, char **azColName,
1198 return strings_collect_cb (cookie, argc, argv, azColName);
1202 /* Auxiliary data structure to collect statistics about
1204 struct signature_stats
1206 struct signature_stats *next;
1208 /* The user-assigned policy for this binding. */
1209 enum tofu_policy policy;
1211 /* How long ago the signature was created (rounded to a multiple of
1212 TIME_AGO_UNIT_SMALL, etc.). */
1214 /* Number of signatures during this time. */
1215 unsigned long count;
1217 /* If the corresponding key/user id has been expired / revoked. */
1221 /* The key that generated this signature. */
1222 char fingerprint[1];
1226 signature_stats_free (struct signature_stats *stats)
1230 struct signature_stats *next = stats->next;
1237 signature_stats_prepend (struct signature_stats **statsp,
1238 const char *fingerprint,
1239 enum tofu_policy policy,
1241 unsigned long count)
1243 struct signature_stats *stats =
1244 xmalloc_clear (sizeof (*stats) + strlen (fingerprint));
1246 stats->next = *statsp;
1249 strcpy (stats->fingerprint, fingerprint);
1250 stats->policy = policy;
1251 stats->time_ago = time_ago;
1252 stats->count = count;
1256 /* Process rows that contain the four columns:
1258 <fingerprint, policy, time ago, count>. */
1260 signature_stats_collect_cb (void *cookie, int argc, char **argv,
1261 char **azColName, sqlite3_stmt *stmt)
1263 struct signature_stats **statsp = cookie;
1265 enum tofu_policy policy;
1267 unsigned long count;
1275 if (string_to_long (&along, argv[i], 0, __LINE__))
1276 return 1; /* Abort */
1284 if (string_to_long (&time_ago, argv[i], 0, __LINE__))
1285 return 1; /* Abort. */
1289 /* If time_ago is NULL, then we had no messages, but we still have a
1290 single row, which count(*) turns into 1. */
1295 if (string_to_ulong (&count, argv[i], 0, __LINE__))
1296 return 1; /* Abort */
1300 log_assert (argc == i);
1302 signature_stats_prepend (statsp, argv[0], policy, time_ago, count);
1307 /* Format the first part of a conflict message and return that as a
1308 * malloced string. */
1310 format_conflict_msg_part1 (int policy, strlist_t conflict_set,
1315 char *tmpstr, *text;
1317 log_assert (conflict_set);
1318 fingerprint = conflict_set->d;
1320 fp = es_fopenmem (0, "rw,samethread");
1322 log_fatal ("error creating memory stream: %s\n",
1323 gpg_strerror (gpg_error_from_syserror()));
1325 if (policy == TOFU_POLICY_NONE)
1328 _("This is the first time the email address \"%s\" is "
1329 "being used with key %s."),
1330 email, fingerprint);
1333 else if (policy == TOFU_POLICY_ASK && conflict_set->next)
1335 int conflicts = strlist_length (conflict_set);
1337 (fp, ngettext("The email address \"%s\" is associated with %d key!",
1338 "The email address \"%s\" is associated with %d keys!",
1343 _(" Since this binding's policy was 'auto', it has been "
1344 "changed to 'ask'."));
1349 _("Please indicate whether this email address should"
1350 " be associated with key %s or whether you think someone"
1351 " is impersonating \"%s\"."),
1352 fingerprint, email);
1353 es_fputc ('\n', fp);
1356 if (es_fclose_snatch (fp, (void **)&tmpstr, NULL))
1357 log_fatal ("error snatching memory stream\n");
1358 text = format_text (tmpstr, 0, 72, 80);
1365 /* Return 1 if A signed B and B signed A. */
1367 cross_sigs (const char *email, kbnode_t a, kbnode_t b)
1371 PKT_public_key *a_pk = a->pkt->pkt.public_key;
1372 PKT_public_key *b_pk = b->pkt->pkt.public_key;
1379 format_keyid (pk_main_keyid (a_pk),
1380 KF_LONG, a_keyid, sizeof (a_keyid));
1381 format_keyid (pk_main_keyid (b_pk),
1382 KF_LONG, b_keyid, sizeof (b_keyid));
1385 for (i = 0; i < 2; i ++)
1387 /* See if SIGNER signed SIGNEE. */
1389 kbnode_t signer = i == 0 ? a : b;
1390 kbnode_t signee = i == 0 ? b : a;
1392 PKT_public_key *signer_pk = signer->pkt->pkt.public_key;
1393 u32 *signer_kid = pk_main_keyid (signer_pk);
1398 /* Iterate over SIGNEE's keyblock and see if there is a valid
1399 signature from SIGNER. */
1400 for (n = signee; n; n = n->next)
1404 if (n->pkt->pkttype == PKT_USER_ID)
1407 /* We're done: we've processed all signatures on the
1412 /* See if this is the matching user id. */
1413 PKT_user_id *user_id = n->pkt->pkt.user_id;
1414 char *email2 = email_from_user_id (user_id->name);
1416 if (strcmp (email, email2) == 0)
1426 if (n->pkt->pkttype != PKT_SIGNATURE)
1429 sig = n->pkt->pkt.signature;
1431 if (! (sig->sig_class == 0x10
1432 || sig->sig_class == 0x11
1433 || sig->sig_class == 0x12
1434 || sig->sig_class == 0x13))
1435 /* Not a signature over a user id. */
1438 /* SIG is on SIGNEE's keyblock. If SIG was generated by the
1439 signer, then it's a match. */
1440 if (keyid_cmp (sig->keyid, signer_kid) == 0)
1445 /* We didn't find a signature from signer over signee. */
1448 log_debug ("No cross sig between %s and %s\n",
1454 /* A signed B and B signed A. */
1456 log_debug ("Cross sig between %s and %s\n",
1462 /* Return whether the key was signed by an ultimately trusted key. */
1464 signed_by_utk (const char *email, kbnode_t a)
1469 for (n = a; n; n = n->next)
1473 if (n->pkt->pkttype == PKT_USER_ID)
1476 /* We're done: we've processed all signatures on the
1481 /* See if this is the matching user id. */
1482 PKT_user_id *user_id = n->pkt->pkt.user_id;
1483 char *email2 = email_from_user_id (user_id->name);
1485 if (strcmp (email, email2) == 0)
1495 if (n->pkt->pkttype != PKT_SIGNATURE)
1498 sig = n->pkt->pkt.signature;
1500 if (! (sig->sig_class == 0x10
1501 || sig->sig_class == 0x11
1502 || sig->sig_class == 0x12
1503 || sig->sig_class == 0x13))
1504 /* Not a signature over a user id. */
1507 /* SIG is on SIGNEE's keyblock. If SIG was generated by the
1508 signer, then it's a match. */
1509 if (tdb_keyid_is_utk (sig->keyid))
1513 log_debug ("TOFU: %s is signed by an ultimately trusted key.\n",
1514 pk_keyid_str (a->pkt->pkt.public_key));
1521 log_debug ("TOFU: %s is NOT signed by an ultimately trusted key.\n",
1522 pk_keyid_str (a->pkt->pkt.public_key));
1530 BINDING_NEW = 1 << 0,
1531 BINDING_CONFLICT = 1 << 1,
1532 BINDING_EXPIRED = 1 << 2,
1533 BINDING_REVOKED = 1 << 3
1537 /* Ask the user about the binding. There are three ways we could end
1540 * - This is a new binding and there is a conflict
1541 * (policy == TOFU_POLICY_NONE && conflict_set_count > 1),
1543 * - This is a new binding and opt.tofu_default_policy is set to
1544 * ask. (policy == TOFU_POLICY_NONE && opt.tofu_default_policy ==
1545 * TOFU_POLICY_ASK), or,
1547 * - The policy is ask (the user deferred last time) (policy ==
1550 * Note: this function must not be called while in a transaction!
1552 * CONFLICT_SET includes all of the conflicting bindings
1553 * with FINGERPRINT first. FLAGS is a bit-wise or of
1557 ask_about_binding (ctrl_t ctrl,
1558 enum tofu_policy *policy,
1560 strlist_t conflict_set,
1561 const char *fingerprint,
1563 const char *user_id,
1568 int conflict_set_count = strlist_length (conflict_set);
1572 strlist_t other_user_ids = NULL;
1573 struct signature_stats *stats = NULL;
1574 struct signature_stats *stats_iter = NULL;
1575 char *prompt = NULL;
1578 dbs = ctrl->tofu.dbs;
1580 log_assert (dbs->in_transaction == 0);
1582 fp = es_fopenmem (0, "rw,samethread");
1584 log_fatal ("error creating memory stream: %s\n",
1585 gpg_strerror (gpg_error_from_syserror()));
1588 char *text = format_conflict_msg_part1 (*policy, conflict_set, email);
1589 es_fputs (text, fp);
1590 es_fputc ('\n', fp);
1594 begin_transaction (ctrl, 0);
1596 /* Find other user ids associated with this key and whether the
1597 * bindings are marked as good or bad. */
1599 (dbs->db, &dbs->s.get_trust_gather_other_user_ids,
1600 strings_collect_cb2, &other_user_ids, &sqerr,
1601 "select user_id, policy from bindings where fingerprint = ?;",
1602 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_END);
1605 log_error (_("error gathering other user IDs: %s\n"), sqerr);
1606 sqlite3_free (sqerr);
1608 rc = gpg_error (GPG_ERR_GENERAL);
1613 strlist_t strlist_iter;
1615 es_fprintf (fp, _("This key's user IDs:\n"));
1616 for (strlist_iter = other_user_ids;
1618 strlist_iter = strlist_iter->next)
1620 char *other_user_id = strlist_iter->d;
1622 enum tofu_policy other_policy;
1624 log_assert (strlist_iter->next);
1625 strlist_iter = strlist_iter->next;
1626 other_thing = strlist_iter->d;
1628 other_policy = atoi (other_thing);
1630 es_fprintf (fp, " %s (", other_user_id);
1631 es_fprintf (fp, _("policy: %s"), tofu_policy_str (other_policy));
1632 es_fprintf (fp, ")\n");
1634 es_fprintf (fp, "\n");
1636 free_strlist (other_user_ids);
1639 /* Get the stats for all the keys in CONFLICT_SET. */
1640 strlist_rev (&conflict_set);
1641 for (iter = conflict_set; iter && ! rc; iter = iter->next)
1643 #define STATS_SQL(table, time, sign) \
1644 "select fingerprint, policy, time_ago, count(*)\n" \
1646 " (select bindings.*,\n" \
1648 " when delta ISNULL then 1\n" \
1649 /* From the future (but if its just a couple of hours in the \
1650 * future don't turn it into a warning)? Or should we use \
1651 * small, medium or large units? (Note: whatever we do, we \
1652 * keep the value in seconds. Then when we group, everything \
1653 * that rounds to the same number of seconds is grouped.) */ \
1654 " when delta < -("STRINGIFY (TIME_AGO_FUTURE_IGNORE)") then 2\n" \
1655 " when delta < ("STRINGIFY (TIME_AGO_SMALL_THRESHOLD)")\n" \
1657 " when delta < ("STRINGIFY (TIME_AGO_MEDIUM_THRESHOLD)")\n" \
1659 " when delta < ("STRINGIFY (TIME_AGO_LARGE_THRESHOLD)")\n" \
1662 " end time_ago,\n" \
1663 " delta time_ago_raw\n" \
1664 " from bindings\n" \
1667 " cast(? - " time " as real) delta\n" \
1668 " from " table ") ss\n" \
1669 " on ss.binding = bindings.oid)\n" \
1670 " where email = ? and fingerprint = ?\n" \
1671 " group by time_ago\n" \
1672 /* Make sure the current key is first. */ \
1673 " order by time_ago desc;\n"
1675 /* Use the time when we saw the signature, not when the
1676 signature was created as that can be forged. */
1678 (dbs->db, &dbs->s.get_trust_gather_signature_stats,
1679 signature_stats_collect_cb, &stats, &sqerr,
1680 STATS_SQL ("signatures", "time", ""),
1681 GPGSQL_ARG_LONG_LONG, (long long) now,
1682 GPGSQL_ARG_STRING, email,
1683 GPGSQL_ARG_STRING, iter->d,
1687 rc = gpg_error (GPG_ERR_GENERAL);
1691 if (!stats || strcmp (iter->d, stats->fingerprint) != 0)
1692 /* No stats for this binding. Add a dummy entry. */
1693 signature_stats_prepend (&stats, iter->d, TOFU_POLICY_AUTO, 1, 1);
1696 (dbs->db, &dbs->s.get_trust_gather_encryption_stats,
1697 signature_stats_collect_cb, &stats, &sqerr,
1698 STATS_SQL ("encryptions", "time", "-"),
1699 GPGSQL_ARG_LONG_LONG, (long long) now,
1700 GPGSQL_ARG_STRING, email,
1701 GPGSQL_ARG_STRING, iter->d,
1705 rc = gpg_error (GPG_ERR_GENERAL);
1711 if (!stats || strcmp (iter->d, stats->fingerprint) != 0
1712 || stats->time_ago > 0)
1713 /* No stats for this binding. Add a dummy entry. */
1714 signature_stats_prepend (&stats, iter->d, TOFU_POLICY_AUTO, -1, 1);
1716 end_transaction (ctrl, 0);
1717 strlist_rev (&conflict_set);
1720 strlist_t strlist_iter;
1722 log_error (_("error gathering signature stats: %s\n"), sqerr);
1723 sqlite3_free (sqerr);
1726 es_fprintf (fp, ngettext("The email address \"%s\" is"
1727 " associated with %d key:\n",
1728 "The email address \"%s\" is"
1729 " associated with %d keys:\n",
1730 conflict_set_count),
1731 email, conflict_set_count);
1732 for (strlist_iter = conflict_set;
1734 strlist_iter = strlist_iter->next)
1735 es_fprintf (fp, " %s\n", strlist_iter->d);
1741 int seen_in_past = 0;
1744 es_fprintf (fp, _("Statistics for keys"
1745 " with the email address \"%s\":\n"),
1747 for (stats_iter = stats; stats_iter; stats_iter = stats_iter->next)
1750 log_debug ("%s: time_ago: %ld; count: %ld\n",
1751 stats_iter->fingerprint,
1752 stats_iter->time_ago,
1756 if (stats_iter->time_ago > 0 && encrypted)
1758 /* We've change from the encrypted stats to the verified
1759 * stats. Reset SEEN_IN_PAST. */
1764 if (! key || strcmp (key, stats_iter->fingerprint))
1769 key = stats_iter->fingerprint;
1770 this_key = strcmp (key, fingerprint) == 0;
1771 key_pp = format_hexfingerprint (key, NULL, 0);
1772 es_fprintf (fp, " %s (", key_pp);
1774 /* Find the associated binding. */
1775 for (binding = conflict_set;
1777 binding = binding->next)
1778 if (strcmp (key, binding->d) == 0)
1780 log_assert (binding);
1782 if ((binding->flags & BINDING_REVOKED))
1784 es_fprintf (fp, _("revoked"));
1785 es_fprintf (fp, _(", "));
1787 else if ((binding->flags & BINDING_EXPIRED))
1789 es_fprintf (fp, _("expired"));
1790 es_fprintf (fp, _(", "));
1794 es_fprintf (fp, _("this key"));
1796 es_fprintf (fp, _("policy: %s"),
1797 tofu_policy_str (stats_iter->policy));
1798 es_fputs ("):\n", fp);
1803 show_statistics (dbs, stats_iter->fingerprint, email,
1804 TOFU_POLICY_ASK, NULL, 1, now);
1807 if (labs(stats_iter->time_ago) == 1)
1809 /* The 1 in this case is the NULL entry. */
1810 log_assert (stats_iter->count == 1);
1811 stats_iter->count = 0;
1813 seen_in_past += stats_iter->count;
1817 if (!stats_iter->count)
1819 if (stats_iter->time_ago > 0)
1820 es_fprintf (fp, ngettext("Verified %d message.",
1821 "Verified %d messages.",
1822 seen_in_past), seen_in_past);
1824 es_fprintf (fp, ngettext("Encrypted %d message.",
1825 "Encrypted %d messages.",
1826 seen_in_past), seen_in_past);
1828 else if (labs(stats_iter->time_ago) == 2)
1830 if (stats_iter->time_ago > 0)
1831 es_fprintf (fp, ngettext("Verified %d message in the future.",
1832 "Verified %d messages in the future.",
1833 seen_in_past), seen_in_past);
1835 es_fprintf (fp, ngettext("Encrypted %d message in the future.",
1836 "Encrypted %d messages in the future.",
1837 seen_in_past), seen_in_past);
1843 if (labs(stats_iter->time_ago) == 3)
1845 int days = 1 + stats_iter->time_ago / TIME_AGO_UNIT_SMALL;
1846 if (stats_iter->time_ago > 0)
1849 ngettext("Messages verified over the past %d day: %d.",
1850 "Messages verified over the past %d days: %d.",
1851 days), days, seen_in_past);
1855 ngettext("Messages encrypted over the past %d day: %d.",
1856 "Messages encrypted over the past %d days: %d.",
1857 days), days, seen_in_past);
1859 else if (labs(stats_iter->time_ago) == 4)
1861 int months = 1 + stats_iter->time_ago / TIME_AGO_UNIT_MEDIUM;
1862 if (stats_iter->time_ago > 0)
1865 ngettext("Messages verified over the past %d month: %d.",
1866 "Messages verified over the past %d months: %d.",
1867 months), months, seen_in_past);
1871 ngettext("Messages encrypted over the past %d month: %d.",
1872 "Messages encrypted over the past %d months: %d.",
1873 months), months, seen_in_past);
1875 else if (labs(stats_iter->time_ago) == 5)
1877 int years = 1 + stats_iter->time_ago / TIME_AGO_UNIT_LARGE;
1878 if (stats_iter->time_ago > 0)
1881 ngettext("Messages verified over the past %d year: %d.",
1882 "Messages verified over the past %d years: %d.",
1883 years), years, seen_in_past);
1887 ngettext("Messages encrypted over the past %d year: %d.",
1888 "Messages encrypted over the past %d years: %d.",
1889 years), years, seen_in_past);
1891 else if (labs(stats_iter->time_ago) == 6)
1893 if (stats_iter->time_ago > 0)
1895 (fp, _("Messages verified in the past: %d."),
1899 (fp, _("Messages encrypted in the past: %d."),
1903 log_assert (! "Broken SQL.\n");
1905 es_fputs ("\n", fp);
1909 if (conflict_set_count > 1 || (conflict_set->flags & BINDING_CONFLICT))
1911 /* This is a conflict. */
1913 /* TRANSLATORS: Please translate the text found in the source
1914 * file below. We don't directly internationalize that text so
1915 * that we can tweak it without breaking translations. */
1916 char *text = _("TOFU detected a binding conflict");
1918 if (!strcmp (text, "TOFU detected a binding conflict"))
1920 /* No translation. Use the English text. */
1922 "Normally, an email address is associated with a single key. "
1923 "However, people sometimes generate a new key if "
1924 "their key is too old or they think it might be compromised. "
1925 "Alternatively, a new key may indicate a man-in-the-middle "
1926 "attack! Before accepting this association, you should talk to or "
1927 "call the person to make sure this new key is legitimate.";
1929 textbuf = format_text (text, 0, 72, 80);
1930 es_fprintf (fp, "\n%s\n", textbuf);
1934 es_fputc ('\n', fp);
1936 /* Add a NUL terminator. */
1938 if (es_fclose_snatch (fp, (void **) &prompt, NULL))
1939 log_fatal ("error snatching memory stream\n");
1941 /* I think showing the large message once is sufficient. If we
1942 * would move it right before the cpr_get many lines will scroll
1943 * away and the user might not realize that he merely entered a
1944 * wrong choise (because he does not see that either). As a small
1945 * benefit we allow C-L to redisplay everything. */
1946 tty_printf ("%s", prompt);
1948 /* Suspend any transaction: it could take a while until the user
1950 tofu_suspend_batch_transaction (ctrl);
1955 /* TRANSLATORS: Two letters (normally the lower and upper case
1956 * version of the hotkey) for each of the five choices. If
1957 * there is only one choice in your language, repeat it. */
1958 choices = _("gG" "aA" "uU" "rR" "bB");
1959 if (strlen (choices) != 10)
1960 log_bug ("Bad TOFU conflict translation! Please report.");
1964 _("(G)ood, (A)ccept once, (U)nknown, (R)eject once, (B)ad? "));
1965 trim_spaces (response);
1967 if (*response == CONTROL_L)
1968 tty_printf ("%s", prompt);
1969 else if (!response[0])
1970 /* Default to unknown. Don't save it. */
1972 tty_printf (_("Defaulting to unknown."));
1973 *policy = TOFU_POLICY_UNKNOWN;
1976 else if (!response[1])
1978 char *choice = strchr (choices, *response);
1982 int c = ((size_t) choice - (size_t) choices) / 2;
1987 *policy = TOFU_POLICY_GOOD;
1988 *trust_level = tofu_policy_to_trust_level (*policy);
1990 case 1: /* Accept once. */
1991 *policy = TOFU_POLICY_ASK;
1992 *trust_level = tofu_policy_to_trust_level (TOFU_POLICY_GOOD);
1994 case 2: /* Unknown. */
1995 *policy = TOFU_POLICY_UNKNOWN;
1996 *trust_level = tofu_policy_to_trust_level (*policy);
1998 case 3: /* Reject once. */
1999 *policy = TOFU_POLICY_ASK;
2000 *trust_level = tofu_policy_to_trust_level (TOFU_POLICY_BAD);
2003 *policy = TOFU_POLICY_BAD;
2004 *trust_level = tofu_policy_to_trust_level (*policy);
2007 log_bug ("c should be between 0 and 4 but it is %d!", c);
2010 if (record_binding (dbs, fingerprint, email, user_id,
2011 *policy, TOFU_POLICY_NONE, NULL, 0, 0, now))
2013 /* If there's an error registering the
2014 * binding, don't save the signature. */
2015 *trust_level = _tofu_GET_TRUST_ERROR;
2023 tofu_resume_batch_transaction (ctrl);
2027 signature_stats_free (stats);
2030 /* Return the set of keys that conflict with the binding <fingerprint,
2031 email> (including the binding itself, which will be first in the
2032 list). For each returned key also sets BINDING_NEW, etc. */
2034 build_conflict_set (tofu_dbs_t dbs,
2035 PKT_public_key *pk, const char *fingerprint,
2040 strlist_t conflict_set = NULL;
2041 int conflict_set_count;
2047 /* Get the fingerprints of any bindings that share the email address
2048 * and whether the bindings have a known conflict.
2050 * Note: if the binding in question is in the DB, it will also be
2051 * returned. Thus, if the result set is empty, then <email,
2052 * fingerprint> is a new binding. */
2054 (dbs->db, &dbs->s.get_trust_bindings_with_this_email,
2055 strings_collect_cb2, &conflict_set, &sqerr,
2057 /* A binding should only appear once, but try not to break in the
2058 * case of corruption. */
2059 " fingerprint || case sum(conflict NOTNULL) when 0 then '' else '!' end"
2060 " from bindings where email = ?"
2061 " group by fingerprint"
2062 /* Make sure the current key comes first in the result list (if
2064 " order by fingerprint = ? asc, fingerprint desc;",
2065 GPGSQL_ARG_STRING, email,
2066 GPGSQL_ARG_STRING, fingerprint,
2070 log_error (_("error reading TOFU database: %s\n"), sqerr);
2071 print_further_info ("listing fingerprints");
2072 sqlite3_free (sqerr);
2073 rc = gpg_error (GPG_ERR_GENERAL);
2077 /* Set BINDING_CONFLICT if the binding has a known conflict. This
2078 * allows us to distinguish between bindings where the user
2079 * explicitly set the policy to ask and bindings where we set the
2080 * policy to ask due to a conflict. */
2081 for (iter = conflict_set; iter; iter = iter->next)
2083 int l = strlen (iter->d);
2084 if (!(l == 2 * MAX_FINGERPRINT_LEN
2085 || l == 2 * MAX_FINGERPRINT_LEN + 1))
2087 log_error (_("TOFU db corruption detected.\n"));
2088 print_further_info ("fingerprint '%s' is not %d characters long",
2089 iter->d, 2 * MAX_FINGERPRINT_LEN);
2092 if (l >= 1 && iter->d[l - 1] == '!')
2094 iter->flags |= BINDING_CONFLICT;
2100 /* If the current binding has not yet been recorded, add it to the
2101 * list. (The order by above ensures that if it is present, it will
2103 if (! (conflict_set && strcmp (conflict_set->d, fingerprint) == 0))
2105 add_to_strlist (&conflict_set, fingerprint);
2106 conflict_set->flags |= BINDING_NEW;
2109 conflict_set_count = strlist_length (conflict_set);
2111 /* Eliminate false conflicts. */
2113 if (conflict_set_count == 1)
2114 /* We only have a single key. There are no false conflicts to
2115 eliminate. But, we do need to set the flags. */
2117 if (pk->has_expired)
2118 conflict_set->flags |= BINDING_EXPIRED;
2119 if (pk->flags.revoked)
2120 conflict_set->flags |= BINDING_REVOKED;
2122 return conflict_set;
2125 /* If two keys have cross signatures, then they are controlled by
2126 * the same person and thus are not in conflict. */
2127 kb_all = xcalloc (sizeof (kb_all[0]), conflict_set_count);
2129 for (i = 0, iter = conflict_set;
2130 i < conflict_set_count;
2131 i ++, iter = iter->next)
2134 KEYDB_SEARCH_DESC desc;
2136 PKT_public_key *binding_pk;
2140 rc = keydb_search_reset (hd);
2143 log_error (_("resetting keydb: %s\n"),
2148 rc = classify_user_id (fp, &desc, 0);
2151 log_error (_("error parsing key specification '%s': %s\n"),
2152 fp, gpg_strerror (rc));
2156 rc = keydb_search (hd, &desc, 1, NULL);
2159 /* Note: it is entirely possible that we don't have the key
2160 corresponding to an entry in the TOFU DB. This can
2161 happen if we merge two TOFU DBs, but not the key
2163 log_info (_("key \"%s\" not found: %s\n"),
2164 fp, gpg_strerror (rc));
2168 rc = keydb_get_keyblock (hd, &kb);
2171 log_error (_("error reading keyblock: %s\n"),
2173 print_further_info ("fingerprint: %s", fp);
2177 merge_keys_and_selfsig (kb);
2179 log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
2183 /* Since we have the key block, use this opportunity to figure
2184 * out if the binding is expired or revoked. */
2185 binding_pk = kb->pkt->pkt.public_key;
2187 /* The binding is always expired/revoked if the key is
2188 * expired/revoked. */
2189 if (binding_pk->has_expired)
2190 iter->flags |= BINDING_EXPIRED;
2191 if (binding_pk->flags.revoked)
2192 iter->flags |= BINDING_REVOKED;
2194 /* The binding is also expired/revoked if the user id is
2195 * expired/revoked. */
2198 while ((n = find_next_kbnode (n, PKT_USER_ID)) && ! found_user_id)
2200 PKT_user_id *user_id2 = n->pkt->pkt.user_id;
2203 if (user_id2->attrib_data)
2206 email2 = email_from_user_id (user_id2->name);
2208 if (strcmp (email, email2) == 0)
2212 if (user_id2->is_revoked)
2213 iter->flags |= BINDING_REVOKED;
2214 if (user_id2->is_expired)
2215 iter->flags |= BINDING_EXPIRED;
2221 if (! found_user_id)
2223 log_info (_("TOFU db corruption detected.\n"));
2224 print_further_info ("user id '%s' not on key block '%s'",
2225 email, fingerprint);
2230 /* Now that we have the key blocks, check for cross sigs. */
2234 strlist_t iter_next;
2237 log_assert (conflict_set_count > 0);
2238 die = xtrycalloc (conflict_set_count, sizeof *die);
2241 /*err = gpg_error_from_syserror ();*/
2242 xoutofcore (); /* Fixme: Let the fucntion return an error. */
2245 for (i = 0; i < conflict_set_count; i ++)
2247 /* Look for cross sigs between this key (i == 0) or a key
2248 * that has cross sigs with i == 0 (i.e., transitively) */
2249 if (! (i == 0 || die[i]))
2252 for (j = i + 1; j < conflict_set_count; j ++)
2253 /* Be careful: we might not have a key block for a key. */
2254 if (kb_all[i] && kb_all[j] && cross_sigs (email, kb_all[i], kb_all[j]))
2258 /* Free unconflicting bindings (and all of the key blocks). */
2259 for (iter = conflict_set, prevp = &conflict_set, i = 0;
2261 iter = iter_next, i ++)
2263 iter_next = iter->next;
2265 release_kbnode (kb_all[i]);
2271 free_strlist (iter);
2272 conflict_set_count --;
2276 prevp = &iter->next;
2280 /* We shouldn't have removed the head. */
2281 log_assert (conflict_set);
2282 log_assert (conflict_set_count >= 1);
2289 log_debug ("binding <key: %s, email: %s> conflicts:\n",
2290 fingerprint, email);
2291 for (iter = conflict_set; iter; iter = iter->next)
2293 log_debug (" %s:%s%s%s%s\n",
2295 (iter->flags & BINDING_NEW) ? " new" : "",
2296 (iter->flags & BINDING_CONFLICT) ? " known_conflict" : "",
2297 (iter->flags & BINDING_EXPIRED) ? " expired" : "",
2298 (iter->flags & BINDING_REVOKED) ? " revoked" : "");
2302 return conflict_set;
2306 /* Return the effective policy for the binding <FINGERPRINT, EMAIL>
2307 * (email has already been normalized) and any conflict information in
2308 * *CONFLICT_SETP, if CONFLICT_SETP is not NULL. Returns
2309 * _tofu_GET_POLICY_ERROR if an error occurs. */
2310 static enum tofu_policy
2311 get_policy (tofu_dbs_t dbs, PKT_public_key *pk,
2312 const char *fingerprint, const char *user_id, const char *email,
2313 strlist_t *conflict_setp, time_t now)
2317 strlist_t results = NULL;
2318 enum tofu_policy policy = _tofu_GET_POLICY_ERROR;
2319 enum tofu_policy effective_policy_orig = TOFU_POLICY_NONE;
2320 enum tofu_policy effective_policy = _tofu_GET_POLICY_ERROR;
2322 char *conflict_orig = NULL;
2323 char *conflict = NULL;
2324 strlist_t conflict_set = NULL;
2325 int conflict_set_count;
2327 /* Check if the <FINGERPRINT, EMAIL> binding is known
2328 (TOFU_POLICY_NONE cannot appear in the DB. Thus, if POLICY is
2329 still TOFU_POLICY_NONE after executing the query, then the
2330 result set was empty.) */
2331 rc = gpgsql_stepx (dbs->db, &dbs->s.get_policy_select_policy_and_conflict,
2332 strings_collect_cb2, &results, &err,
2333 "select policy, conflict, effective_policy from bindings\n"
2334 " where fingerprint = ? and email = ?",
2335 GPGSQL_ARG_STRING, fingerprint,
2336 GPGSQL_ARG_STRING, email,
2340 log_error (_("error reading TOFU database: %s\n"), err);
2341 print_further_info ("reading the policy");
2343 rc = gpg_error (GPG_ERR_GENERAL);
2347 if (strlist_length (results) == 0)
2349 /* No results. Use the defaults. */
2350 policy = TOFU_POLICY_NONE;
2351 effective_policy = TOFU_POLICY_NONE;
2353 else if (strlist_length (results) == 3)
2355 /* Parse and sanity check the results. */
2357 if (string_to_long (&along, results->d, 0, __LINE__))
2359 log_error (_("error reading TOFU database: %s\n"),
2360 gpg_strerror (GPG_ERR_BAD_DATA));
2361 print_further_info ("bad value for policy: %s", results->d);
2366 if (! (policy == TOFU_POLICY_AUTO
2367 || policy == TOFU_POLICY_GOOD
2368 || policy == TOFU_POLICY_UNKNOWN
2369 || policy == TOFU_POLICY_BAD
2370 || policy == TOFU_POLICY_ASK))
2372 log_error (_("error reading TOFU database: %s\n"),
2373 gpg_strerror (GPG_ERR_DB_CORRUPTED));
2374 print_further_info ("invalid value for policy (%d)", policy);
2375 effective_policy = _tofu_GET_POLICY_ERROR;
2379 if (*results->next->d)
2380 conflict = xstrdup (results->next->d);
2382 if (string_to_long (&along, results->next->next->d, 0, __LINE__))
2384 log_error (_("error reading TOFU database: %s\n"),
2385 gpg_strerror (GPG_ERR_BAD_DATA));
2386 print_further_info ("bad value for effective policy: %s",
2387 results->next->next->d);
2390 effective_policy = along;
2392 if (! (effective_policy == TOFU_POLICY_NONE
2393 || effective_policy == TOFU_POLICY_AUTO
2394 || effective_policy == TOFU_POLICY_GOOD
2395 || effective_policy == TOFU_POLICY_UNKNOWN
2396 || effective_policy == TOFU_POLICY_BAD
2397 || effective_policy == TOFU_POLICY_ASK))
2399 log_error (_("error reading TOFU database: %s\n"),
2400 gpg_strerror (GPG_ERR_DB_CORRUPTED));
2401 print_further_info ("invalid value for effective_policy (%d)",
2403 effective_policy = _tofu_GET_POLICY_ERROR;
2409 /* The result has the wrong form. */
2411 log_error (_("error reading TOFU database: %s\n"),
2412 gpg_strerror (GPG_ERR_BAD_DATA));
2413 print_further_info ("reading policy: expected 3 columns, got %d\n",
2414 strlist_length (results));
2418 /* Save the effective policy and conflict so we know if we changed
2420 effective_policy_orig = effective_policy;
2421 conflict_orig = conflict;
2423 /* Unless there is a conflict, if the effective policy is cached,
2424 * just return it. The reason we don't do this when there is a
2425 * conflict is because of the following scenario: assume A and B
2426 * conflict and B has signed A's key. Now, later we import A's
2427 * signature on B. We need to recheck A, but the signature was on
2428 * B, i.e., when B changes, we invalidate B's effective policy, but
2429 * we also need to invalidate A's effective policy. Instead, we
2430 * assume that conflicts are rare and don't optimize for them, which
2431 * would complicate the code. */
2432 if (effective_policy != TOFU_POLICY_NONE && !conflict)
2435 /* If the user explicitly set the policy, then respect that. */
2436 if (policy != TOFU_POLICY_AUTO && policy != TOFU_POLICY_NONE)
2438 effective_policy = policy;
2442 /* Unless proven wrong, assume the effective policy is 'auto'. */
2443 effective_policy = TOFU_POLICY_AUTO;
2445 /* See if the key is ultimately trusted. */
2449 keyid_from_pk (pk, kid);
2450 if (tdb_keyid_is_utk (kid))
2452 effective_policy = TOFU_POLICY_GOOD;
2457 /* See if the key is signed by an ultimately trusted key. */
2459 int fingerprint_raw_len = strlen (fingerprint) / 2;
2460 char fingerprint_raw[20];
2463 if (fingerprint_raw_len != sizeof fingerprint_raw
2464 || ((len = hex2bin (fingerprint,
2465 fingerprint_raw, fingerprint_raw_len))
2466 != strlen (fingerprint)))
2469 log_debug ("TOFU: Bad fingerprint: %s (len: %zu, parsed: %d)\n",
2470 fingerprint, strlen (fingerprint), len);
2477 lookup_err = get_pubkey_byfprint (NULL, &kb,
2479 fingerprint_raw_len);
2483 log_debug ("TOFU: Looking up %s: %s\n",
2484 fingerprint, gpg_strerror (lookup_err));
2488 int is_signed_by_utk = signed_by_utk (email, kb);
2489 release_kbnode (kb);
2490 if (is_signed_by_utk)
2492 effective_policy = TOFU_POLICY_GOOD;
2499 /* Check for any conflicts / see if a previously discovered conflict
2500 * disappeared. The latter can happen if the conflicting bindings
2501 * are now cross signed, for instance. */
2503 conflict_set = build_conflict_set (dbs, pk, fingerprint, email);
2504 conflict_set_count = strlist_length (conflict_set);
2505 if (conflict_set_count == 0)
2507 /* build_conflict_set should always at least return the current
2508 binding. Something went wrong. */
2509 effective_policy = _tofu_GET_POLICY_ERROR;
2513 if (conflict_set_count == 1
2514 && (conflict_set->flags & BINDING_NEW))
2516 /* We've never observed a binding with this email address and we
2517 * have a default policy, which is not to ask the user. */
2519 /* If we've seen this binding, then we've seen this email and
2520 * policy couldn't possibly be TOFU_POLICY_NONE. */
2521 log_assert (policy == TOFU_POLICY_NONE);
2524 log_debug ("TOFU: New binding <key: %s, user id: %s>, no conflict.\n",
2525 fingerprint, email);
2527 effective_policy = TOFU_POLICY_AUTO;
2531 if (conflict_set_count == 1
2532 && (conflict_set->flags & BINDING_CONFLICT))
2534 /* No known conflicts now, but there was a conflict. This means
2535 * at some point, there was a conflict and we changed this
2536 * binding's policy to ask and set the conflicting key. The
2537 * conflict can go away if there is not a cross sig between the
2538 * two keys. In this case, just silently clear the conflict and
2539 * reset the policy to auto. */
2542 log_debug ("TOFU: binding <key: %s, user id: %s> had a conflict, but it's been resolved (probably via cross sig).\n",
2543 fingerprint, email);
2545 effective_policy = TOFU_POLICY_AUTO;
2551 if (conflict_set_count == 1)
2553 /* No conflicts and never marked as conflicting. */
2555 log_assert (!conflict);
2557 effective_policy = TOFU_POLICY_AUTO;
2562 /* There is a conflicting key. */
2563 log_assert (conflict_set_count > 1);
2564 effective_policy = TOFU_POLICY_ASK;
2565 conflict = xstrdup (conflict_set->next->d);
2568 log_assert (policy == _tofu_GET_POLICY_ERROR
2569 || policy == TOFU_POLICY_NONE
2570 || policy == TOFU_POLICY_AUTO
2571 || policy == TOFU_POLICY_GOOD
2572 || policy == TOFU_POLICY_UNKNOWN
2573 || policy == TOFU_POLICY_BAD
2574 || policy == TOFU_POLICY_ASK);
2575 /* Everything but NONE. */
2576 log_assert (effective_policy == _tofu_GET_POLICY_ERROR
2577 || effective_policy == TOFU_POLICY_AUTO
2578 || effective_policy == TOFU_POLICY_GOOD
2579 || effective_policy == TOFU_POLICY_UNKNOWN
2580 || effective_policy == TOFU_POLICY_BAD
2581 || effective_policy == TOFU_POLICY_ASK);
2583 if (effective_policy != TOFU_POLICY_ASK && conflict)
2586 /* If we don't have a record of this binding, its effective policy
2587 * changed, or conflict changed, update the DB. */
2588 if (effective_policy != _tofu_GET_POLICY_ERROR
2589 && (/* New binding. */
2590 policy == TOFU_POLICY_NONE
2591 /* effective_policy changed. */
2592 || effective_policy != effective_policy_orig
2593 /* conflict changed. */
2594 || (conflict != conflict_orig
2595 && (!conflict || !conflict_orig
2596 || strcmp (conflict, conflict_orig) != 0))))
2598 if (record_binding (dbs, fingerprint, email, user_id,
2599 policy == TOFU_POLICY_NONE ? TOFU_POLICY_AUTO : policy,
2600 effective_policy, conflict, 1, 0, now) != 0)
2601 log_error (_("error setting TOFU binding's policy"
2602 " to %s\n"), tofu_policy_str (policy));
2605 /* If the caller wants the set of conflicts, return it. */
2606 if (effective_policy == TOFU_POLICY_ASK && conflict_setp)
2609 conflict_set = build_conflict_set (dbs, pk, fingerprint, email);
2610 *conflict_setp = conflict_set;
2614 free_strlist (conflict_set);
2617 *conflict_setp = NULL;
2620 xfree (conflict_orig);
2621 if (conflict != conflict_orig)
2623 free_strlist (results);
2625 return effective_policy;
2629 /* Return the trust level (TRUST_NEVER, etc.) for the binding
2630 * <FINGERPRINT, EMAIL> (email is already normalized). If no policy
2631 * is registered, returns TOFU_POLICY_NONE. If an error occurs,
2632 * returns _tofu_GET_TRUST_ERROR.
2634 * PK is the public key object for FINGERPRINT.
2636 * USER_ID is the unadulterated user id.
2638 * If MAY_ASK is set, then we may interact with the user. This is
2639 * necessary if there is a conflict or the binding's policy is
2640 * TOFU_POLICY_ASK. In the case of a conflict, we set the new
2641 * conflicting binding's policy to TOFU_POLICY_ASK. In either case,
2642 * we return TRUST_UNDEFINED. Note: if MAY_ASK is set, then this
2643 * function must not be called while in a transaction! */
2644 static enum tofu_policy
2645 get_trust (ctrl_t ctrl, PKT_public_key *pk,
2646 const char *fingerprint, const char *email,
2647 const char *user_id, int may_ask, time_t now)
2649 tofu_dbs_t dbs = ctrl->tofu.dbs;
2650 int in_transaction = 0;
2651 enum tofu_policy policy;
2654 strlist_t conflict_set = NULL;
2655 int trust_level = TRUST_UNKNOWN;
2661 log_assert (dbs->in_transaction == 0);
2666 log_assert (pk_is_primary (pk));
2668 /* Make sure _tofu_GET_TRUST_ERROR isn't equal to any of the trust
2670 log_assert (_tofu_GET_TRUST_ERROR != TRUST_UNKNOWN
2671 && _tofu_GET_TRUST_ERROR != TRUST_EXPIRED
2672 && _tofu_GET_TRUST_ERROR != TRUST_UNDEFINED
2673 && _tofu_GET_TRUST_ERROR != TRUST_NEVER
2674 && _tofu_GET_TRUST_ERROR != TRUST_MARGINAL
2675 && _tofu_GET_TRUST_ERROR != TRUST_FULLY
2676 && _tofu_GET_TRUST_ERROR != TRUST_ULTIMATE);
2678 /* If the key is ultimately trusted, there is nothing to do. */
2682 keyid_from_pk (pk, kid);
2683 if (tdb_keyid_is_utk (kid))
2685 trust_level = TRUST_ULTIMATE;
2690 begin_transaction (ctrl, 0);
2693 policy = get_policy (dbs, pk, fingerprint, user_id, email, &conflict_set, now);
2694 if (policy == TOFU_POLICY_AUTO)
2696 policy = opt.tofu_default_policy;
2698 log_debug ("TOFU: binding <key: %s, user id: %s>'s policy is"
2699 " auto (default: %s).\n",
2701 tofu_policy_str (opt.tofu_default_policy));
2705 case TOFU_POLICY_AUTO:
2706 case TOFU_POLICY_GOOD:
2707 case TOFU_POLICY_UNKNOWN:
2708 case TOFU_POLICY_BAD:
2709 /* The saved judgement is auto -> auto, good, unknown or bad.
2710 * We don't need to ask the user anything. */
2712 log_debug ("TOFU: Known binding <key: %s, user id: %s>'s policy: %s\n",
2713 fingerprint, email, tofu_policy_str (policy));
2714 trust_level = tofu_policy_to_trust_level (policy);
2717 case TOFU_POLICY_ASK:
2718 /* We need to ask the user what to do. */
2721 case _tofu_GET_POLICY_ERROR:
2722 trust_level = _tofu_GET_TRUST_ERROR;
2726 log_bug ("%s: Impossible value for policy (%d)\n", __func__, policy);
2732 * 1. The saved policy is auto and the default policy is ask
2733 * (get_policy() == TOFU_POLICY_AUTO
2734 * && opt.tofu_default_policy == TOFU_POLICY_ASK)
2736 * 2. The saved policy is ask (either last time the user selected
2737 * accept once or reject once or there was a conflict and this
2738 * binding's policy was changed from auto to ask)
2739 * (policy == TOFU_POLICY_ASK).
2741 log_assert (policy == TOFU_POLICY_ASK);
2745 /* We can't be in a normal transaction in ask_about_binding. */
2746 end_transaction (ctrl, 0);
2749 /* If we get here, we need to ask the user about the binding. */
2750 ask_about_binding (ctrl,
2761 for (iter = conflict_set; iter; iter = iter->next)
2762 show_statistics (dbs, iter->d, email,
2763 TOFU_POLICY_ASK, NULL, 1, now);
2765 trust_level = TRUST_UNDEFINED;
2768 /* Mark any conflicting bindings that have an automatic policy as
2769 * now requiring confirmation. Note: we do this after we ask for
2770 * confirmation so that when the current policy is printed, it is
2772 if (! in_transaction)
2774 begin_transaction (ctrl, 0);
2778 /* The conflict set should always contain at least one element:
2779 * the current key. */
2780 log_assert (conflict_set);
2782 for (iter = conflict_set->next; iter; iter = iter->next)
2784 /* We don't immediately set the effective policy to 'ask,
2786 rc = gpgsql_exec_printf
2787 (dbs->db, NULL, NULL, &sqerr,
2788 "update bindings set effective_policy = %d, conflict = %Q"
2789 " where email = %Q and fingerprint = %Q and effective_policy != %d;",
2790 TOFU_POLICY_NONE, fingerprint,
2791 email, iter->d, TOFU_POLICY_ASK);
2794 log_error (_("error changing TOFU policy: %s\n"), sqerr);
2795 print_further_info ("binding: <key: %s, user id: %s>",
2796 fingerprint, user_id);
2797 sqlite3_free (sqerr);
2799 rc = gpg_error (GPG_ERR_GENERAL);
2802 log_debug ("Set %s to conflict with %s\n",
2803 iter->d, fingerprint);
2808 end_transaction (ctrl, 0);
2810 free_strlist (conflict_set);
2816 /* Return a malloced string of the form
2818 * The caller should replace all '~' in the returned string by a space
2819 * and also free the returned string.
2821 * This is actually a bad hack which may not work correctly with all
2825 time_ago_str (long long int t)
2827 /* It would be nice to use a macro to do this, but gettext
2828 works on the unpreprocessed code. */
2829 #define MIN_SECS (60)
2830 #define HOUR_SECS (60 * MIN_SECS)
2831 #define DAY_SECS (24 * HOUR_SECS)
2832 #define WEEK_SECS (7 * DAY_SECS)
2833 #define MONTH_SECS (30 * DAY_SECS)
2834 #define YEAR_SECS (365 * DAY_SECS)
2836 if (t > 2 * YEAR_SECS)
2838 long long int c = t / YEAR_SECS;
2839 return xtryasprintf (ngettext("%lld~year", "%lld~years", c), c);
2841 if (t > 2 * MONTH_SECS)
2843 long long int c = t / MONTH_SECS;
2844 return xtryasprintf (ngettext("%lld~month", "%lld~months", c), c);
2846 if (t > 2 * WEEK_SECS)
2848 long long int c = t / WEEK_SECS;
2849 return xtryasprintf (ngettext("%lld~week", "%lld~weeks", c), c);
2851 if (t > 2 * DAY_SECS)
2853 long long int c = t / DAY_SECS;
2854 return xtryasprintf (ngettext("%lld~day", "%lld~days", c), c);
2856 if (t > 2 * HOUR_SECS)
2858 long long int c = t / HOUR_SECS;
2859 return xtryasprintf (ngettext("%lld~hour", "%lld~hours", c), c);
2861 if (t > 2 * MIN_SECS)
2863 long long int c = t / MIN_SECS;
2864 return xtryasprintf (ngettext("%lld~minute", "%lld~minutes", c), c);
2866 return xtryasprintf (ngettext("%lld~second", "%lld~seconds", t), t);
2870 /* If FP is NULL, write TOFU_STATS status line. If FP is not NULL
2871 * write a "tfs" record to that stream. */
2873 write_stats_status (estream_t fp,
2874 enum tofu_policy policy,
2875 unsigned long signature_count,
2876 unsigned long signature_first_seen,
2877 unsigned long signature_most_recent,
2878 unsigned long signature_days,
2879 unsigned long encryption_count,
2880 unsigned long encryption_first_done,
2881 unsigned long encryption_most_recent,
2882 unsigned long encryption_days)
2888 /* Use the euclidean distance (m = sqrt(a^2 + b^2)) rather then the
2889 sum of the magnitudes (m = a + b) to ensure a balance between
2890 verified signatures and encrypted messages. */
2891 days = sqrtu32 (signature_days * signature_days
2892 + encryption_days * encryption_days);
2895 validity = 1; /* Key without history. */
2896 else if (days < 2 * BASIC_TRUST_THRESHOLD)
2897 validity = 2; /* Key with too little history. */
2898 else if (days < 2 * FULL_TRUST_THRESHOLD)
2899 validity = 3; /* Key with enough history for basic trust. */
2901 validity = 4; /* Key with a lot of history. */
2903 if (policy == TOFU_POLICY_ASK)
2904 summary = 0; /* Key requires attention. */
2910 es_fprintf (fp, "tfs:1:%d:%lu:%lu:%s:%lu:%lu:%lu:%lu:%d:%lu:%lu:\n",
2911 summary, signature_count, encryption_count,
2912 tofu_policy_str (policy),
2913 signature_first_seen, signature_most_recent,
2914 encryption_first_done, encryption_most_recent,
2915 validity, signature_days, encryption_days);
2919 write_status_printf (STATUS_TOFU_STATS,
2920 "%d %lu %lu %s %lu %lu %lu %lu %d %lu %lu",
2924 tofu_policy_str (policy),
2925 signature_first_seen,
2926 signature_most_recent,
2927 encryption_first_done,
2928 encryption_most_recent,
2930 signature_days, encryption_days);
2934 /* Note: If OUTFP is not NULL, this function merely prints a "tfs" record
2937 * POLICY is the key's policy (as returned by get_policy).
2939 * Returns 0 if if ONLY_STATUS_FD is set. Otherwise, returns whether
2940 * the caller should call show_warning after iterating over all user
2944 show_statistics (tofu_dbs_t dbs,
2945 const char *fingerprint, const char *email,
2946 enum tofu_policy policy,
2947 estream_t outfp, int only_status_fd, time_t now)
2949 char *fingerprint_pp;
2951 strlist_t strlist = NULL;
2954 unsigned long signature_first_seen = 0;
2955 unsigned long signature_most_recent = 0;
2956 unsigned long signature_count = 0;
2957 unsigned long signature_days = 0;
2958 unsigned long encryption_first_done = 0;
2959 unsigned long encryption_most_recent = 0;
2960 unsigned long encryption_count = 0;
2961 unsigned long encryption_days = 0;
2963 int show_warning = 0;
2965 if (only_status_fd && ! is_status_enabled ())
2968 fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
2970 /* Get the signature stats. */
2971 rc = gpgsql_exec_printf
2972 (dbs->db, strings_collect_cb, &strlist, &err,
2973 "select count (*), min (signatures.time), max (signatures.time)\n"
2974 " from signatures\n"
2975 " left join bindings on signatures.binding = bindings.oid\n"
2976 " where fingerprint = %Q and email = %Q;",
2977 fingerprint, email);
2980 log_error (_("error reading TOFU database: %s\n"), err);
2981 print_further_info ("getting signature statistics");
2983 rc = gpg_error (GPG_ERR_GENERAL);
2986 rc = gpgsql_exec_printf
2987 (dbs->db, strings_collect_cb, &strlist, &err,
2988 "select count (*) from\n"
2989 " (select round(signatures.time / (24 * 60 * 60)) day\n"
2990 " from signatures\n"
2991 " left join bindings on signatures.binding = bindings.oid\n"
2992 " where fingerprint = %Q and email = %Q\n"
2994 fingerprint, email);
2997 log_error (_("error reading TOFU database: %s\n"), err);
2998 print_further_info ("getting signature statistics (by day)");
3000 rc = gpg_error (GPG_ERR_GENERAL);
3006 /* We expect exactly 4 elements. */
3007 log_assert (strlist->next);
3008 log_assert (strlist->next->next);
3009 log_assert (strlist->next->next->next);
3010 log_assert (! strlist->next->next->next->next);
3012 string_to_ulong (&signature_days, strlist->d, -1, __LINE__);
3013 string_to_ulong (&signature_count, strlist->next->d, -1, __LINE__);
3014 string_to_ulong (&signature_first_seen,
3015 strlist->next->next->d, -1, __LINE__);
3016 string_to_ulong (&signature_most_recent,
3017 strlist->next->next->next->d, -1, __LINE__);
3019 free_strlist (strlist);
3023 /* Get the encryption stats. */
3024 rc = gpgsql_exec_printf
3025 (dbs->db, strings_collect_cb, &strlist, &err,
3026 "select count (*), min (encryptions.time), max (encryptions.time)\n"
3027 " from encryptions\n"
3028 " left join bindings on encryptions.binding = bindings.oid\n"
3029 " where fingerprint = %Q and email = %Q;",
3030 fingerprint, email);
3033 log_error (_("error reading TOFU database: %s\n"), err);
3034 print_further_info ("getting encryption statistics");
3036 rc = gpg_error (GPG_ERR_GENERAL);
3039 rc = gpgsql_exec_printf
3040 (dbs->db, strings_collect_cb, &strlist, &err,
3041 "select count (*) from\n"
3042 " (select round(encryptions.time / (24 * 60 * 60)) day\n"
3043 " from encryptions\n"
3044 " left join bindings on encryptions.binding = bindings.oid\n"
3045 " where fingerprint = %Q and email = %Q\n"
3047 fingerprint, email);
3050 log_error (_("error reading TOFU database: %s\n"), err);
3051 print_further_info ("getting encryption statistics (by day)");
3053 rc = gpg_error (GPG_ERR_GENERAL);
3059 /* We expect exactly 4 elements. */
3060 log_assert (strlist->next);
3061 log_assert (strlist->next->next);
3062 log_assert (strlist->next->next->next);
3063 log_assert (! strlist->next->next->next->next);
3065 string_to_ulong (&encryption_days, strlist->d, -1, __LINE__);
3066 string_to_ulong (&encryption_count, strlist->next->d, -1, __LINE__);
3067 string_to_ulong (&encryption_first_done,
3068 strlist->next->next->d, -1, __LINE__);
3069 string_to_ulong (&encryption_most_recent,
3070 strlist->next->next->next->d, -1, __LINE__);
3072 free_strlist (strlist);
3077 write_status_text_and_buffer (STATUS_TOFU_USER, fingerprint,
3078 email, strlen (email), 0);
3080 write_stats_status (outfp, policy,
3082 signature_first_seen,
3083 signature_most_recent,
3086 encryption_first_done,
3087 encryption_most_recent,
3090 if (!outfp && !only_status_fd)
3095 fp = es_fopenmem (0, "rw,samethread");
3097 log_fatal ("error creating memory stream: %s\n",
3098 gpg_strerror (gpg_error_from_syserror()));
3100 if (signature_count == 0 && encryption_count == 0)
3103 _("%s: Verified 0~signatures and encrypted 0~messages."),
3108 if (signature_count == 0)
3109 es_fprintf (fp, _("%s: Verified 0 signatures."), email);
3112 /* TRANSLATORS: The final %s is replaced by a string like
3114 char *ago_str = time_ago_str (now - signature_first_seen);
3117 ngettext("%s: Verified %ld~signature in the past %s.",
3118 "%s: Verified %ld~signatures in the past %s.",
3120 email, signature_count, ago_str);
3126 if (encryption_count == 0)
3127 es_fprintf (fp, _("Encrypted 0 messages."));
3130 char *ago_str = time_ago_str (now - encryption_first_done);
3132 /* TRANSLATORS: The final %s is replaced by a string like
3135 ngettext("Encrypted %ld~message in the past %s.",
3136 "Encrypted %ld~messages in the past %s.",
3138 encryption_count, ago_str);
3146 es_fprintf (fp, _("(policy: %s)"), tofu_policy_str (policy));
3148 es_fputs ("\n", fp);
3154 if (es_fclose_snatch (fp, (void **) &tmpmsg, NULL))
3155 log_fatal ("error snatching memory stream\n");
3156 msg = format_text (tmpmsg, 0, 72, 80);
3159 /* Print a status line but suppress the trailing LF.
3160 * Spaces are not percent escaped. */
3162 write_status_buffer (STATUS_TOFU_STATS_LONG,
3163 msg, strlen (msg)-1, -1);
3165 /* Remove the non-breaking space markers. */
3166 for (p=msg; *p; p++)
3171 log_string (GPGRT_LOG_INFO, msg);
3174 if (policy == TOFU_POLICY_AUTO)
3176 if (signature_count == 0)
3177 log_info (_("Warning: we have yet to see"
3178 " a message signed using this key and user id!\n"));
3179 else if (signature_count == 1)
3180 log_info (_("Warning: we've only seen one message"
3181 " signed using this key and user id!\n"));
3183 if (encryption_count == 0)
3184 log_info (_("Warning: you have yet to encrypt"
3185 " a message to this key!\n"));
3186 else if (encryption_count == 1)
3187 log_info (_("Warning: you have only encrypted"
3188 " one message to this key!\n"));
3190 /* Cf. write_stats_status */
3191 if (sqrtu32 (encryption_count * encryption_count
3192 + signature_count * signature_count)
3193 < 2 * BASIC_TRUST_THRESHOLD)
3199 xfree (fingerprint_pp);
3201 return show_warning;
3205 show_warning (const char *fingerprint, strlist_t user_id_list)
3207 char *set_policy_command;
3211 set_policy_command =
3212 xasprintf ("gpg --tofu-policy bad %s", fingerprint);
3216 ("Warning: if you think you've seen more signatures "
3217 "by this key and user id, then this key might be a "
3218 "forgery! Carefully examine the email address for small "
3219 "variations. If the key is suspect, then use\n"
3221 "to mark it as being bad.\n",
3222 "Warning: if you think you've seen more signatures "
3223 "by this key and these user ids, then this key might be a "
3224 "forgery! Carefully examine the email addresses for small "
3225 "variations. If the key is suspect, then use\n"
3227 "to mark it as being bad.\n",
3228 strlist_length (user_id_list)),
3229 set_policy_command);
3231 text = format_text (tmpmsg, 0, 72, 80);
3233 log_string (GPGRT_LOG_INFO, text);
3236 es_free (set_policy_command);
3240 /* Extract the email address from a user id and normalize it. If the
3241 user id doesn't contain an email address, then we use the whole
3242 user_id and normalize that. The returned string must be freed. */
3244 email_from_user_id (const char *user_id)
3246 char *email = mailbox_from_userid (user_id);
3249 /* Hmm, no email address was provided or we are out of core. Just
3250 take the lower-case version of the whole user id. It could be
3251 a hostname, for instance. */
3252 email = ascii_strlwr (xstrdup (user_id));
3258 /* Register the signature with the bindings <fingerprint, USER_ID>,
3259 for each USER_ID in USER_ID_LIST. The fingerprint is taken from
3260 the primary key packet PK.
3262 SIG_DIGEST_BIN is the binary representation of the message's
3263 digest. SIG_DIGEST_BIN_LEN is its length.
3265 SIG_TIME is the time that the signature was generated.
3267 ORIGIN is a free-formed string describing the origin of the
3268 signature. If this was from an email and the Claws MUA was used,
3269 then this should be something like: "email:claws". If this is
3270 NULL, the default is simply "unknown".
3272 If MAY_ASK is 1, then this function may interact with the user.
3273 This is necessary if there is a conflict or the binding's policy is
3276 This function returns 0 on success and an error code if an error
3279 tofu_register_signature (ctrl_t ctrl,
3280 PKT_public_key *pk, strlist_t user_id_list,
3281 const byte *sig_digest_bin, int sig_digest_bin_len,
3282 time_t sig_time, const char *origin)
3284 time_t now = gnupg_get_time ();
3287 char *fingerprint = NULL;
3294 dbs = opendbs (ctrl);
3297 rc = gpg_error (GPG_ERR_GENERAL);
3298 log_error (_("error opening TOFU database: %s\n"),
3303 /* We do a query and then an insert. Make sure they are atomic
3304 by wrapping them in a transaction. */
3305 rc = begin_transaction (ctrl, 0);
3309 log_assert (pk_is_primary (pk));
3311 sig_digest = make_radix64_string (sig_digest_bin, sig_digest_bin_len);
3312 fingerprint = hexfingerprint (pk, NULL, 0);
3315 /* The default origin is simply "unknown". */
3318 for (user_id = user_id_list; user_id; user_id = user_id->next)
3320 email = email_from_user_id (user_id->d);
3323 log_debug ("TOFU: Registering signature %s with binding"
3324 " <key: %s, user id: %s>\n",
3325 sig_digest, fingerprint, email);
3327 /* Make sure the binding exists and record any TOFU
3329 if (get_trust (ctrl, pk, fingerprint, email, user_id->d, 0, now)
3330 == _tofu_GET_TRUST_ERROR)
3332 rc = gpg_error (GPG_ERR_GENERAL);
3337 /* If we've already seen this signature before, then don't add
3340 (dbs->db, &dbs->s.register_already_seen,
3341 get_single_unsigned_long_cb2, &c, &err,
3342 "select count (*)\n"
3343 " from signatures left join bindings\n"
3344 " on signatures.binding = bindings.oid\n"
3345 " where fingerprint = ? and email = ? and sig_time = ?\n"
3346 " and sig_digest = ?",
3347 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3348 GPGSQL_ARG_LONG_LONG, (long long) sig_time,
3349 GPGSQL_ARG_STRING, sig_digest,
3353 log_error (_("error reading TOFU database: %s\n"), err);
3354 print_further_info ("checking existence");
3356 rc = gpg_error (GPG_ERR_GENERAL);
3359 /* Duplicates! This should not happen. In particular,
3360 because <fingerprint, email, sig_time, sig_digest> is the
3362 log_debug ("SIGNATURES DB contains duplicate records"
3363 " <key: %s, email: %s, time: 0x%lx, sig: %s,"
3365 " Please report.\n",
3366 fingerprint, email, (unsigned long) sig_time,
3367 sig_digest, origin);
3371 log_debug ("Already observed the signature and binding"
3372 " <key: %s, email: %s, time: 0x%lx, sig: %s,"
3374 fingerprint, email, (unsigned long) sig_time,
3375 sig_digest, origin);
3377 else if (opt.dry_run)
3379 log_info ("TOFU database update skipped due to --dry-run\n");
3382 /* This is the first time that we've seen this signature and
3383 binding. Record it. */
3386 log_debug ("TOFU: Saving signature"
3387 " <key: %s, user id: %s, sig: %s>\n",
3388 fingerprint, email, sig_digest);
3390 log_assert (c == 0);
3393 (dbs->db, &dbs->s.register_signature, NULL, NULL, &err,
3394 "insert into signatures\n"
3395 " (binding, sig_digest, origin, sig_time, time)\n"
3397 " ((select oid from bindings\n"
3398 " where fingerprint = ? and email = ?),\n"
3400 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3401 GPGSQL_ARG_STRING, sig_digest, GPGSQL_ARG_STRING, origin,
3402 GPGSQL_ARG_LONG_LONG, (long long) sig_time,
3403 GPGSQL_ARG_LONG_LONG, (long long) now,
3407 log_error (_("error updating TOFU database: %s\n"), err);
3408 print_further_info ("insert signatures");
3410 rc = gpg_error (GPG_ERR_GENERAL);
3421 rollback_transaction (ctrl);
3423 rc = end_transaction (ctrl, 0);
3425 xfree (fingerprint);
3432 tofu_register_encryption (ctrl_t ctrl,
3433 PKT_public_key *pk, strlist_t user_id_list,
3436 time_t now = gnupg_get_time ();
3440 int free_user_id_list = 0;
3441 char *fingerprint = NULL;
3445 dbs = opendbs (ctrl);
3448 rc = gpg_error (GPG_ERR_GENERAL);
3449 log_error (_("error opening TOFU database: %s\n"),
3454 if (/* We need the key block to find the primary key. */
3455 ! pk_is_primary (pk)
3456 /* We need the key block to find all user ids. */
3458 kb = get_pubkeyblock (pk->keyid);
3460 /* Make sure PK is a primary key. */
3461 if (! pk_is_primary (pk))
3462 pk = kb->pkt->pkt.public_key;
3466 /* Use all non-revoked user ids. Do use expired user ids. */
3469 while ((n = find_next_kbnode (n, PKT_USER_ID)))
3471 PKT_user_id *uid = n->pkt->pkt.user_id;
3473 if (uid->is_revoked)
3476 add_to_strlist (&user_id_list, uid->name);
3479 free_user_id_list = 1;
3482 log_info (_("WARNING: Encrypting to %s, which has no "
3483 "non-revoked user ids.\n"),
3484 keystr (pk->keyid));
3487 fingerprint = hexfingerprint (pk, NULL, 0);
3489 tofu_begin_batch_update (ctrl);
3490 tofu_resume_batch_transaction (ctrl);
3492 for (user_id = user_id_list; user_id; user_id = user_id->next)
3494 char *email = email_from_user_id (user_id->d);
3496 /* Make sure the binding exists and that we recognize any
3498 int tl = get_trust (ctrl, pk, fingerprint, email, user_id->d,
3500 if (tl == _tofu_GET_TRUST_ERROR)
3503 rc = gpg_error (GPG_ERR_GENERAL);
3509 (dbs->db, &dbs->s.register_encryption, NULL, NULL, &err,
3510 "insert into encryptions\n"
3511 " (binding, time)\n"
3513 " ((select oid from bindings\n"
3514 " where fingerprint = ? and email = ?),\n"
3516 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3517 GPGSQL_ARG_LONG_LONG, (long long) now,
3521 log_error (_("error updating TOFU database: %s\n"), err);
3522 print_further_info ("insert encryption");
3524 rc = gpg_error (GPG_ERR_GENERAL);
3531 tofu_end_batch_update (ctrl);
3534 release_kbnode (kb);
3536 if (free_user_id_list)
3537 free_strlist (user_id_list);
3539 xfree (fingerprint);
3545 /* Combine a trust level returned from the TOFU trust model with a
3546 trust level returned by the PGP trust model. This is primarily of
3547 interest when the trust model is tofu+pgp (TM_TOFU_PGP).
3549 This function ors together the upper bits (the values not covered
3550 by TRUST_MASK, i.e., TRUST_FLAG_REVOKED, etc.). */
3552 tofu_wot_trust_combine (int tofu_base, int wot_base)
3554 int tofu = tofu_base & TRUST_MASK;
3555 int wot = wot_base & TRUST_MASK;
3556 int upper = (tofu_base & ~TRUST_MASK) | (wot_base & ~TRUST_MASK);
3558 log_assert (tofu == TRUST_UNKNOWN
3559 || tofu == TRUST_EXPIRED
3560 || tofu == TRUST_UNDEFINED
3561 || tofu == TRUST_NEVER
3562 || tofu == TRUST_MARGINAL
3563 || tofu == TRUST_FULLY
3564 || tofu == TRUST_ULTIMATE);
3565 log_assert (wot == TRUST_UNKNOWN
3566 || wot == TRUST_EXPIRED
3567 || wot == TRUST_UNDEFINED
3568 || wot == TRUST_NEVER
3569 || wot == TRUST_MARGINAL
3570 || wot == TRUST_FULLY
3571 || wot == TRUST_ULTIMATE);
3573 /* We first consider negative trust policys. These trump positive
3575 if (tofu == TRUST_NEVER || wot == TRUST_NEVER)
3576 /* TRUST_NEVER trumps everything else. */
3577 return upper | TRUST_NEVER;
3578 if (tofu == TRUST_EXPIRED || wot == TRUST_EXPIRED)
3579 /* TRUST_EXPIRED trumps everything but TRUST_NEVER. */
3580 return upper | TRUST_EXPIRED;
3582 /* Now we only have positive or neutral trust policies. We take
3584 if (tofu == TRUST_ULTIMATE)
3585 return upper | TRUST_ULTIMATE | TRUST_FLAG_TOFU_BASED;
3586 if (wot == TRUST_ULTIMATE)
3587 return upper | TRUST_ULTIMATE;
3589 if (tofu == TRUST_FULLY)
3590 return upper | TRUST_FULLY | TRUST_FLAG_TOFU_BASED;
3591 if (wot == TRUST_FULLY)
3592 return upper | TRUST_FULLY;
3594 if (tofu == TRUST_MARGINAL)
3595 return upper | TRUST_MARGINAL | TRUST_FLAG_TOFU_BASED;
3596 if (wot == TRUST_MARGINAL)
3597 return upper | TRUST_MARGINAL;
3599 if (tofu == TRUST_UNDEFINED)
3600 return upper | TRUST_UNDEFINED | TRUST_FLAG_TOFU_BASED;
3601 if (wot == TRUST_UNDEFINED)
3602 return upper | TRUST_UNDEFINED;
3604 return upper | TRUST_UNKNOWN;
3608 /* Write a "tfs" record for a --with-colons listing. */
3610 tofu_write_tfs_record (ctrl_t ctrl, estream_t fp,
3611 PKT_public_key *pk, const char *user_id)
3613 time_t now = gnupg_get_time ();
3618 enum tofu_policy policy;
3621 return 0; /* No TOFU stats possible for an empty ID. */
3623 dbs = opendbs (ctrl);
3626 err = gpg_error (GPG_ERR_GENERAL);
3627 log_error (_("error opening TOFU database: %s\n"), gpg_strerror (err));
3631 fingerprint = hexfingerprint (pk, NULL, 0);
3632 email = email_from_user_id (user_id);
3633 policy = get_policy (dbs, pk, fingerprint, user_id, email, NULL, now);
3635 show_statistics (dbs, fingerprint, email, policy, fp, 0, now);
3638 xfree (fingerprint);
3643 /* Return the validity (TRUST_NEVER, etc.) of the bindings
3644 <FINGERPRINT, USER_ID>, for each USER_ID in USER_ID_LIST. If
3645 USER_ID_LIST->FLAG is set, then the id is considered to be expired.
3647 PK is the primary key packet.
3649 If MAY_ASK is 1 and the policy is TOFU_POLICY_ASK, then the user
3650 will be prompted to choose a policy. If MAY_ASK is 0 and the
3651 policy is TOFU_POLICY_ASK, then TRUST_UNKNOWN is returned.
3653 Returns TRUST_UNDEFINED if an error occurs. */
3655 tofu_get_validity (ctrl_t ctrl, PKT_public_key *pk, strlist_t user_id_list,
3658 time_t now = gnupg_get_time ();
3660 char *fingerprint = NULL;
3662 int trust_level = TRUST_UNKNOWN;
3664 int bindings_valid = 0;
3665 int need_warning = 0;
3667 dbs = opendbs (ctrl);
3670 log_error (_("error opening TOFU database: %s\n"),
3671 gpg_strerror (GPG_ERR_GENERAL));
3672 return TRUST_UNDEFINED;
3675 fingerprint = hexfingerprint (pk, NULL, 0);
3677 tofu_begin_batch_update (ctrl);
3678 /* Start the batch transaction now. */
3679 tofu_resume_batch_transaction (ctrl);
3681 for (user_id = user_id_list; user_id; user_id = user_id->next, bindings ++)
3683 char *email = email_from_user_id (user_id->d);
3685 /* Always call get_trust to make sure the binding is
3687 int tl = get_trust (ctrl, pk, fingerprint, email, user_id->d,
3689 if (tl == _tofu_GET_TRUST_ERROR)
3692 trust_level = TRUST_UNDEFINED;
3698 log_debug ("TOFU: validity for <key: %s, user id: %s>: %s%s.\n",
3700 trust_value_to_string (tl),
3701 user_id->flags ? " (but expired)" : "");
3706 if (tl != TRUST_EXPIRED)
3709 if (may_ask && tl != TRUST_ULTIMATE && tl != TRUST_EXPIRED)
3711 enum tofu_policy policy =
3712 get_policy (dbs, pk, fingerprint, user_id->d, email, NULL, now);
3715 show_statistics (dbs, fingerprint, email, policy, NULL, 0, now);
3718 if (tl == TRUST_NEVER)
3719 trust_level = TRUST_NEVER;
3720 else if (tl == TRUST_EXPIRED)
3721 /* Ignore expired bindings in the trust calculation. */
3723 else if (tl > trust_level)
3725 /* The expected values: */
3726 log_assert (tl == TRUST_UNKNOWN || tl == TRUST_UNDEFINED
3727 || tl == TRUST_MARGINAL || tl == TRUST_FULLY
3728 || tl == TRUST_ULTIMATE);
3730 /* We assume the following ordering: */
3731 log_assert (TRUST_UNKNOWN < TRUST_UNDEFINED);
3732 log_assert (TRUST_UNDEFINED < TRUST_MARGINAL);
3733 log_assert (TRUST_MARGINAL < TRUST_FULLY);
3734 log_assert (TRUST_FULLY < TRUST_ULTIMATE);
3743 show_warning (fingerprint, user_id_list);
3746 tofu_end_batch_update (ctrl);
3748 xfree (fingerprint);
3750 if (bindings_valid == 0)
3753 log_debug ("no (of %d) valid bindings."
3754 " Can't get TOFU validity for this set of user ids.\n",
3762 /* Set the policy for all non-revoked user ids in the keyblock KB to
3765 If no key is available with the specified key id, then this
3766 function returns GPG_ERR_NO_PUBKEY.
3768 Returns 0 on success and an error code otherwise. */
3770 tofu_set_policy (ctrl_t ctrl, kbnode_t kb, enum tofu_policy policy)
3773 time_t now = gnupg_get_time ();
3776 char *fingerprint = NULL;
3778 log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
3779 pk = kb->pkt->pkt.public_key;
3781 dbs = opendbs (ctrl);
3784 log_error (_("error opening TOFU database: %s\n"),
3785 gpg_strerror (GPG_ERR_GENERAL));
3786 return gpg_error (GPG_ERR_GENERAL);
3790 log_debug ("Setting TOFU policy for %s to %s\n",
3791 keystr (pk->keyid), tofu_policy_str (policy));
3792 if (! pk_is_primary (pk))
3793 log_bug ("%s: Passed a subkey, but expecting a primary key.\n", __func__);
3795 fingerprint = hexfingerprint (pk, NULL, 0);
3797 begin_transaction (ctrl, 0);
3799 for (; kb; kb = kb->next)
3801 PKT_user_id *user_id;
3804 if (kb->pkt->pkttype != PKT_USER_ID)
3807 user_id = kb->pkt->pkt.user_id;
3808 if (user_id->is_revoked)
3809 /* Skip revoked user ids. (Don't skip expired user ids, the
3810 expiry can be changed.) */
3813 email = email_from_user_id (user_id->name);
3815 err = record_binding (dbs, fingerprint, email, user_id->name,
3816 policy, TOFU_POLICY_NONE, NULL, 0, 1, now);
3819 log_error (_("error setting policy for key %s, user id \"%s\": %s"),
3820 fingerprint, email, gpg_strerror (err));
3829 rollback_transaction (ctrl);
3831 end_transaction (ctrl, 0);
3833 xfree (fingerprint);
3837 /* Return the TOFU policy for the specified binding in *POLICY. If no
3838 policy has been set for the binding, sets *POLICY to
3841 PK is a primary public key and USER_ID is a user id.
3843 Returns 0 on success and an error code otherwise. */
3845 tofu_get_policy (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *user_id,
3846 enum tofu_policy *policy)
3848 time_t now = gnupg_get_time ();
3853 /* Make sure PK is a primary key. */
3854 log_assert (pk_is_primary (pk));
3856 dbs = opendbs (ctrl);
3859 log_error (_("error opening TOFU database: %s\n"),
3860 gpg_strerror (GPG_ERR_GENERAL));
3861 return gpg_error (GPG_ERR_GENERAL);
3864 fingerprint = hexfingerprint (pk, NULL, 0);
3866 email = email_from_user_id (user_id->name);
3868 *policy = get_policy (dbs, pk, fingerprint, user_id->name, email, NULL, now);
3871 xfree (fingerprint);
3872 if (*policy == _tofu_GET_POLICY_ERROR)
3873 return gpg_error (GPG_ERR_GENERAL);
3878 tofu_notice_key_changed (ctrl_t ctrl, kbnode_t kb)
3883 char *sqlerr = NULL;
3886 /* Make sure PK is a primary key. */
3887 setup_main_keyids (kb);
3888 pk = kb->pkt->pkt.public_key;
3889 log_assert (pk_is_primary (pk));
3891 dbs = opendbs (ctrl);
3894 log_error (_("error opening TOFU database: %s\n"),
3895 gpg_strerror (GPG_ERR_GENERAL));
3896 return gpg_error (GPG_ERR_GENERAL);
3899 fingerprint = hexfingerprint (pk, NULL, 0);
3901 rc = gpgsql_stepx (dbs->db, NULL, NULL, NULL, &sqlerr,
3902 "update bindings set effective_policy = ?"
3903 " where fingerprint = ?;",
3904 GPGSQL_ARG_INT, (int) TOFU_POLICY_NONE,
3905 GPGSQL_ARG_STRING, fingerprint,
3907 xfree (fingerprint);
3909 if (rc == _tofu_GET_POLICY_ERROR)
3910 return gpg_error (GPG_ERR_GENERAL);