1 /* tofu.c - TOFU trust model.
2  * Copyright (C) 2015, 2016 g10 Code GmbH
3  *
4  * This file is part of GnuPG.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19 
20 /* TODO:
21 
22    - Format the fingerprints nicely when printing (similar to gpg
23      --list-keys)
24  */
25 
26 #include <config.h>
27 #include <stdio.h>
28 #include <sys/stat.h>
29 #include <stdarg.h>
30 #include <sqlite3.h>
31 #include <time.h>
32 
33 #include "gpg.h"
34 #include "../common/types.h"
35 #include "../common/logging.h"
36 #include "../common/stringhelp.h"
37 #include "options.h"
38 #include "../common/mbox-util.h"
39 #include "../common/i18n.h"
40 #include "../common/ttyio.h"
41 #include "trustdb.h"
42 #include "../common/mkdir_p.h"
43 #include "gpgsql.h"
44 #include "../common/status.h"
45 
46 #include "tofu.h"
47 
48 
49 #define CONTROL_L ('L' - 'A' + 1)
50 
51 /* Number of days with signed / ecnrypted messages required to
52  * indicate that enough history is available for basic trust.  */
53 #define BASIC_TRUST_THRESHOLD  4
54 /* Number of days with signed / encrypted messages required to
55  * indicate that a lot of history is available.  */
56 #define FULL_TRUST_THRESHOLD  21
57 
58 
59 /* A struct with data pertaining to the tofu DB.  There is one such
60    struct per session and it is cached in session's ctrl structure.
61    To initialize this or get the current singleton, call opendbs().
62    There is no need to explicitly release it; cleanup is done when the
63    CTRL object is released.  */
64 struct tofu_dbs_s
65 {
66   sqlite3 *db;
67   char *want_lock_file;
68   time_t want_lock_file_ctime;
69 
70   struct
71   {
72     sqlite3_stmt *savepoint_batch;
73     sqlite3_stmt *savepoint_batch_commit;
74 
75     sqlite3_stmt *record_binding_get_old_policy;
76     sqlite3_stmt *record_binding_update;
77     sqlite3_stmt *get_policy_select_policy_and_conflict;
78     sqlite3_stmt *get_trust_bindings_with_this_email;
79     sqlite3_stmt *get_trust_gather_other_user_ids;
80     sqlite3_stmt *get_trust_gather_signature_stats;
81     sqlite3_stmt *get_trust_gather_encryption_stats;
82     sqlite3_stmt *register_already_seen;
83     sqlite3_stmt *register_signature;
84     sqlite3_stmt *register_encryption;
85   } s;
86 
87   int in_batch_transaction;
88   int in_transaction;
89   time_t batch_update_started;
90 };
91 
92 
93 #define STRINGIFY(s) STRINGIFY2(s)
94 #define STRINGIFY2(s) #s
95 
96 /* The grouping parameters when collecting signature statistics.  */
97 
98 /* If a message is signed a couple of hours in the future, just assume
99    some clock skew.  */
100 #define TIME_AGO_FUTURE_IGNORE (2 * 60 * 60)
101 /* Days.  */
102 #define TIME_AGO_UNIT_SMALL (24 * 60 * 60)
103 #define TIME_AGO_SMALL_THRESHOLD (7 * TIME_AGO_UNIT_SMALL)
104 /* Months.  */
105 #define TIME_AGO_UNIT_MEDIUM (30 * 24 * 60 * 60)
106 #define TIME_AGO_MEDIUM_THRESHOLD (2 * TIME_AGO_UNIT_MEDIUM)
107 /* Years.  */
108 #define TIME_AGO_UNIT_LARGE (365 * 24 * 60 * 60)
109 #define TIME_AGO_LARGE_THRESHOLD (2 * TIME_AGO_UNIT_LARGE)
110 
111 /* Local prototypes.  */
112 static gpg_error_t end_transaction (ctrl_t ctrl, int only_batch);
113 static char *email_from_user_id (const char *user_id);
114 static int show_statistics (tofu_dbs_t dbs,
115                             const char *fingerprint, const char *email,
116                             enum tofu_policy policy,
117                             estream_t outfp, int only_status_fd, time_t now);
118 
119 const char *
tofu_policy_str(enum tofu_policy policy)120 tofu_policy_str (enum tofu_policy policy)
121 {
122   switch (policy)
123     {
124     case TOFU_POLICY_NONE: return "none";
125     case TOFU_POLICY_AUTO: return "auto";
126     case TOFU_POLICY_GOOD: return "good";
127     case TOFU_POLICY_UNKNOWN: return "unknown";
128     case TOFU_POLICY_BAD: return "bad";
129     case TOFU_POLICY_ASK: return "ask";
130     default: return "???";
131     }
132 }
133 
134 /* Convert a binding policy (e.g., TOFU_POLICY_BAD) to a trust level
135    (e.g., TRUST_BAD) in light of the current configuration.  */
136 int
tofu_policy_to_trust_level(enum tofu_policy policy)137 tofu_policy_to_trust_level (enum tofu_policy policy)
138 {
139   if (policy == TOFU_POLICY_AUTO)
140     /* If POLICY is AUTO, fallback to OPT.TOFU_DEFAULT_POLICY.  */
141     policy = opt.tofu_default_policy;
142 
143   switch (policy)
144     {
145     case TOFU_POLICY_AUTO:
146       /* If POLICY and OPT.TOFU_DEFAULT_POLICY are both AUTO, default
147 	 to marginal trust.  */
148       return TRUST_MARGINAL;
149     case TOFU_POLICY_GOOD:
150       return TRUST_FULLY;
151     case TOFU_POLICY_UNKNOWN:
152       return TRUST_UNKNOWN;
153     case TOFU_POLICY_BAD:
154       return TRUST_NEVER;
155     case TOFU_POLICY_ASK:
156       return TRUST_UNKNOWN;
157     default:
158       log_bug ("Bad value for trust policy: %d\n",
159 	       opt.tofu_default_policy);
160       return 0;
161     }
162 }
163 
164 
165 
166 /* Start a transaction on DB.  If ONLY_BATCH is set, then this will
167    start a batch transaction if we haven't started a batch transaction
168    and one has been requested.  */
169 static gpg_error_t
begin_transaction(ctrl_t ctrl,int only_batch)170 begin_transaction (ctrl_t ctrl, int only_batch)
171 {
172   tofu_dbs_t dbs = ctrl->tofu.dbs;
173   int rc;
174   char *err = NULL;
175 
176   log_assert (dbs);
177 
178   /* If we've been in batch update mode for a while (on average, more
179    * than 500 ms), to prevent starving other gpg processes, we drop
180    * and retake the batch lock.
181    *
182    * Note: gnupg_get_time has a one second resolution, if we wanted a
183    * higher resolution, we could use npth_clock_gettime.  */
184   if (/* No real transactions.  */
185       dbs->in_transaction == 0
186       /* There is an open batch transaction.  */
187       && dbs->in_batch_transaction
188       /* And some time has gone by since it was started.  */
189       && dbs->batch_update_started != gnupg_get_time ())
190     {
191       struct stat statbuf;
192 
193       /* If we are in a batch update, then batch updates better have
194          been enabled.  */
195       log_assert (ctrl->tofu.batch_updated_wanted);
196 
197       /* Check if another process wants to run.  (We just ignore any
198        * stat failure.  A waiter might have to wait a bit longer, but
199        * otherwise there should be no impact.)  */
200       if (gnupg_stat (dbs->want_lock_file, &statbuf) == 0
201           && statbuf.st_ctime != dbs->want_lock_file_ctime)
202         {
203           end_transaction (ctrl, 2);
204 
205           /* Yield to allow another process a chance to run.  Note:
206            * testing suggests that anything less than a 100ms tends to
207            * not result in the other process getting the lock.  */
208           gnupg_usleep (100000);
209         }
210       else
211         dbs->batch_update_started = gnupg_get_time ();
212     }
213 
214   if (/* We don't have an open batch transaction.  */
215       !dbs->in_batch_transaction
216       && (/* Batch mode is enabled or we are starting a new transaction.  */
217           ctrl->tofu.batch_updated_wanted || dbs->in_transaction == 0))
218     {
219       struct stat statbuf;
220 
221       /* We are in batch mode, but we don't have an open batch
222        * transaction.  Since the batch save point must be the outer
223        * save point, it must be taken before the inner save point.  */
224       log_assert (dbs->in_transaction == 0);
225 
226       rc = gpgsql_stepx (dbs->db, &dbs->s.savepoint_batch,
227                           NULL, NULL, &err,
228                           "begin immediate transaction;", GPGSQL_ARG_END);
229       if (rc)
230         {
231           log_error (_("error beginning transaction on TOFU database: %s\n"),
232                      err);
233           sqlite3_free (err);
234           return gpg_error (GPG_ERR_GENERAL);
235         }
236 
237       dbs->in_batch_transaction = 1;
238       dbs->batch_update_started = gnupg_get_time ();
239 
240       if (gnupg_stat (dbs->want_lock_file, &statbuf) == 0)
241         dbs->want_lock_file_ctime = statbuf.st_ctime;
242     }
243 
244   if (only_batch)
245     return 0;
246 
247   log_assert (dbs->in_transaction >= 0);
248   dbs->in_transaction ++;
249 
250   rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
251                            "savepoint inner%d;",
252                            dbs->in_transaction);
253   if (rc)
254     {
255       log_error (_("error beginning transaction on TOFU database: %s\n"),
256                  err);
257       sqlite3_free (err);
258       return gpg_error (GPG_ERR_GENERAL);
259     }
260 
261   return 0;
262 }
263 
264 
265 /* Commit a transaction.  If ONLY_BATCH is 1, then this only ends the
266  * batch transaction if we have left batch mode.  If ONLY_BATCH is 2,
267  * this commits any open batch transaction even if we are still in
268  * batch mode.  */
269 static gpg_error_t
end_transaction(ctrl_t ctrl,int only_batch)270 end_transaction (ctrl_t ctrl, int only_batch)
271 {
272   tofu_dbs_t dbs = ctrl->tofu.dbs;
273   int rc;
274   char *err = NULL;
275 
276   if (only_batch || (! only_batch && dbs->in_transaction == 1))
277     {
278       if (!dbs)
279         return 0;  /* Shortcut to allow for easier cleanup code.  */
280 
281       /* If we are releasing the batch transaction, then we better not
282          be in a normal transaction.  */
283       if (only_batch)
284         log_assert (dbs->in_transaction == 0);
285 
286       if (/* Batch mode disabled?  */
287           (!ctrl->tofu.batch_updated_wanted || only_batch == 2)
288           /* But, we still have an open batch transaction?  */
289           && dbs->in_batch_transaction)
290         {
291           /* The batch transaction is still in open, but we've left
292            * batch mode.  */
293           dbs->in_batch_transaction = 0;
294           dbs->in_transaction = 0;
295 
296           rc = gpgsql_stepx (dbs->db, &dbs->s.savepoint_batch_commit,
297                              NULL, NULL, &err,
298                              "commit transaction;", GPGSQL_ARG_END);
299           if (rc)
300             {
301               log_error (_("error committing transaction on TOFU database: %s\n"),
302                          err);
303               sqlite3_free (err);
304               return gpg_error (GPG_ERR_GENERAL);
305             }
306 
307           return 0;
308         }
309 
310       if (only_batch)
311         return 0;
312     }
313 
314   log_assert (dbs);
315   log_assert (dbs->in_transaction > 0);
316 
317   rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
318                            "release inner%d;", dbs->in_transaction);
319 
320   dbs->in_transaction --;
321 
322   if (rc)
323     {
324       log_error (_("error committing transaction on TOFU database: %s\n"),
325                  err);
326       sqlite3_free (err);
327       return gpg_error (GPG_ERR_GENERAL);
328     }
329 
330   return 0;
331 }
332 
333 
334 static gpg_error_t
rollback_transaction(ctrl_t ctrl)335 rollback_transaction (ctrl_t ctrl)
336 {
337   tofu_dbs_t dbs = ctrl->tofu.dbs;
338   int rc;
339   char *err = NULL;
340 
341   log_assert (dbs);
342   log_assert (dbs->in_transaction > 0);
343 
344   /* Be careful to not undo any progress made by closed transactions in
345      batch mode.  */
346   rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
347                            "rollback to inner%d;",
348                            dbs->in_transaction);
349 
350   dbs->in_transaction --;
351 
352   if (rc)
353     {
354       log_error (_("error rolling back transaction on TOFU database: %s\n"),
355                  err);
356       sqlite3_free (err);
357       return gpg_error (GPG_ERR_GENERAL);
358     }
359 
360   return 0;
361 }
362 
363 void
tofu_begin_batch_update(ctrl_t ctrl)364 tofu_begin_batch_update (ctrl_t ctrl)
365 {
366   ctrl->tofu.batch_updated_wanted ++;
367 }
368 
369 void
tofu_end_batch_update(ctrl_t ctrl)370 tofu_end_batch_update (ctrl_t ctrl)
371 {
372   log_assert (ctrl->tofu.batch_updated_wanted > 0);
373   ctrl->tofu.batch_updated_wanted --;
374   end_transaction (ctrl, 1);
375 }
376 
377 /* Suspend any extant batch transaction (it is safe to call this even
378    no batch transaction has been started).  Note: you cannot suspend a
379    batch transaction if you are in a normal transaction.  The batch
380    transaction can be resumed explicitly by calling
381    tofu_resume_batch_transaction or implicitly by starting a normal
382    transaction.  */
383 static void
tofu_suspend_batch_transaction(ctrl_t ctrl)384 tofu_suspend_batch_transaction (ctrl_t ctrl)
385 {
386   end_transaction (ctrl, 2);
387 }
388 
389 /* Resume a batch transaction if there is no extant batch transaction
390    and one has been requested using tofu_begin_batch_transaction.  */
391 static void
tofu_resume_batch_transaction(ctrl_t ctrl)392 tofu_resume_batch_transaction (ctrl_t ctrl)
393 {
394   begin_transaction (ctrl, 1);
395 }
396 
397 
398 
399 /* Wrapper around strtol which prints a warning in case of a
400  * conversion error.  On success the converted value is stored at
401  * R_VALUE and 0 is returned; on error FALLBACK is stored at R_VALUE
402  * and an error code is returned.  */
403 static gpg_error_t
string_to_long(long * r_value,const char * string,long fallback,int line)404 string_to_long (long *r_value, const char *string, long fallback, int line)
405 {
406   gpg_error_t err;
407   char *tail = NULL;
408 
409   gpg_err_set_errno (0);
410   *r_value = strtol (string, &tail, 0);
411   if (errno || !(!strcmp (tail, ".0") || !*tail))
412     {
413       err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
414       log_debug ("%s:%d: strtol failed for TOFU DB data; returned string"
415                  " (string='%.10s%s'; tail='%.10s%s'): %s\n",
416                  __FILE__, line,
417                  string, string && strlen(string) > 10 ? "..." : "",
418                  tail, tail && strlen(tail) > 10 ? "..." : "",
419                  gpg_strerror (err));
420       *r_value = fallback;
421     }
422   else
423     err = 0;
424 
425   return err;
426 }
427 
428 
429 /* Wrapper around strtoul which prints a warning in case of a
430  * conversion error.  On success the converted value is stored at
431  * R_VALUE and 0 is returned; on error FALLBACK is stored at R_VALUE
432  * and an error code is returned.  */
433 static gpg_error_t
string_to_ulong(unsigned long * r_value,const char * string,unsigned long fallback,int line)434 string_to_ulong (unsigned long *r_value, const char *string,
435                  unsigned long fallback, int line)
436 {
437   gpg_error_t err;
438   char *tail = NULL;
439 
440   gpg_err_set_errno (0);
441   *r_value = strtoul (string, &tail, 0);
442   if (errno || !(!strcmp (tail, ".0") || !*tail))
443     {
444       err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
445       log_debug ("%s:%d: strtoul failed for TOFU DB data; returned string"
446                  " (string='%.10s%s'; tail='%.10s%s'): %s\n",
447                  __FILE__, line,
448                  string, string && strlen(string) > 10 ? "..." : "",
449                  tail, tail && strlen(tail) > 10 ? "..." : "",
450                  gpg_strerror (err));
451       *r_value = fallback;
452     }
453   else
454     err = 0;
455 
456   return err;
457 }
458 
459 
460 
461 /* Collect results of a select count (*) ...; style query.  Aborts if
462    the argument is not a valid integer (or real of the form X.0).  */
463 static int
get_single_unsigned_long_cb(void * cookie,int argc,char ** argv,char ** azColName)464 get_single_unsigned_long_cb (void *cookie, int argc, char **argv,
465 			     char **azColName)
466 {
467   unsigned long int *count = cookie;
468 
469   (void) azColName;
470 
471   log_assert (argc == 1);
472 
473   if (string_to_ulong (count, argv[0], 0, __LINE__))
474     return 1; /* Abort.  */
475   return 0;
476 }
477 
478 static int
get_single_unsigned_long_cb2(void * cookie,int argc,char ** argv,char ** azColName,sqlite3_stmt * stmt)479 get_single_unsigned_long_cb2 (void *cookie, int argc, char **argv,
480 			     char **azColName, sqlite3_stmt *stmt)
481 {
482   (void) stmt;
483   return get_single_unsigned_long_cb (cookie, argc, argv, azColName);
484 }
485 
486 /* We expect a single integer column whose name is "version".  COOKIE
487    must point to an int.  This function always aborts.  On error or a
488    if the version is bad, sets *VERSION to -1.  */
489 static int
version_check_cb(void * cookie,int argc,char ** argv,char ** azColName)490 version_check_cb (void *cookie, int argc, char **argv, char **azColName)
491 {
492   int *version = cookie;
493 
494   if (argc != 1 || strcmp (azColName[0], "version") != 0)
495     {
496       *version = -1;
497       return 1;
498     }
499 
500   if (strcmp (argv[0], "1") == 0)
501     *version = 1;
502   else
503     {
504       log_error (_("unsupported TOFU database version: %s\n"), argv[0]);
505       *version = -1;
506     }
507 
508   /* Don't run again.  */
509   return 1;
510 }
511 
512 static int
check_utks(sqlite3 * db)513 check_utks (sqlite3 *db)
514 {
515   int rc;
516   char *err = NULL;
517   struct key_item *utks;
518   struct key_item *ki;
519   int utk_count;
520   char *utks_string = NULL;
521   char keyid_str[16+1];
522   long utks_unchanged = 0;
523 
524   /* An early version of the v1 format did not include the list of
525    * known ultimately trusted keys.
526    *
527    * This list is used to detect when the set of ultimately trusted
528    * keys changes.  We need to detect this to invalidate the effective
529    * policy, which can change if an ultimately trusted key is added or
530    * removed.  */
531   rc = sqlite3_exec (db,
532                      "create table if not exists ultimately_trusted_keys"
533                      " (keyid);\n",
534                      NULL, NULL, &err);
535   if (rc)
536     {
537       log_error ("error creating 'ultimately_trusted_keys' TOFU table: %s\n",
538                  err);
539       sqlite3_free (err);
540       goto out;
541     }
542 
543 
544   utks = tdb_utks ();
545   for (ki = utks, utk_count = 0; ki; ki = ki->next, utk_count ++)
546     ;
547 
548   if (utk_count)
549     {
550       /* Build a list of keyids of the form "XXX","YYY","ZZZ".  */
551       int len = (1 + 16 + 1 + 1) * utk_count;
552       int o = 0;
553 
554       utks_string = xmalloc (len);
555       *utks_string = 0;
556       for (ki = utks, utk_count = 0; ki; ki = ki->next, utk_count ++)
557         {
558           utks_string[o ++] = '\'';
559           format_keyid (ki->kid, KF_LONG,
560                         keyid_str, sizeof (keyid_str));
561           memcpy (&utks_string[o], keyid_str, 16);
562           o += 16;
563           utks_string[o ++] = '\'';
564           utks_string[o ++] = ',';
565         }
566       utks_string[o - 1] = 0;
567       log_assert (o == len);
568     }
569 
570   rc = gpgsql_exec_printf
571     (db, get_single_unsigned_long_cb, &utks_unchanged, &err,
572      "select"
573      /* Removed UTKs?  (Known UTKs in current UTKs.)  */
574      "  ((select count(*) from ultimately_trusted_keys"
575      "     where (keyid in (%s))) == %d)"
576      " and"
577      /* New UTKs?  */
578      "  ((select count(*) from ultimately_trusted_keys"
579      "     where keyid not in (%s)) == 0);",
580      utks_string ? utks_string : "",
581      utk_count,
582      utks_string ? utks_string : "");
583   xfree (utks_string);
584   if (rc)
585     {
586       log_error (_("TOFU DB error"));
587       print_further_info ("checking if ultimately trusted keys changed: %s",
588                          err);
589       sqlite3_free (err);
590       goto out;
591     }
592 
593   if (utks_unchanged)
594     goto out;
595 
596   if (DBG_TRUST)
597     log_debug ("TOFU: ultimately trusted keys changed.\n");
598 
599   /* Given that the set of ultimately trusted keys
600    * changed, clear any cached policies.  */
601   rc = gpgsql_exec_printf
602     (db, NULL, NULL, &err,
603      "update bindings set effective_policy = %d;",
604      TOFU_POLICY_NONE);
605   if (rc)
606     {
607       log_error (_("TOFU DB error"));
608       print_further_info ("clearing cached policies: %s", err);
609       sqlite3_free (err);
610       goto out;
611     }
612 
613   /* Now, update the UTK table.  */
614   rc = sqlite3_exec (db,
615                      "drop table ultimately_trusted_keys;",
616                      NULL, NULL, &err);
617   if (rc)
618     {
619       log_error (_("TOFU DB error"));
620       print_further_info ("dropping ultimately_trusted_keys: %s", err);
621       sqlite3_free (err);
622       goto out;
623     }
624 
625   rc = sqlite3_exec (db,
626                      "create table if not exists"
627                      " ultimately_trusted_keys (keyid);\n",
628                      NULL, NULL, &err);
629   if (rc)
630     {
631       log_error (_("TOFU DB error"));
632       print_further_info ("creating ultimately_trusted_keys: %s", err);
633       sqlite3_free (err);
634       goto out;
635     }
636 
637   for (ki = utks; ki; ki = ki->next)
638     {
639       format_keyid (ki->kid, KF_LONG,
640                     keyid_str, sizeof (keyid_str));
641       rc = gpgsql_exec_printf
642         (db, NULL, NULL, &err,
643          "insert into ultimately_trusted_keys values ('%s');",
644          keyid_str);
645       if (rc)
646         {
647           log_error (_("TOFU DB error"));
648           print_further_info ("updating ultimately_trusted_keys: %s",
649                               err);
650           sqlite3_free (err);
651           goto out;
652         }
653     }
654 
655  out:
656   return rc;
657 }
658 
659 /* If the DB is new, initialize it.  Otherwise, check the DB's
660    version.
661 
662    Return 0 if the database is okay and 1 otherwise.  */
663 static int
initdb(sqlite3 * db)664 initdb (sqlite3 *db)
665 {
666   char *err = NULL;
667   int rc;
668   unsigned long int count;
669   int version = -1;
670 
671   rc = sqlite3_exec (db, "begin transaction;", NULL, NULL, &err);
672   if (rc)
673     {
674       log_error (_("error beginning transaction on TOFU database: %s\n"),
675 		 err);
676       sqlite3_free (err);
677       return 1;
678     }
679 
680   /* If the DB has no tables, then assume this is a new DB that needs
681      to be initialized.  */
682   rc = sqlite3_exec (db,
683 		     "select count(*) from sqlite_master where type='table';",
684 		     get_single_unsigned_long_cb, &count, &err);
685   if (rc)
686     {
687       log_error (_("error reading TOFU database: %s\n"), err);
688       print_further_info ("query available tables");
689       sqlite3_free (err);
690       goto out;
691     }
692   else if (count != 0)
693     /* Assume that the DB is already initialized.  Make sure the
694        version is okay.  */
695     {
696       rc = sqlite3_exec (db, "select version from version;", version_check_cb,
697 			 &version, &err);
698       if (rc == SQLITE_ABORT && version == 1)
699 	/* Happy, happy, joy, joy.  */
700 	{
701 	  sqlite3_free (err);
702           rc = 0;
703           goto out;
704 	}
705       else if (rc == SQLITE_ABORT && version == -1)
706 	/* Unsupported version.  */
707 	{
708 	  /* An error message was already displayed.  */
709 	  sqlite3_free (err);
710           goto out;
711 	}
712       else if (rc)
713 	/* Some error.  */
714 	{
715 	  log_error (_("error determining TOFU database's version: %s\n"), err);
716 	  sqlite3_free (err);
717           goto out;
718 	}
719       else
720         {
721           /* Unexpected success.  This can only happen if there are no
722              rows.  (select returned 0, but expected ABORT.)  */
723 	  log_error (_("error determining TOFU database's version: %s\n"),
724                      gpg_strerror (GPG_ERR_NO_DATA));
725           rc = 1;
726           goto out;
727 	}
728     }
729 
730   /* Create the version table.  */
731   rc = sqlite3_exec (db,
732 		     "create table version (version INTEGER);",
733 		     NULL, NULL, &err);
734   if (rc)
735     {
736       log_error (_("error initializing TOFU database: %s\n"), err);
737       print_further_info ("create version");
738       sqlite3_free (err);
739       goto out;
740     }
741 
742   /* Initialize the version table, which contains a single integer
743      value.  */
744   rc = sqlite3_exec (db,
745 		     "insert into version values (1);",
746 		     NULL, NULL, &err);
747   if (rc)
748     {
749       log_error (_("error initializing TOFU database: %s\n"), err);
750       print_further_info ("insert version");
751       sqlite3_free (err);
752       goto out;
753     }
754 
755   /* The list of <fingerprint, email> bindings and auxiliary data.
756    *
757    *  OID is a unique ID identifying this binding (and used by the
758    *    signatures table, see below).  Note: OIDs will never be
759    *    reused.
760    *
761    *  FINGERPRINT: The key's fingerprint.
762    *
763    *  EMAIL: The normalized email address.
764    *
765    *  USER_ID: The unmodified user id from which EMAIL was extracted.
766    *
767    *  TIME: The time this binding was first observed.
768    *
769    *  POLICY: The trust policy (TOFU_POLICY_BAD, etc. as an integer).
770    *
771    *  CONFLICT is either NULL or a fingerprint.  Assume that we have
772    *    a binding <0xdeadbeef, foo@example.com> and then we observe
773    *    <0xbaddecaf, foo@example.com>.  There two bindings conflict
774    *    (they have the same email address).  When we observe the
775    *    latter binding, we warn the user about the conflict and ask
776    *    for a policy decision about the new binding.  We also change
777    *    the old binding's policy to ask if it was auto.  So that we
778    *     know why this occurred, we also set conflict to 0xbaddecaf.
779    */
780   rc = gpgsql_exec_printf
781       (db, NULL, NULL, &err,
782        "create table bindings\n"
783        " (oid INTEGER PRIMARY KEY AUTOINCREMENT,\n"
784        "  fingerprint TEXT, email TEXT, user_id TEXT, time INTEGER,\n"
785        "  policy INTEGER CHECK (policy in (%d, %d, %d, %d, %d)),\n"
786        "  conflict STRING,\n"
787        "  unique (fingerprint, email));\n"
788        "create index bindings_fingerprint_email\n"
789        " on bindings (fingerprint, email);\n"
790        "create index bindings_email on bindings (email);\n",
791        TOFU_POLICY_AUTO, TOFU_POLICY_GOOD, TOFU_POLICY_UNKNOWN,
792        TOFU_POLICY_BAD, TOFU_POLICY_ASK);
793   if (rc)
794     {
795       log_error (_("error initializing TOFU database: %s\n"), err);
796       print_further_info ("create bindings");
797       sqlite3_free (err);
798       goto out;
799     }
800 
801   /* The signatures that we have observed.
802    *
803    * BINDING refers to a record in the bindings table, which
804    * describes the binding (i.e., this is a foreign key that
805    * references bindings.oid).
806    *
807    * SIG_DIGEST is the digest stored in the signature.
808    *
809    * SIG_TIME is the timestamp stored in the signature.
810    *
811    * ORIGIN is a free-form string that describes who fed this
812    * signature to GnuPG (e.g., email:claws).
813    *
814    * TIME is the time this signature was registered.  */
815   rc = sqlite3_exec (db,
816 			 "create table signatures "
817 			 " (binding INTEGER NOT NULL, sig_digest TEXT,"
818 			 "  origin TEXT, sig_time INTEGER, time INTEGER,"
819 			 "  primary key (binding, sig_digest, origin));",
820 			 NULL, NULL, &err);
821   if (rc)
822     {
823       log_error (_("error initializing TOFU database: %s\n"), err);
824       print_further_info ("create signatures");
825       sqlite3_free (err);
826       goto out;
827     }
828 
829  out:
830   if (! rc)
831     {
832       /* Early version of the v1 format did not include the encryption
833          table.  Add it.  */
834       rc = sqlite3_exec (db,
835                          "create table if not exists encryptions"
836                          " (binding INTEGER NOT NULL,"
837                          "  time INTEGER);"
838                          "create index if not exists encryptions_binding"
839                          " on encryptions (binding);\n",
840                          NULL, NULL, &err);
841       if (rc)
842         {
843 	  log_error ("error creating 'encryptions' TOFU table: %s\n",
844 		     err);
845           sqlite3_free (err);
846         }
847     }
848   if (! rc)
849     {
850       /* The effective policy for a binding.  If a key is ultimately
851        * trusted, then the effective policy of all of its bindings is
852        * good.  Likewise if a key is signed by an ultimately trusted
853        * key, etc.  If the effective policy is NONE, then we need to
854        * recompute the effective policy.  Otherwise, the effective
855        * policy is considered to be up to date, i.e., effective_policy
856        * is a cache of the computed policy.  */
857       rc = gpgsql_exec_printf
858         (db, NULL, NULL, &err,
859          "alter table bindings"
860          " add column effective_policy INTEGER"
861          " DEFAULT %d"
862          " CHECK (effective_policy in (%d, %d, %d, %d, %d, %d));",
863          TOFU_POLICY_NONE,
864          TOFU_POLICY_NONE, TOFU_POLICY_AUTO, TOFU_POLICY_GOOD,
865          TOFU_POLICY_UNKNOWN, TOFU_POLICY_BAD, TOFU_POLICY_ASK);
866       if (rc)
867 	{
868           if (rc == SQLITE_ERROR)
869             /* Almost certainly "duplicate column name", which we can
870              * safely ignore.  */
871             rc = 0;
872           else
873             log_error ("adding column effective_policy to bindings DB: %s\n",
874                        err);
875 	  sqlite3_free (err);
876 	}
877     }
878 
879   if (! rc)
880     rc = check_utks (db);
881 
882   if (rc)
883     {
884       rc = sqlite3_exec (db, "rollback;", NULL, NULL, &err);
885       if (rc)
886 	{
887 	  log_error (_("error rolling back transaction on TOFU database: %s\n"),
888 		     err);
889 	  sqlite3_free (err);
890 	}
891       return 1;
892     }
893   else
894     {
895       rc = sqlite3_exec (db, "end transaction;", NULL, NULL, &err);
896       if (rc)
897 	{
898 	  log_error (_("error committing transaction on TOFU database: %s\n"),
899 		     err);
900 	  sqlite3_free (err);
901 	  return 1;
902 	}
903       return 0;
904     }
905 }
906 
907 static int
busy_handler(void * cookie,int call_count)908 busy_handler (void *cookie, int call_count)
909 {
910   ctrl_t ctrl = cookie;
911   tofu_dbs_t dbs = ctrl->tofu.dbs;
912 
913   (void) call_count;
914 
915   /* Update the want-lock-file time stamp (specifically, the ctime) so
916    * that the current owner knows that we (well, someone) want the
917    * lock.  */
918   if (dbs)
919     {
920       /* Note: we don't fail if we can't create the lock file: this
921        * process will have to wait a bit longer, but otherwise nothing
922        * horrible should happen.  */
923 
924       estream_t fp;
925 
926       fp = es_fopen (dbs->want_lock_file, "w");
927       if (! fp)
928         log_debug ("TOFU: Error opening '%s': %s\n",
929                    dbs->want_lock_file, strerror (errno));
930       else
931         es_fclose (fp);
932     }
933 
934   /* Call again.  */
935   return 1;
936 }
937 
938 /* Create a new DB handle.  Returns NULL on error.  */
939 /* FIXME: Change to return an error code for better reporting by the
940    caller.  */
941 static tofu_dbs_t
opendbs(ctrl_t ctrl)942 opendbs (ctrl_t ctrl)
943 {
944   char *filename;
945   sqlite3 *db;
946   int rc;
947 
948   if (!ctrl->tofu.dbs)
949     {
950       filename = make_filename (gnupg_homedir (), "tofu.db", NULL);
951 
952       rc = sqlite3_open (filename, &db);
953       if (rc)
954         {
955           log_error (_("error opening TOFU database '%s': %s\n"),
956                      filename, sqlite3_errmsg (db));
957           /* Even if an error occurs, DB is guaranteed to be valid.  */
958           sqlite3_close (db);
959           db = NULL;
960         }
961 
962       /* If a DB is locked wait up to 5 seconds for the lock to be cleared
963          before failing.  */
964       if (db)
965         {
966           sqlite3_busy_timeout (db, 5 * 1000);
967           sqlite3_busy_handler (db, busy_handler, ctrl);
968         }
969 
970       if (db && initdb (db))
971         {
972           sqlite3_close (db);
973           db = NULL;
974         }
975 
976       if (db)
977         {
978           ctrl->tofu.dbs = xmalloc_clear (sizeof *ctrl->tofu.dbs);
979           ctrl->tofu.dbs->db = db;
980           ctrl->tofu.dbs->want_lock_file = xasprintf ("%s-want-lock", filename);
981         }
982 
983       xfree (filename);
984     }
985   else
986     log_assert (ctrl->tofu.dbs->db);
987 
988   return ctrl->tofu.dbs;
989 }
990 
991 
992 /* Release all of the resources associated with the DB handle.  */
993 void
tofu_closedbs(ctrl_t ctrl)994 tofu_closedbs (ctrl_t ctrl)
995 {
996   tofu_dbs_t dbs;
997   sqlite3_stmt **statements;
998 
999   dbs = ctrl->tofu.dbs;
1000   if (!dbs)
1001     return;  /* Not initialized.  */
1002 
1003   log_assert (dbs->in_transaction == 0);
1004 
1005   end_transaction (ctrl, 2);
1006 
1007   /* Arghh, that is a surprising use of the struct.  */
1008   for (statements = (void *) &dbs->s;
1009        (void *) statements < (void *) &(&dbs->s)[1];
1010        statements ++)
1011     sqlite3_finalize (*statements);
1012 
1013   sqlite3_close (dbs->db);
1014   xfree (dbs->want_lock_file);
1015   xfree (dbs);
1016   ctrl->tofu.dbs = NULL;
1017 }
1018 
1019 
1020 /* Collect results of a select min (foo) ...; style query.  Aborts if
1021    the argument is not a valid integer (or real of the form X.0).  */
1022 static int
get_single_long_cb(void * cookie,int argc,char ** argv,char ** azColName)1023 get_single_long_cb (void *cookie, int argc, char **argv, char **azColName)
1024 {
1025   long *count = cookie;
1026 
1027   (void) azColName;
1028 
1029   log_assert (argc == 1);
1030 
1031   if (string_to_long (count, argv[0], 0, __LINE__))
1032     return 1; /* Abort.  */
1033 
1034   return 0;
1035 }
1036 
1037 static int
get_single_long_cb2(void * cookie,int argc,char ** argv,char ** azColName,sqlite3_stmt * stmt)1038 get_single_long_cb2 (void *cookie, int argc, char **argv, char **azColName,
1039                      sqlite3_stmt *stmt)
1040 {
1041   (void) stmt;
1042   return get_single_long_cb (cookie, argc, argv, azColName);
1043 }
1044 
1045 /* Record (or update) a trust policy about a (possibly new)
1046    binding.
1047 
1048    If SHOW_OLD is set, the binding's old policy is displayed.  */
1049 static gpg_error_t
record_binding(tofu_dbs_t dbs,const char * fingerprint,const char * email,const char * user_id,enum tofu_policy policy,enum tofu_policy effective_policy,const char * conflict,int set_conflict,int show_old,time_t now)1050 record_binding (tofu_dbs_t dbs, const char *fingerprint, const char *email,
1051 		const char *user_id,
1052                 enum tofu_policy policy, enum tofu_policy effective_policy,
1053                 const char *conflict, int set_conflict,
1054                 int show_old, time_t now)
1055 {
1056   char *fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
1057   gpg_error_t rc;
1058   char *err = NULL;
1059 
1060   if (! (policy == TOFU_POLICY_AUTO
1061 	 || policy == TOFU_POLICY_GOOD
1062 	 || policy == TOFU_POLICY_UNKNOWN
1063 	 || policy == TOFU_POLICY_BAD
1064 	 || policy == TOFU_POLICY_ASK))
1065     log_bug ("%s: Bad value for policy (%d)!\n", __func__, policy);
1066 
1067 
1068   if (DBG_TRUST || show_old)
1069     {
1070       /* Get the old policy.  Since this is just for informational
1071        * purposes, there is no need to start a transaction or to die
1072        * if there is a failure.  */
1073 
1074       /* policy_old needs to be a long and not an enum tofu_policy,
1075          because we pass it by reference to get_single_long_cb2, which
1076          expects a long.  */
1077       long policy_old = TOFU_POLICY_NONE;
1078 
1079       rc = gpgsql_stepx
1080 	(dbs->db, &dbs->s.record_binding_get_old_policy,
1081          get_single_long_cb2, &policy_old, &err,
1082 	 "select policy from bindings where fingerprint = ? and email = ?",
1083 	 GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1084          GPGSQL_ARG_END);
1085       if (rc)
1086 	{
1087 	  log_debug ("TOFU: Error reading from binding database"
1088 		     " (reading policy for <key: %s, user id: %s>): %s\n",
1089 		     fingerprint, email, err);
1090 	  sqlite3_free (err);
1091 	}
1092 
1093       if (policy_old != TOFU_POLICY_NONE)
1094         (show_old ? log_info : log_debug)
1095           ("Changing TOFU trust policy for binding"
1096            " <key: %s, user id: %s> from %s to %s.\n",
1097            fingerprint, show_old ? user_id : email,
1098            tofu_policy_str (policy_old),
1099            tofu_policy_str (policy));
1100       else
1101         (show_old ? log_info : log_debug)
1102           ("Setting TOFU trust policy for new binding"
1103            " <key: %s, user id: %s> to %s.\n",
1104            fingerprint, show_old ? user_id : email,
1105            tofu_policy_str (policy));
1106     }
1107 
1108   if (opt.dry_run)
1109     {
1110       log_info ("TOFU database update skipped due to --dry-run\n");
1111       rc = 0;
1112       goto leave;
1113     }
1114 
1115   rc = gpgsql_stepx
1116     (dbs->db, &dbs->s.record_binding_update, NULL, NULL, &err,
1117      "insert or replace into bindings\n"
1118      " (oid, fingerprint, email, user_id, time,"
1119      "  policy, conflict, effective_policy)\n"
1120      " values (\n"
1121      /* If we don't explicitly reuse the OID, then SQLite will
1122       * reallocate a new one.  We just need to search for the OID
1123       * based on the fingerprint and email since they are unique.  */
1124      "  (select oid from bindings where fingerprint = ? and email = ?),\n"
1125      "  ?, ?, ?, ?, ?,"
1126      /* If SET_CONFLICT is 0, then preserve conflict's current value.  */
1127      "  case ?"
1128      "    when 0 then"
1129      "      (select conflict from bindings where fingerprint = ? and email = ?)"
1130      "    else ?"
1131      "  end,"
1132      "  ?);",
1133      /* oid subquery.  */
1134      GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1135      /* values 2 through 6.  */
1136      GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1137      GPGSQL_ARG_STRING, user_id,
1138      GPGSQL_ARG_LONG_LONG, (long long) now,
1139      GPGSQL_ARG_INT, (int) policy,
1140      /* conflict subquery.  */
1141      GPGSQL_ARG_INT, set_conflict ? 1 : 0,
1142      GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1143      GPGSQL_ARG_STRING, conflict ? conflict : "",
1144      GPGSQL_ARG_INT, (int) effective_policy,
1145      GPGSQL_ARG_END);
1146   if (rc)
1147     {
1148       log_error (_("error updating TOFU database: %s\n"), err);
1149       print_further_info (" insert bindings <key: %s, user id: %s> = %s",
1150                           fingerprint, email, tofu_policy_str (policy));
1151       sqlite3_free (err);
1152       goto leave;
1153     }
1154 
1155  leave:
1156   xfree (fingerprint_pp);
1157   return rc;
1158 }
1159 
1160 
1161 /* Collect the strings returned by a query in a simple string list.
1162    Any NULL values are converted to the empty string.
1163 
1164    If a result has 3 rows and each row contains two columns, then the
1165    results are added to the list as follows (the value is parentheses
1166    is the 1-based index in the final list):
1167 
1168      row 1, col 2 (6)
1169      row 1, col 1 (5)
1170      row 2, col 2 (4)
1171      row 2, col 1 (3)
1172      row 3, col 2 (2)
1173      row 3, col 1 (1)
1174 
1175    This is because add_to_strlist pushes the results onto the front of
1176    the list.  The end result is that the rows are backwards, but the
1177    columns are in the expected order.  */
1178 static int
strings_collect_cb(void * cookie,int argc,char ** argv,char ** azColName)1179 strings_collect_cb (void *cookie, int argc, char **argv, char **azColName)
1180 {
1181   int i;
1182   strlist_t *strlist = cookie;
1183 
1184   (void) azColName;
1185 
1186   for (i = argc - 1; i >= 0; i --)
1187     add_to_strlist (strlist, argv[i] ? argv[i] : "");
1188 
1189   return 0;
1190 }
1191 
1192 static int
strings_collect_cb2(void * cookie,int argc,char ** argv,char ** azColName,sqlite3_stmt * stmt)1193 strings_collect_cb2 (void *cookie, int argc, char **argv, char **azColName,
1194                      sqlite3_stmt *stmt)
1195 {
1196   (void) stmt;
1197   return strings_collect_cb (cookie, argc, argv, azColName);
1198 
1199 }
1200 
1201 /* Auxiliary data structure to collect statistics about
1202    signatures.  */
1203 struct signature_stats
1204 {
1205   struct signature_stats *next;
1206 
1207   /* The user-assigned policy for this binding.  */
1208   enum tofu_policy policy;
1209 
1210   /* How long ago the signature was created (rounded to a multiple of
1211      TIME_AGO_UNIT_SMALL, etc.).  */
1212   long time_ago;
1213   /* Number of signatures during this time.  */
1214   unsigned long count;
1215 
1216   /* If the corresponding key/user id has been expired / revoked.  */
1217   int is_expired;
1218   int is_revoked;
1219 
1220   /* The key that generated this signature.  */
1221   char fingerprint[1];
1222 };
1223 
1224 static void
signature_stats_free(struct signature_stats * stats)1225 signature_stats_free (struct signature_stats *stats)
1226 {
1227   while (stats)
1228     {
1229       struct signature_stats *next = stats->next;
1230       xfree (stats);
1231       stats = next;
1232     }
1233 }
1234 
1235 static void
signature_stats_prepend(struct signature_stats ** statsp,const char * fingerprint,enum tofu_policy policy,long time_ago,unsigned long count)1236 signature_stats_prepend (struct signature_stats **statsp,
1237 			 const char *fingerprint,
1238 			 enum tofu_policy policy,
1239 			 long time_ago,
1240 			 unsigned long count)
1241 {
1242   struct signature_stats *stats =
1243     xmalloc_clear (sizeof (*stats) + strlen (fingerprint));
1244 
1245   stats->next = *statsp;
1246   *statsp = stats;
1247 
1248   strcpy (stats->fingerprint, fingerprint);
1249   stats->policy = policy;
1250   stats->time_ago = time_ago;
1251   stats->count = count;
1252 }
1253 
1254 
1255 /* Process rows that contain the four columns:
1256 
1257      <fingerprint, policy, time ago, count>.  */
1258 static int
signature_stats_collect_cb(void * cookie,int argc,char ** argv,char ** azColName,sqlite3_stmt * stmt)1259 signature_stats_collect_cb (void *cookie, int argc, char **argv,
1260 			    char **azColName, sqlite3_stmt *stmt)
1261 {
1262   struct signature_stats **statsp = cookie;
1263   int i = 0;
1264   enum tofu_policy policy;
1265   long time_ago;
1266   unsigned long count;
1267   long along;
1268 
1269   (void) azColName;
1270   (void) stmt;
1271 
1272   i ++;
1273 
1274   if (string_to_long (&along, argv[i], 0, __LINE__))
1275     return 1;  /* Abort */
1276   policy = along;
1277   i ++;
1278 
1279   if (! argv[i])
1280     time_ago = 0;
1281   else
1282     {
1283       if (string_to_long (&time_ago, argv[i], 0, __LINE__))
1284         return 1; /* Abort.  */
1285     }
1286   i ++;
1287 
1288   /* If time_ago is NULL, then we had no messages, but we still have a
1289      single row, which count(*) turns into 1.  */
1290   if (! argv[i - 1])
1291     count = 0;
1292   else
1293     {
1294       if (string_to_ulong (&count, argv[i], 0, __LINE__))
1295         return 1; /* Abort */
1296     }
1297   i ++;
1298 
1299   log_assert (argc == i);
1300 
1301   signature_stats_prepend (statsp, argv[0], policy, time_ago, count);
1302 
1303   return 0;
1304 }
1305 
1306 /* Format the first part of a conflict message and return that as a
1307  * malloced string. Returns NULL on error. */
1308 static char *
format_conflict_msg_part1(int policy,strlist_t conflict_set,const char * email)1309 format_conflict_msg_part1 (int policy, strlist_t conflict_set,
1310                            const char *email)
1311 {
1312   estream_t fp;
1313   char *fingerprint;
1314   char *tmpstr, *text;
1315 
1316   log_assert (conflict_set);
1317   fingerprint = conflict_set->d;
1318 
1319   fp = es_fopenmem (0, "rw,samethread");
1320   if (!fp)
1321     log_fatal ("error creating memory stream: %s\n",
1322                gpg_strerror (gpg_error_from_syserror()));
1323 
1324   if (policy == TOFU_POLICY_NONE)
1325     {
1326       es_fprintf (fp,
1327                   _("This is the first time the email address \"%s\" is "
1328                     "being used with key %s."),
1329                   email, fingerprint);
1330       es_fputs ("  ", fp);
1331     }
1332   else if (policy == TOFU_POLICY_ASK && conflict_set->next)
1333     {
1334       int conflicts = strlist_length (conflict_set);
1335       es_fprintf
1336         (fp, ngettext("The email address \"%s\" is associated with %d key!",
1337                       "The email address \"%s\" is associated with %d keys!",
1338                       conflicts),
1339          email, conflicts);
1340       if (opt.verbose)
1341         es_fprintf (fp,
1342                     _("  Since this binding's policy was 'auto', it has been "
1343                       "changed to 'ask'."));
1344       es_fputs ("  ", fp);
1345     }
1346 
1347   es_fprintf (fp,
1348               _("Please indicate whether this email address should"
1349                 " be associated with key %s or whether you think someone"
1350                 " is impersonating \"%s\"."),
1351               fingerprint, email);
1352   es_fputc ('\n', fp);
1353 
1354   es_fputc (0, fp);
1355   if (es_fclose_snatch (fp, (void **)&tmpstr, NULL))
1356     log_fatal ("error snatching memory stream\n");
1357   text = format_text (tmpstr, 72, 80);
1358   es_free (tmpstr);
1359 
1360   return text;
1361 }
1362 
1363 
1364 /* Return 1 if A signed B and B signed A.  */
1365 static int
cross_sigs(const char * email,kbnode_t a,kbnode_t b)1366 cross_sigs (const char *email, kbnode_t a, kbnode_t b)
1367 {
1368   int i;
1369 
1370   PKT_public_key *a_pk = a->pkt->pkt.public_key;
1371   PKT_public_key *b_pk = b->pkt->pkt.public_key;
1372 
1373   char a_keyid[33];
1374   char b_keyid[33];
1375 
1376   if (DBG_TRUST)
1377     {
1378       format_keyid (pk_main_keyid (a_pk),
1379                     KF_LONG, a_keyid, sizeof (a_keyid));
1380       format_keyid (pk_main_keyid (b_pk),
1381                     KF_LONG, b_keyid, sizeof (b_keyid));
1382     }
1383 
1384   for (i = 0; i < 2; i ++)
1385     {
1386       /* See if SIGNER signed SIGNEE.  */
1387 
1388       kbnode_t signer = i == 0 ? a : b;
1389       kbnode_t signee = i == 0 ? b : a;
1390 
1391       PKT_public_key *signer_pk = signer->pkt->pkt.public_key;
1392       u32 *signer_kid = pk_main_keyid (signer_pk);
1393       kbnode_t n;
1394 
1395       int saw_email = 0;
1396 
1397       /* Iterate over SIGNEE's keyblock and see if there is a valid
1398          signature from SIGNER.  */
1399       for (n = signee; n; n = n->next)
1400         {
1401           PKT_signature *sig;
1402 
1403           if (n->pkt->pkttype == PKT_USER_ID)
1404             {
1405               if (saw_email)
1406                 /* We're done: we've processed all signatures on the
1407                    user id.  */
1408                 break;
1409               else
1410                 {
1411                   /* See if this is the matching user id.  */
1412                   PKT_user_id *user_id = n->pkt->pkt.user_id;
1413                   char *email2 = email_from_user_id (user_id->name);
1414 
1415                   if (strcmp (email, email2) == 0)
1416                     saw_email = 1;
1417 
1418                   xfree (email2);
1419                 }
1420             }
1421 
1422           if (! saw_email)
1423             continue;
1424 
1425           if (n->pkt->pkttype != PKT_SIGNATURE)
1426             continue;
1427 
1428           sig = n->pkt->pkt.signature;
1429 
1430           if (! (sig->sig_class == 0x10
1431                  || sig->sig_class == 0x11
1432                  || sig->sig_class == 0x12
1433                  || sig->sig_class == 0x13))
1434             /* Not a signature over a user id.  */
1435             continue;
1436 
1437           /* SIG is on SIGNEE's keyblock.  If SIG was generated by the
1438              signer, then it's a match.  */
1439           if (keyid_cmp (sig->keyid, signer_kid) == 0)
1440             /* Match!  */
1441             break;
1442         }
1443       if (! n)
1444         /* We didn't find a signature from signer over signee.  */
1445         {
1446           if (DBG_TRUST)
1447             log_debug ("No cross sig between %s and %s\n",
1448                        a_keyid, b_keyid);
1449           return 0;
1450         }
1451     }
1452 
1453   /* A signed B and B signed A.  */
1454   if (DBG_TRUST)
1455     log_debug ("Cross sig between %s and %s\n",
1456                a_keyid, b_keyid);
1457 
1458   return 1;
1459 }
1460 
1461 /* Return whether the key was signed by an ultimately trusted key.  */
1462 static int
signed_by_utk(const char * email,kbnode_t a)1463 signed_by_utk (const char *email, kbnode_t a)
1464 {
1465   kbnode_t n;
1466   int saw_email = 0;
1467 
1468   for (n = a; n; n = n->next)
1469     {
1470       PKT_signature *sig;
1471 
1472       if (n->pkt->pkttype == PKT_USER_ID)
1473         {
1474           if (saw_email)
1475             /* We're done: we've processed all signatures on the
1476                user id.  */
1477             break;
1478           else
1479             {
1480               /* See if this is the matching user id.  */
1481               PKT_user_id *user_id = n->pkt->pkt.user_id;
1482               char *email2 = email_from_user_id (user_id->name);
1483 
1484               if (strcmp (email, email2) == 0)
1485                 saw_email = 1;
1486 
1487               xfree (email2);
1488             }
1489         }
1490 
1491       if (! saw_email)
1492         continue;
1493 
1494       if (n->pkt->pkttype != PKT_SIGNATURE)
1495         continue;
1496 
1497       sig = n->pkt->pkt.signature;
1498 
1499       if (! (sig->sig_class == 0x10
1500              || sig->sig_class == 0x11
1501              || sig->sig_class == 0x12
1502              || sig->sig_class == 0x13))
1503         /* Not a signature over a user id.  */
1504         continue;
1505 
1506       /* SIG is on SIGNEE's keyblock.  If SIG was generated by the
1507          signer, then it's a match.  */
1508       if (tdb_keyid_is_utk (sig->keyid))
1509         {
1510           /* Match!  */
1511           if (DBG_TRUST)
1512             log_debug ("TOFU: %s is signed by an ultimately trusted key.\n",
1513                        pk_keyid_str (a->pkt->pkt.public_key));
1514 
1515           return 1;
1516         }
1517     }
1518 
1519   if (DBG_TRUST)
1520     log_debug ("TOFU: %s is NOT signed by an ultimately trusted key.\n",
1521                pk_keyid_str (a->pkt->pkt.public_key));
1522 
1523   return 0;
1524 }
1525 
1526 
1527 enum
1528   {
1529     BINDING_NEW = 1 << 0,
1530     BINDING_CONFLICT = 1 << 1,
1531     BINDING_EXPIRED = 1 << 2,
1532     BINDING_REVOKED = 1 << 3
1533   };
1534 
1535 
1536 /* Ask the user about the binding.  There are three ways we could end
1537  * up here:
1538  *
1539  *   - This is a new binding and there is a conflict
1540  *     (policy == TOFU_POLICY_NONE && conflict_set_count > 1),
1541  *
1542  *   - This is a new binding and opt.tofu_default_policy is set to
1543  *     ask.  (policy == TOFU_POLICY_NONE && opt.tofu_default_policy ==
1544  *     TOFU_POLICY_ASK), or,
1545  *
1546  *   - The policy is ask (the user deferred last time) (policy ==
1547  *     TOFU_POLICY_ASK).
1548  *
1549  * Note: this function must not be called while in a transaction!
1550  *
1551  * CONFLICT_SET includes all of the conflicting bindings
1552  * with FINGERPRINT first.  FLAGS is a bit-wise or of
1553  * BINDING_NEW, etc.
1554  */
1555 static void
ask_about_binding(ctrl_t ctrl,enum tofu_policy * policy,int * trust_level,strlist_t conflict_set,const char * fingerprint,const char * email,const char * user_id,time_t now)1556 ask_about_binding (ctrl_t ctrl,
1557                    enum tofu_policy *policy,
1558                    int *trust_level,
1559                    strlist_t conflict_set,
1560                    const char *fingerprint,
1561                    const char *email,
1562                    const char *user_id,
1563                    time_t now)
1564 {
1565   tofu_dbs_t dbs;
1566   strlist_t iter;
1567   int conflict_set_count = strlist_length (conflict_set);
1568   char *sqerr = NULL;
1569   int rc;
1570   estream_t fp;
1571   strlist_t other_user_ids = NULL;
1572   struct signature_stats *stats = NULL;
1573   struct signature_stats *stats_iter = NULL;
1574   char *prompt = NULL;
1575   const char *choices;
1576 
1577   dbs = ctrl->tofu.dbs;
1578   log_assert (dbs);
1579   log_assert (dbs->in_transaction == 0);
1580 
1581   fp = es_fopenmem (0, "rw,samethread");
1582   if (!fp)
1583     log_fatal ("error creating memory stream: %s\n",
1584                gpg_strerror (gpg_error_from_syserror()));
1585 
1586   {
1587     char *text = format_conflict_msg_part1 (*policy, conflict_set, email);
1588     if (!text) /* FIXME: Return the error all the way up.  */
1589       log_fatal ("format failed: %s\n",
1590                  gpg_strerror (gpg_error_from_syserror()));
1591 
1592     es_fputs (text, fp);
1593     es_fputc ('\n', fp);
1594     xfree (text);
1595   }
1596 
1597   begin_transaction (ctrl, 0);
1598 
1599   /* Find other user ids associated with this key and whether the
1600    * bindings are marked as good or bad.  */
1601   rc = gpgsql_stepx
1602     (dbs->db, &dbs->s.get_trust_gather_other_user_ids,
1603      strings_collect_cb2, &other_user_ids, &sqerr,
1604      "select user_id, policy from bindings where fingerprint = ?;",
1605      GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_END);
1606   if (rc)
1607     {
1608       log_error (_("error gathering other user IDs: %s\n"), sqerr);
1609       sqlite3_free (sqerr);
1610       sqerr = NULL;
1611       rc = gpg_error (GPG_ERR_GENERAL);
1612     }
1613 
1614   if (other_user_ids)
1615     {
1616       strlist_t strlist_iter;
1617 
1618       es_fprintf (fp, _("This key's user IDs:\n"));
1619       for (strlist_iter = other_user_ids;
1620            strlist_iter;
1621            strlist_iter = strlist_iter->next)
1622         {
1623           char *other_user_id = strlist_iter->d;
1624           char *other_thing;
1625           enum tofu_policy other_policy;
1626 
1627           log_assert (strlist_iter->next);
1628           strlist_iter = strlist_iter->next;
1629           other_thing = strlist_iter->d;
1630 
1631           other_policy = atoi (other_thing);
1632 
1633           es_fprintf (fp, "  %s (", other_user_id);
1634           es_fprintf (fp, _("policy: %s"), tofu_policy_str (other_policy));
1635           es_fprintf (fp, ")\n");
1636         }
1637       es_fprintf (fp, "\n");
1638 
1639       free_strlist (other_user_ids);
1640     }
1641 
1642   /* Get the stats for all the keys in CONFLICT_SET.  */
1643   strlist_rev (&conflict_set);
1644   for (iter = conflict_set; iter && ! rc; iter = iter->next)
1645     {
1646 #define STATS_SQL(table, time, sign)                         \
1647          "select fingerprint, policy, time_ago, count(*)\n" \
1648          " from\n" \
1649          "  (select bindings.*,\n" \
1650          "     "sign" case\n" \
1651          "       when delta ISNULL then 1\n" \
1652          /* From the future (but if its just a couple of hours in the \
1653           * future don't turn it into a warning)?  Or should we use \
1654           * small, medium or large units?  (Note: whatever we do, we \
1655           * keep the value in seconds.  Then when we group, everything \
1656           * that rounds to the same number of seconds is grouped.)  */ \
1657          "      when delta < -("STRINGIFY (TIME_AGO_FUTURE_IGNORE)") then 2\n" \
1658          "      when delta < ("STRINGIFY (TIME_AGO_SMALL_THRESHOLD)")\n" \
1659          "       then 3\n" \
1660          "      when delta < ("STRINGIFY (TIME_AGO_MEDIUM_THRESHOLD)")\n" \
1661          "       then 4\n" \
1662          "      when delta < ("STRINGIFY (TIME_AGO_LARGE_THRESHOLD)")\n" \
1663          "       then 5\n" \
1664          "      else 6\n" \
1665          "     end time_ago,\n" \
1666          "    delta time_ago_raw\n" \
1667          "   from bindings\n" \
1668          "   left join\n" \
1669          "     (select *,\n" \
1670          "        cast(? - " time " as real) delta\n" \
1671          "       from " table ") ss\n" \
1672          "    on ss.binding = bindings.oid)\n" \
1673          " where email = ? and fingerprint = ?\n" \
1674          " group by time_ago\n" \
1675          /* Make sure the current key is first.  */ \
1676          " order by time_ago desc;\n"
1677 
1678       /* Use the time when we saw the signature, not when the
1679          signature was created as that can be forged.  */
1680       rc = gpgsql_stepx
1681         (dbs->db, &dbs->s.get_trust_gather_signature_stats,
1682          signature_stats_collect_cb, &stats, &sqerr,
1683          STATS_SQL ("signatures", "time", ""),
1684          GPGSQL_ARG_LONG_LONG, (long long) now,
1685          GPGSQL_ARG_STRING, email,
1686          GPGSQL_ARG_STRING, iter->d,
1687          GPGSQL_ARG_END);
1688       if (rc)
1689         {
1690           sqlite3_free (sqerr);
1691           sqerr = NULL;
1692           rc = gpg_error (GPG_ERR_GENERAL);
1693           break;
1694         }
1695 
1696       if (!stats || strcmp (iter->d, stats->fingerprint) != 0)
1697         /* No stats for this binding.  Add a dummy entry.  */
1698         signature_stats_prepend (&stats, iter->d, TOFU_POLICY_AUTO, 1, 1);
1699 
1700       rc = gpgsql_stepx
1701         (dbs->db, &dbs->s.get_trust_gather_encryption_stats,
1702          signature_stats_collect_cb, &stats, &sqerr,
1703          STATS_SQL ("encryptions", "time", "-"),
1704          GPGSQL_ARG_LONG_LONG, (long long) now,
1705          GPGSQL_ARG_STRING, email,
1706          GPGSQL_ARG_STRING, iter->d,
1707          GPGSQL_ARG_END);
1708       if (rc)
1709         {
1710           rc = gpg_error (GPG_ERR_GENERAL);
1711           break;
1712         }
1713 
1714 #undef STATS_SQL
1715 
1716       if (!stats || strcmp (iter->d, stats->fingerprint) != 0
1717           || stats->time_ago > 0)
1718         /* No stats for this binding.  Add a dummy entry.  */
1719         signature_stats_prepend (&stats, iter->d, TOFU_POLICY_AUTO, -1, 1);
1720     }
1721   end_transaction (ctrl, 0);
1722   strlist_rev (&conflict_set);
1723   if (rc)
1724     {
1725       strlist_t strlist_iter;
1726 
1727       log_error (_("error gathering signature stats: %s\n"), sqerr);
1728       sqlite3_free (sqerr);
1729       sqerr = NULL;
1730 
1731       es_fprintf (fp, ngettext("The email address \"%s\" is"
1732                                " associated with %d key:\n",
1733                                "The email address \"%s\" is"
1734                                " associated with %d keys:\n",
1735                                conflict_set_count),
1736                   email, conflict_set_count);
1737       for (strlist_iter = conflict_set;
1738            strlist_iter;
1739            strlist_iter = strlist_iter->next)
1740         es_fprintf (fp, "  %s\n", strlist_iter->d);
1741     }
1742   else
1743     {
1744       char *key = NULL;
1745       strlist_t binding;
1746       int seen_in_past = 0;
1747       int encrypted = 1;
1748 
1749       es_fprintf (fp, _("Statistics for keys"
1750                         " with the email address \"%s\":\n"),
1751                   email);
1752       for (stats_iter = stats; stats_iter; stats_iter = stats_iter->next)
1753         {
1754 #if 0
1755           log_debug ("%s: time_ago: %ld; count: %ld\n",
1756                      stats_iter->fingerprint,
1757                      stats_iter->time_ago,
1758                      stats_iter->count);
1759 #endif
1760 
1761           if (stats_iter->time_ago > 0 && encrypted)
1762             {
1763               /* We've change from the encrypted stats to the verified
1764                * stats.  Reset SEEN_IN_PAST.  */
1765               encrypted = 0;
1766               seen_in_past = 0;
1767             }
1768 
1769           if (! key || strcmp (key, stats_iter->fingerprint))
1770             {
1771               int this_key;
1772               char *key_pp;
1773 
1774               key = stats_iter->fingerprint;
1775               this_key = strcmp (key, fingerprint) == 0;
1776               key_pp = format_hexfingerprint (key, NULL, 0);
1777               es_fprintf (fp, "  %s (", key_pp);
1778 
1779               /* Find the associated binding.  */
1780               for (binding = conflict_set;
1781                    binding;
1782                    binding = binding->next)
1783                 if (strcmp (key, binding->d) == 0)
1784                   break;
1785               log_assert (binding);
1786 
1787               if ((binding->flags & BINDING_REVOKED))
1788                 {
1789                   es_fprintf (fp, _("revoked"));
1790                   es_fprintf (fp, ", ");
1791                 }
1792               else if ((binding->flags & BINDING_EXPIRED))
1793                 {
1794                   es_fprintf (fp, _("expired"));
1795                   es_fprintf (fp, ", ");
1796                 }
1797 
1798               if (this_key)
1799                 es_fprintf (fp, _("this key"));
1800               else
1801                 es_fprintf (fp, _("policy: %s"),
1802                             tofu_policy_str (stats_iter->policy));
1803               es_fputs ("):\n", fp);
1804               xfree (key_pp);
1805 
1806               seen_in_past = 0;
1807 
1808               show_statistics (dbs, stats_iter->fingerprint, email,
1809                                TOFU_POLICY_ASK, NULL, 1, now);
1810             }
1811 
1812           if (labs(stats_iter->time_ago) == 1)
1813             {
1814               /* The 1 in this case is the NULL entry.  */
1815               log_assert (stats_iter->count == 1);
1816               stats_iter->count = 0;
1817             }
1818           seen_in_past += stats_iter->count;
1819 
1820           es_fputs ("    ", fp);
1821 
1822           if (!stats_iter->count)
1823             {
1824               if (stats_iter->time_ago > 0)
1825                 es_fprintf (fp, ngettext("Verified %d message.",
1826                                          "Verified %d messages.",
1827                                          seen_in_past), seen_in_past);
1828               else
1829                 es_fprintf (fp, ngettext("Encrypted %d message.",
1830                                          "Encrypted %d messages.",
1831                                          seen_in_past), seen_in_past);
1832             }
1833           else if (labs(stats_iter->time_ago) == 2)
1834             {
1835               if (stats_iter->time_ago > 0)
1836                 es_fprintf (fp, ngettext("Verified %d message in the future.",
1837                                          "Verified %d messages in the future.",
1838                                          seen_in_past), seen_in_past);
1839               else
1840                 es_fprintf (fp, ngettext("Encrypted %d message in the future.",
1841                                          "Encrypted %d messages in the future.",
1842                                          seen_in_past), seen_in_past);
1843               /* Reset it.  */
1844               seen_in_past = 0;
1845             }
1846           else
1847             {
1848               if (labs(stats_iter->time_ago) == 3)
1849                 {
1850                   int days = 1 + stats_iter->time_ago / TIME_AGO_UNIT_SMALL;
1851                   if (stats_iter->time_ago > 0)
1852                     es_fprintf
1853                       (fp,
1854                        ngettext("Messages verified over the past %d day: %d.",
1855                                 "Messages verified over the past %d days: %d.",
1856                                 days), days, seen_in_past);
1857                   else
1858                     es_fprintf
1859                       (fp,
1860                        ngettext("Messages encrypted over the past %d day: %d.",
1861                                 "Messages encrypted over the past %d days: %d.",
1862                                 days), days, seen_in_past);
1863                 }
1864               else if (labs(stats_iter->time_ago) == 4)
1865                 {
1866                   int months = 1 + stats_iter->time_ago / TIME_AGO_UNIT_MEDIUM;
1867                   if (stats_iter->time_ago > 0)
1868                     es_fprintf
1869                       (fp,
1870                        ngettext("Messages verified over the past %d month: %d.",
1871                                 "Messages verified over the past %d months: %d.",
1872                                 months), months, seen_in_past);
1873                   else
1874                     es_fprintf
1875                       (fp,
1876                        ngettext("Messages encrypted over the past %d month: %d.",
1877                                 "Messages encrypted over the past %d months: %d.",
1878                                 months), months, seen_in_past);
1879                 }
1880               else if (labs(stats_iter->time_ago) == 5)
1881                 {
1882                   int years = 1 + stats_iter->time_ago / TIME_AGO_UNIT_LARGE;
1883                   if (stats_iter->time_ago > 0)
1884                     es_fprintf
1885                       (fp,
1886                        ngettext("Messages verified over the past %d year: %d.",
1887                                 "Messages verified over the past %d years: %d.",
1888                                 years), years, seen_in_past);
1889                   else
1890                     es_fprintf
1891                       (fp,
1892                        ngettext("Messages encrypted over the past %d year: %d.",
1893                                 "Messages encrypted over the past %d years: %d.",
1894                                 years), years, seen_in_past);
1895                 }
1896               else if (labs(stats_iter->time_ago) == 6)
1897                 {
1898                   if (stats_iter->time_ago > 0)
1899                     es_fprintf
1900                       (fp, _("Messages verified in the past: %d."),
1901                        seen_in_past);
1902                   else
1903                     es_fprintf
1904                       (fp, _("Messages encrypted in the past: %d."),
1905                        seen_in_past);
1906                 }
1907               else
1908                 log_assert (! "Broken SQL.\n");
1909             }
1910           es_fputs ("\n", fp);
1911         }
1912     }
1913 
1914   if (conflict_set_count > 1 || (conflict_set->flags & BINDING_CONFLICT))
1915     {
1916       /* This is a conflict.  */
1917 
1918       /* TRANSLATORS: Please translate the text found in the source
1919        * file below.  We don't directly internationalize that text so
1920        * that we can tweak it without breaking translations.  */
1921       const char *text = _("TOFU detected a binding conflict");
1922       char *textbuf;
1923       if (!strcmp (text, "TOFU detected a binding conflict"))
1924         {
1925           /* No translation.  Use the English text.  */
1926           text =
1927             "Normally, an email address is associated with a single key.  "
1928             "However, people sometimes generate a new key if "
1929             "their key is too old or they think it might be compromised.  "
1930             "Alternatively, a new key may indicate a man-in-the-middle "
1931             "attack!  Before accepting this association, you should talk to or "
1932             "call the person to make sure this new key is legitimate.";
1933         }
1934       textbuf = format_text (text, 72, 80);
1935       es_fprintf (fp, "\n%s\n", textbuf? textbuf : "[OUT OF CORE!]");
1936       xfree (textbuf);
1937     }
1938 
1939   es_fputc ('\n', fp);
1940 
1941   /* Add a NUL terminator.  */
1942   es_fputc (0, fp);
1943   if (es_fclose_snatch (fp, (void **) &prompt, NULL))
1944     log_fatal ("error snatching memory stream\n");
1945 
1946   /* I think showing the large message once is sufficient.  If we
1947    * would move it right before the cpr_get many lines will scroll
1948    * away and the user might not realize that he merely entered a
1949    * wrong choice (because he does not see that either).  As a small
1950    * benefit we allow C-L to redisplay everything.  */
1951   tty_printf ("%s", prompt);
1952 
1953   /* Suspend any transaction: it could take a while until the user
1954      responds.  */
1955   tofu_suspend_batch_transaction (ctrl);
1956   while (1)
1957     {
1958       char *response;
1959 
1960       /* TRANSLATORS: Two letters (normally the lower and upper case
1961        * version of the hotkey) for each of the five choices.  If
1962        * there is only one choice in your language, repeat it.  */
1963       choices = _("gG" "aA" "uU" "rR" "bB");
1964       if (strlen (choices) != 10)
1965         log_bug ("Bad TOFU conflict translation!  Please report.");
1966 
1967       response = cpr_get
1968         ("tofu.conflict",
1969          _("(G)ood, (A)ccept once, (U)nknown, (R)eject once, (B)ad? "));
1970       trim_spaces (response);
1971       cpr_kill_prompt ();
1972       if (*response == CONTROL_L)
1973         tty_printf ("%s", prompt);
1974       else if (!response[0])
1975         /* Default to unknown.  Don't save it.  */
1976         {
1977           xfree (response);
1978           tty_printf (_("Defaulting to unknown.\n"));
1979           *policy = TOFU_POLICY_UNKNOWN;
1980           break;
1981         }
1982       else if (!response[1])
1983         {
1984           char *choice = strchr (choices, *response);
1985 
1986           if (choice)
1987             {
1988               int c = ((size_t) choice - (size_t) choices) / 2;
1989               xfree (response);
1990 
1991               switch (c)
1992                 {
1993                 case 0: /* Good.  */
1994                   *policy = TOFU_POLICY_GOOD;
1995                   *trust_level = tofu_policy_to_trust_level (*policy);
1996                   break;
1997                 case 1: /* Accept once.  */
1998                   *policy = TOFU_POLICY_ASK;
1999                   *trust_level = tofu_policy_to_trust_level (TOFU_POLICY_GOOD);
2000                   break;
2001                 case 2: /* Unknown.  */
2002                   *policy = TOFU_POLICY_UNKNOWN;
2003                   *trust_level = tofu_policy_to_trust_level (*policy);
2004                   break;
2005                 case 3: /* Reject once.  */
2006                   *policy = TOFU_POLICY_ASK;
2007                   *trust_level = tofu_policy_to_trust_level (TOFU_POLICY_BAD);
2008                   break;
2009                 case 4: /* Bad.  */
2010                   *policy = TOFU_POLICY_BAD;
2011                   *trust_level = tofu_policy_to_trust_level (*policy);
2012                   break;
2013                 default:
2014                   log_bug ("c should be between 0 and 4 but it is %d!", c);
2015                 }
2016 
2017               if (record_binding (dbs, fingerprint, email, user_id,
2018                                   *policy, TOFU_POLICY_NONE, NULL, 0, 0, now))
2019                 {
2020                   /* If there's an error registering the
2021                    * binding, don't save the signature.  */
2022                   *trust_level = _tofu_GET_TRUST_ERROR;
2023                 }
2024               break;
2025             }
2026         }
2027       xfree (response);
2028     }
2029 
2030   tofu_resume_batch_transaction (ctrl);
2031 
2032   xfree (prompt);
2033 
2034   signature_stats_free (stats);
2035 }
2036 
2037 /* Return the set of keys that conflict with the binding <fingerprint,
2038    email> (including the binding itself, which will be first in the
2039    list).  For each returned key also sets BINDING_NEW, etc.  */
2040 static strlist_t
build_conflict_set(ctrl_t ctrl,tofu_dbs_t dbs,PKT_public_key * pk,const char * fingerprint,const char * email)2041 build_conflict_set (ctrl_t ctrl, tofu_dbs_t dbs,
2042                     PKT_public_key *pk, const char *fingerprint,
2043                     const char *email)
2044 {
2045   gpg_error_t rc;
2046   char *sqerr;
2047   strlist_t conflict_set = NULL;
2048   int conflict_set_count;
2049   strlist_t iter;
2050   kbnode_t *kb_all;
2051   KEYDB_HANDLE hd;
2052   int i;
2053 
2054   /* Get the fingerprints of any bindings that share the email address
2055    * and whether the bindings have a known conflict.
2056    *
2057    * Note: if the binding in question is in the DB, it will also be
2058    * returned.  Thus, if the result set is empty, then <email,
2059    * fingerprint> is a new binding.  */
2060   rc = gpgsql_stepx
2061     (dbs->db, &dbs->s.get_trust_bindings_with_this_email,
2062      strings_collect_cb2, &conflict_set, &sqerr,
2063      "select"
2064      /* A binding should only appear once, but try not to break in the
2065       * case of corruption.  */
2066      "  fingerprint || case sum(conflict NOTNULL) when 0 then '' else '!' end"
2067      " from bindings where email = ?"
2068      "  group by fingerprint"
2069      /* Make sure the current key comes first in the result list (if
2070         it is present).  */
2071      "  order by fingerprint = ? asc, fingerprint desc;",
2072      GPGSQL_ARG_STRING, email,
2073      GPGSQL_ARG_STRING, fingerprint,
2074      GPGSQL_ARG_END);
2075   if (rc)
2076     {
2077       log_error (_("error reading TOFU database: %s\n"), sqerr);
2078       print_further_info ("listing fingerprints");
2079       sqlite3_free (sqerr);
2080       rc = gpg_error (GPG_ERR_GENERAL);
2081       return NULL;
2082     }
2083 
2084   /* Set BINDING_CONFLICT if the binding has a known conflict.  This
2085    * allows us to distinguish between bindings where the user
2086    * explicitly set the policy to ask and bindings where we set the
2087    * policy to ask due to a conflict.  */
2088   for (iter = conflict_set; iter; iter = iter->next)
2089     {
2090       /* Fixme: Why the check against N+1?  */
2091       int l = strlen (iter->d);
2092       if (!(l == 2 * 20
2093             || l == 2 * 20 + 1
2094             || l == 2 * 32
2095             || l == 2 * 32 + 1))
2096         {
2097           log_error (_("TOFU db corruption detected.\n"));
2098           print_further_info ("fingerprint '%s' is %d characters long",
2099                               iter->d, l);
2100         }
2101 
2102       if (l >= 1 && iter->d[l - 1] == '!')
2103         {
2104           iter->flags |= BINDING_CONFLICT;
2105           /* Remove the !.  */
2106           iter->d[l - 1] = 0;
2107         }
2108     }
2109 
2110   /* If the current binding has not yet been recorded, add it to the
2111    * list.  (The order by above ensures that if it is present, it will
2112    * be first.)  */
2113   if (! (conflict_set && strcmp (conflict_set->d, fingerprint) == 0))
2114     {
2115       add_to_strlist (&conflict_set, fingerprint);
2116       conflict_set->flags |= BINDING_NEW;
2117     }
2118 
2119   conflict_set_count = strlist_length (conflict_set);
2120 
2121   /* Eliminate false conflicts.  */
2122 
2123   if (conflict_set_count == 1)
2124     /* We only have a single key.  There are no false conflicts to
2125        eliminate.  But, we do need to set the flags.  */
2126     {
2127       if (pk->has_expired)
2128         conflict_set->flags |= BINDING_EXPIRED;
2129       if (pk->flags.revoked)
2130         conflict_set->flags |= BINDING_REVOKED;
2131 
2132       return conflict_set;
2133     }
2134 
2135   /* If two keys have cross signatures, then they are controlled by
2136    * the same person and thus are not in conflict.  */
2137   kb_all = xcalloc (sizeof (kb_all[0]), conflict_set_count);
2138   hd = keydb_new (ctrl);
2139   for (i = 0, iter = conflict_set;
2140        i < conflict_set_count;
2141        i ++, iter = iter->next)
2142     {
2143       char *fp = iter->d;
2144       KEYDB_SEARCH_DESC desc;
2145       kbnode_t kb;
2146       PKT_public_key *binding_pk;
2147       kbnode_t n;
2148       int found_user_id;
2149 
2150       rc = keydb_search_reset (hd);
2151       if (rc)
2152         {
2153           log_error ("resetting keydb failed: %s\n", gpg_strerror (rc));
2154           continue;
2155         }
2156 
2157       rc = classify_user_id (fp, &desc, 0);
2158       if (rc)
2159         {
2160           log_error (_("error parsing key specification '%s': %s\n"),
2161                      fp, gpg_strerror (rc));
2162           continue;
2163         }
2164 
2165       rc = keydb_search (hd, &desc, 1, NULL);
2166       if (rc)
2167         {
2168           /* Note: it is entirely possible that we don't have the key
2169              corresponding to an entry in the TOFU DB.  This can
2170              happen if we merge two TOFU DBs, but not the key
2171              rings.  */
2172           log_info (_("key \"%s\" not found: %s\n"),
2173                     fp, gpg_strerror (rc));
2174           continue;
2175         }
2176 
2177       rc = keydb_get_keyblock (hd, &kb);
2178       if (rc)
2179         {
2180           log_error (_("error reading keyblock: %s\n"),
2181                      gpg_strerror (rc));
2182           print_further_info ("fingerprint: %s", fp);
2183           continue;
2184         }
2185 
2186       merge_keys_and_selfsig (ctrl, kb);
2187 
2188       log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
2189 
2190       kb_all[i] = kb;
2191 
2192       /* Since we have the key block, use this opportunity to figure
2193        * out if the binding is expired or revoked.  */
2194       binding_pk = kb->pkt->pkt.public_key;
2195 
2196       /* The binding is always expired/revoked if the key is
2197        * expired/revoked.  */
2198       if (binding_pk->has_expired)
2199         iter->flags |= BINDING_EXPIRED;
2200       if (binding_pk->flags.revoked)
2201         iter->flags |= BINDING_REVOKED;
2202 
2203       /* The binding is also expired/revoked if the user id is
2204        * expired/revoked.  */
2205       n = kb;
2206       found_user_id = 0;
2207       while ((n = find_next_kbnode (n, PKT_USER_ID)) && ! found_user_id)
2208         {
2209           PKT_user_id *user_id2 = n->pkt->pkt.user_id;
2210           char *email2;
2211 
2212           if (user_id2->attrib_data)
2213             continue;
2214 
2215           email2 = email_from_user_id (user_id2->name);
2216 
2217           if (strcmp (email, email2) == 0)
2218             {
2219               found_user_id = 1;
2220 
2221               if (user_id2->flags.revoked)
2222                 iter->flags |= BINDING_REVOKED;
2223               if (user_id2->flags.expired)
2224                 iter->flags |= BINDING_EXPIRED;
2225             }
2226 
2227           xfree (email2);
2228         }
2229 
2230       if (! found_user_id)
2231         {
2232           log_info (_("TOFU db corruption detected.\n"));
2233           print_further_info ("user id '%s' not on key block '%s'",
2234                               email, fingerprint);
2235         }
2236     }
2237   keydb_release (hd);
2238 
2239   /* Now that we have the key blocks, check for cross sigs.  */
2240   {
2241     int j;
2242     strlist_t *prevp;
2243     strlist_t iter_next;
2244     int *die;
2245 
2246     log_assert (conflict_set_count > 0);
2247     die = xtrycalloc (conflict_set_count, sizeof *die);
2248     if (!die)
2249       {
2250         /*err = gpg_error_from_syserror ();*/
2251         xoutofcore (); /* Fixme: Let the function return an error.  */
2252       }
2253 
2254     for (i = 0; i < conflict_set_count; i ++)
2255       {
2256         /* Look for cross sigs between this key (i == 0) or a key
2257          * that has cross sigs with i == 0 (i.e., transitively) */
2258         if (! (i == 0 || die[i]))
2259           continue;
2260 
2261         for (j = i + 1; j < conflict_set_count; j ++)
2262           /* Be careful: we might not have a key block for a key.  */
2263           if (kb_all[i] && kb_all[j] && cross_sigs (email, kb_all[i], kb_all[j]))
2264             die[j] = 1;
2265       }
2266 
2267     /* Free unconflicting bindings (and all of the key blocks).  */
2268     for (iter = conflict_set, prevp = &conflict_set, i = 0;
2269          iter;
2270          iter = iter_next, i ++)
2271       {
2272         iter_next = iter->next;
2273 
2274         release_kbnode (kb_all[i]);
2275 
2276         if (die[i])
2277           {
2278             *prevp = iter_next;
2279             iter->next = NULL;
2280             free_strlist (iter);
2281             conflict_set_count --;
2282           }
2283         else
2284           {
2285             prevp = &iter->next;
2286           }
2287       }
2288 
2289     /* We shouldn't have removed the head.  */
2290     log_assert (conflict_set);
2291     log_assert (conflict_set_count >= 1);
2292     xfree (die);
2293   }
2294   xfree (kb_all);
2295 
2296   if (DBG_TRUST)
2297     {
2298       log_debug ("binding <key: %s, email: %s> conflicts:\n",
2299                  fingerprint, email);
2300       for (iter = conflict_set; iter; iter = iter->next)
2301         {
2302           log_debug ("  %s:%s%s%s%s\n",
2303                      iter->d,
2304                      (iter->flags & BINDING_NEW) ? " new" : "",
2305                      (iter->flags & BINDING_CONFLICT) ? " known_conflict" : "",
2306                      (iter->flags & BINDING_EXPIRED) ? " expired" : "",
2307                      (iter->flags & BINDING_REVOKED) ? " revoked" : "");
2308         }
2309     }
2310 
2311   return conflict_set;
2312 }
2313 
2314 
2315 /* Return the effective policy for the binding <FINGERPRINT, EMAIL>
2316  * (email has already been normalized).  Returns
2317  * _tofu_GET_POLICY_ERROR if an error occurs.  Returns any conflict
2318  * information in *CONFLICT_SETP if CONFLICT_SETP is not NULL and the
2319  * returned policy is TOFU_POLICY_ASK (consequently, if there is a
2320  * conflict, but the user set the policy to good *CONFLICT_SETP will
2321  * empty).  Note: as per build_conflict_set, which is used to build
2322  * the conflict information, the conflict information includes the
2323  * current user id as the first element of the linked list.
2324  *
2325  * This function registers the binding in the bindings table if it has
2326  * not yet been registered.
2327  */
2328 static enum tofu_policy
get_policy(ctrl_t ctrl,tofu_dbs_t dbs,PKT_public_key * pk,const char * fingerprint,const char * user_id,const char * email,strlist_t * conflict_setp,time_t now)2329 get_policy (ctrl_t ctrl, tofu_dbs_t dbs, PKT_public_key *pk,
2330             const char *fingerprint, const char *user_id, const char *email,
2331 	    strlist_t *conflict_setp, time_t now)
2332 {
2333   int rc;
2334   char *err = NULL;
2335   strlist_t results = NULL;
2336   enum tofu_policy policy = _tofu_GET_POLICY_ERROR;
2337   enum tofu_policy effective_policy_orig = TOFU_POLICY_NONE;
2338   enum tofu_policy effective_policy = _tofu_GET_POLICY_ERROR;
2339   long along;
2340   char *conflict_orig = NULL;
2341   char *conflict = NULL;
2342   strlist_t conflict_set = NULL;
2343   int conflict_set_count;
2344 
2345   /* Check if the <FINGERPRINT, EMAIL> binding is known
2346      (TOFU_POLICY_NONE cannot appear in the DB.  Thus, if POLICY is
2347      still TOFU_POLICY_NONE after executing the query, then the
2348      result set was empty.)  */
2349   rc = gpgsql_stepx (dbs->db, &dbs->s.get_policy_select_policy_and_conflict,
2350                       strings_collect_cb2, &results, &err,
2351                       "select policy, conflict, effective_policy from bindings\n"
2352                       " where fingerprint = ? and email = ?",
2353                       GPGSQL_ARG_STRING, fingerprint,
2354                       GPGSQL_ARG_STRING, email,
2355                       GPGSQL_ARG_END);
2356   if (rc)
2357     {
2358       log_error (_("error reading TOFU database: %s\n"), err);
2359       print_further_info ("reading the policy");
2360       sqlite3_free (err);
2361       rc = gpg_error (GPG_ERR_GENERAL);
2362       goto out;
2363     }
2364 
2365   if (strlist_length (results) == 0)
2366     {
2367       /* No results.  Use the defaults.  */
2368       policy = TOFU_POLICY_NONE;
2369       effective_policy = TOFU_POLICY_NONE;
2370     }
2371   else if (strlist_length (results) == 3)
2372     {
2373       /* Parse and sanity check the results.  */
2374 
2375       if (string_to_long (&along, results->d, 0, __LINE__))
2376         {
2377           log_error (_("error reading TOFU database: %s\n"),
2378                      gpg_strerror (GPG_ERR_BAD_DATA));
2379           print_further_info ("bad value for policy: %s", results->d);
2380           goto out;
2381         }
2382       policy = along;
2383 
2384       if (! (policy == TOFU_POLICY_AUTO
2385              || policy == TOFU_POLICY_GOOD
2386              || policy == TOFU_POLICY_UNKNOWN
2387              || policy == TOFU_POLICY_BAD
2388              || policy == TOFU_POLICY_ASK))
2389         {
2390           log_error (_("error reading TOFU database: %s\n"),
2391                      gpg_strerror (GPG_ERR_DB_CORRUPTED));
2392           print_further_info ("invalid value for policy (%d)", policy);
2393           effective_policy = _tofu_GET_POLICY_ERROR;
2394           goto out;
2395         }
2396 
2397       if (*results->next->d)
2398         conflict = xstrdup (results->next->d);
2399 
2400       if (string_to_long (&along, results->next->next->d, 0, __LINE__))
2401         {
2402           log_error (_("error reading TOFU database: %s\n"),
2403                      gpg_strerror (GPG_ERR_BAD_DATA));
2404           print_further_info ("bad value for effective policy: %s",
2405                               results->next->next->d);
2406           goto out;
2407         }
2408       effective_policy = along;
2409 
2410       if (! (effective_policy == TOFU_POLICY_NONE
2411              || effective_policy == TOFU_POLICY_AUTO
2412              || effective_policy == TOFU_POLICY_GOOD
2413              || effective_policy == TOFU_POLICY_UNKNOWN
2414              || effective_policy == TOFU_POLICY_BAD
2415              || effective_policy == TOFU_POLICY_ASK))
2416         {
2417           log_error (_("error reading TOFU database: %s\n"),
2418                      gpg_strerror (GPG_ERR_DB_CORRUPTED));
2419           print_further_info ("invalid value for effective_policy (%d)",
2420                               effective_policy);
2421           effective_policy = _tofu_GET_POLICY_ERROR;
2422           goto out;
2423         }
2424     }
2425   else
2426     {
2427       /* The result has the wrong form.  */
2428 
2429       log_error (_("error reading TOFU database: %s\n"),
2430                  gpg_strerror (GPG_ERR_BAD_DATA));
2431       print_further_info ("reading policy: expected 3 columns, got %d\n",
2432                           strlist_length (results));
2433       goto out;
2434     }
2435 
2436   /* Save the effective policy and conflict so we know if we changed
2437    * them.  */
2438   effective_policy_orig = effective_policy;
2439   conflict_orig = conflict;
2440 
2441   /* Unless there is a conflict, if the effective policy is cached,
2442    * just return it.  The reason we don't do this when there is a
2443    * conflict is because of the following scenario: assume A and B
2444    * conflict and B has signed A's key.  Now, later we import A's
2445    * signature on B.  We need to recheck A, but the signature was on
2446    * B, i.e., when B changes, we invalidate B's effective policy, but
2447    * we also need to invalidate A's effective policy.  Instead, we
2448    * assume that conflicts are rare and don't optimize for them, which
2449    * would complicate the code.  */
2450   if (effective_policy != TOFU_POLICY_NONE && !conflict)
2451     goto out;
2452 
2453   /* If the user explicitly set the policy, then respect that.  */
2454   if (policy != TOFU_POLICY_AUTO && policy != TOFU_POLICY_NONE)
2455     {
2456       effective_policy = policy;
2457       goto out;
2458     }
2459 
2460   /* Unless proven wrong, assume the effective policy is 'auto'.  */
2461   effective_policy = TOFU_POLICY_AUTO;
2462 
2463   /* See if the key is ultimately trusted.  */
2464   {
2465     u32 kid[2];
2466 
2467     keyid_from_pk (pk, kid);
2468     if (tdb_keyid_is_utk (kid))
2469       {
2470         effective_policy = TOFU_POLICY_GOOD;
2471         goto out;
2472       }
2473   }
2474 
2475   /* See if the key is signed by an ultimately trusted key.  */
2476   {
2477     int fingerprint_raw_len = strlen (fingerprint) / 2;
2478     char fingerprint_raw[MAX_FINGERPRINT_LEN];
2479     int len = 0;
2480 
2481     /* FIXME(fingerprint) */
2482     if (fingerprint_raw_len != 20 /*sizeof fingerprint_raw */
2483         || ((len = hex2bin (fingerprint,
2484                             fingerprint_raw, fingerprint_raw_len))
2485             != strlen (fingerprint)))
2486       {
2487         if (DBG_TRUST)
2488           log_debug ("TOFU: Bad fingerprint: %s (len: %zu, parsed: %d)\n",
2489                      fingerprint, strlen (fingerprint), len);
2490       }
2491     else
2492       {
2493         int lookup_err;
2494         kbnode_t kb;
2495 
2496         lookup_err = get_pubkey_byfprint (ctrl, NULL, &kb,
2497                                           fingerprint_raw,
2498                                           fingerprint_raw_len);
2499         if (lookup_err)
2500           {
2501             if (DBG_TRUST)
2502               log_debug ("TOFU: Looking up %s: %s\n",
2503                          fingerprint, gpg_strerror (lookup_err));
2504           }
2505         else
2506           {
2507             int is_signed_by_utk = signed_by_utk (email, kb);
2508             release_kbnode (kb);
2509             if (is_signed_by_utk)
2510               {
2511                 effective_policy = TOFU_POLICY_GOOD;
2512                 goto out;
2513               }
2514           }
2515       }
2516   }
2517 
2518   /* Check for any conflicts / see if a previously discovered conflict
2519    * disappeared.  The latter can happen if the conflicting bindings
2520    * are now cross signed, for instance.  */
2521 
2522   conflict_set = build_conflict_set (ctrl, dbs, pk, fingerprint, email);
2523   conflict_set_count = strlist_length (conflict_set);
2524   if (conflict_set_count == 0)
2525     {
2526       /* build_conflict_set should always at least return the current
2527          binding.  Something went wrong.  */
2528       effective_policy = _tofu_GET_POLICY_ERROR;
2529       goto out;
2530     }
2531 
2532   if (conflict_set_count == 1
2533       && (conflict_set->flags & BINDING_NEW))
2534     {
2535       /* We've never observed a binding with this email address and we
2536        * have a default policy, which is not to ask the user.  */
2537 
2538       /* If we've seen this binding, then we've seen this email and
2539        * policy couldn't possibly be TOFU_POLICY_NONE.  */
2540       log_assert (policy == TOFU_POLICY_NONE);
2541 
2542       if (DBG_TRUST)
2543 	log_debug ("TOFU: New binding <key: %s, user id: %s>, no conflict.\n",
2544 		   fingerprint, email);
2545 
2546       effective_policy = TOFU_POLICY_AUTO;
2547       goto out;
2548     }
2549 
2550   if (conflict_set_count == 1
2551       && (conflict_set->flags & BINDING_CONFLICT))
2552     {
2553       /* No known conflicts now, but there was a conflict.  This means
2554        * at some point, there was a conflict and we changed this
2555        * binding's policy to ask and set the conflicting key.  The
2556        * conflict can go away if there is not a cross sig between the
2557        * two keys.  In this case, just silently clear the conflict and
2558        * reset the policy to auto.  */
2559 
2560       if (DBG_TRUST)
2561         log_debug ("TOFU: binding <key: %s, user id: %s> had a conflict, but it's been resolved (probably via  cross sig).\n",
2562                    fingerprint, email);
2563 
2564       effective_policy = TOFU_POLICY_AUTO;
2565       conflict = NULL;
2566 
2567       goto out;
2568     }
2569 
2570   if (conflict_set_count == 1)
2571     {
2572       /* No conflicts and never marked as conflicting.  */
2573 
2574       log_assert (!conflict);
2575 
2576       effective_policy = TOFU_POLICY_AUTO;
2577 
2578       goto out;
2579     }
2580 
2581   /* There is a conflicting key.  */
2582   log_assert (conflict_set_count > 1);
2583   effective_policy = TOFU_POLICY_ASK;
2584   conflict = xstrdup (conflict_set->next->d);
2585 
2586  out:
2587   log_assert (policy == _tofu_GET_POLICY_ERROR
2588               || policy == TOFU_POLICY_NONE
2589               || policy == TOFU_POLICY_AUTO
2590               || policy == TOFU_POLICY_GOOD
2591               || policy == TOFU_POLICY_UNKNOWN
2592               || policy == TOFU_POLICY_BAD
2593               || policy == TOFU_POLICY_ASK);
2594   /* Everything but NONE.  */
2595   log_assert (effective_policy == _tofu_GET_POLICY_ERROR
2596               || effective_policy == TOFU_POLICY_AUTO
2597               || effective_policy == TOFU_POLICY_GOOD
2598               || effective_policy == TOFU_POLICY_UNKNOWN
2599               || effective_policy == TOFU_POLICY_BAD
2600               || effective_policy == TOFU_POLICY_ASK);
2601 
2602   if (effective_policy != TOFU_POLICY_ASK && conflict)
2603     conflict = NULL;
2604 
2605   /* If we don't have a record of this binding, its effective policy
2606    * changed, or conflict changed, update the DB.  */
2607   if (effective_policy != _tofu_GET_POLICY_ERROR
2608       && (/* New binding.  */
2609           policy == TOFU_POLICY_NONE
2610           /* effective_policy changed.  */
2611           || effective_policy != effective_policy_orig
2612           /* conflict changed.  */
2613           || (conflict != conflict_orig
2614               && (!conflict || !conflict_orig
2615                   || strcmp (conflict, conflict_orig) != 0))))
2616     {
2617       if (record_binding (dbs, fingerprint, email, user_id,
2618                           policy == TOFU_POLICY_NONE ? TOFU_POLICY_AUTO : policy,
2619                           effective_policy, conflict, 1, 0, now) != 0)
2620         log_error ("error setting TOFU binding's policy"
2621                      " to %s\n", tofu_policy_str (policy));
2622     }
2623 
2624   /* If the caller wants the set of conflicts, return it.  */
2625   if (effective_policy == TOFU_POLICY_ASK && conflict_setp)
2626     {
2627       if (! conflict_set)
2628         conflict_set = build_conflict_set (ctrl, dbs, pk, fingerprint, email);
2629       *conflict_setp = conflict_set;
2630     }
2631   else
2632     {
2633       free_strlist (conflict_set);
2634 
2635       if (conflict_setp)
2636         *conflict_setp = NULL;
2637     }
2638 
2639   xfree (conflict_orig);
2640   if (conflict != conflict_orig)
2641     xfree (conflict);
2642   free_strlist (results);
2643 
2644   return effective_policy;
2645 }
2646 
2647 
2648 /* Return the trust level (TRUST_NEVER, etc.) for the binding
2649  * <FINGERPRINT, EMAIL> (email is already normalized).  If no policy
2650  * is registered, returns TOFU_POLICY_NONE.  If an error occurs,
2651  * returns _tofu_GET_TRUST_ERROR.
2652  *
2653  * PK is the public key object for FINGERPRINT.
2654  *
2655  * USER_ID is the unadulterated user id.
2656  *
2657  * If MAY_ASK is set, then we may interact with the user.  This is
2658  * necessary if there is a conflict or the binding's policy is
2659  * TOFU_POLICY_ASK.  In the case of a conflict, we set the new
2660  * conflicting binding's policy to TOFU_POLICY_ASK.  In either case,
2661  * we return TRUST_UNDEFINED.  Note: if MAY_ASK is set, then this
2662  * function must not be called while in a transaction!  */
2663 static enum tofu_policy
get_trust(ctrl_t ctrl,PKT_public_key * pk,const char * fingerprint,const char * email,const char * user_id,int may_ask,enum tofu_policy * policyp,strlist_t * conflict_setp,time_t now)2664 get_trust (ctrl_t ctrl, PKT_public_key *pk,
2665            const char *fingerprint, const char *email,
2666            const char *user_id, int may_ask,
2667            enum tofu_policy *policyp, strlist_t *conflict_setp,
2668            time_t now)
2669 {
2670   tofu_dbs_t dbs = ctrl->tofu.dbs;
2671   int in_transaction = 0;
2672   enum tofu_policy policy;
2673   int rc;
2674   char *sqerr = NULL;
2675   strlist_t conflict_set = NULL;
2676   int trust_level = TRUST_UNKNOWN;
2677   strlist_t iter;
2678 
2679   log_assert (dbs);
2680 
2681   if (may_ask)
2682     log_assert (dbs->in_transaction == 0);
2683 
2684   if (opt.batch)
2685     may_ask = 0;
2686 
2687   log_assert (pk_is_primary (pk));
2688 
2689   /* Make sure _tofu_GET_TRUST_ERROR isn't equal to any of the trust
2690      levels.  */
2691   log_assert (_tofu_GET_TRUST_ERROR != TRUST_UNKNOWN
2692               && _tofu_GET_TRUST_ERROR != TRUST_EXPIRED
2693               && _tofu_GET_TRUST_ERROR != TRUST_UNDEFINED
2694               && _tofu_GET_TRUST_ERROR != TRUST_NEVER
2695               && _tofu_GET_TRUST_ERROR != TRUST_MARGINAL
2696               && _tofu_GET_TRUST_ERROR != TRUST_FULLY
2697               && _tofu_GET_TRUST_ERROR != TRUST_ULTIMATE);
2698 
2699   begin_transaction (ctrl, 0);
2700   in_transaction = 1;
2701 
2702   /* We need to call get_policy even if the key is ultimately trusted
2703    * to make sure the binding has been registered.  */
2704   policy = get_policy (ctrl, dbs, pk, fingerprint, user_id, email,
2705                        &conflict_set, now);
2706 
2707   if (policy == TOFU_POLICY_ASK)
2708     /* The conflict set should always contain at least one element:
2709      * the current key.  */
2710     log_assert (conflict_set);
2711   else
2712     /* If the policy is not TOFU_POLICY_ASK, then conflict_set will be
2713      * NULL.  */
2714     log_assert (! conflict_set);
2715 
2716   /* If the key is ultimately trusted, there is nothing to do.  */
2717   {
2718     u32 kid[2];
2719 
2720     keyid_from_pk (pk, kid);
2721     if (tdb_keyid_is_utk (kid))
2722       {
2723         trust_level = TRUST_ULTIMATE;
2724         policy = TOFU_POLICY_GOOD;
2725         goto out;
2726       }
2727   }
2728 
2729   if (policy == TOFU_POLICY_AUTO)
2730     {
2731       policy = opt.tofu_default_policy;
2732       if (DBG_TRUST)
2733 	log_debug ("TOFU: binding <key: %s, user id: %s>'s policy is"
2734                    " auto (default: %s).\n",
2735 		   fingerprint, email,
2736 		   tofu_policy_str (opt.tofu_default_policy));
2737 
2738       if (policy == TOFU_POLICY_ASK)
2739         /* The default policy is ASK, but there is no conflict (policy
2740          * was 'auto').  In this case, we need to make sure the
2741          * conflict set includes at least the current user id.  */
2742         {
2743           add_to_strlist (&conflict_set, fingerprint);
2744         }
2745     }
2746   switch (policy)
2747     {
2748     case TOFU_POLICY_AUTO:
2749     case TOFU_POLICY_GOOD:
2750     case TOFU_POLICY_UNKNOWN:
2751     case TOFU_POLICY_BAD:
2752       /* The saved judgement is auto -> auto, good, unknown or bad.
2753        * We don't need to ask the user anything.  */
2754       if (DBG_TRUST)
2755 	log_debug ("TOFU: Known binding <key: %s, user id: %s>'s policy: %s\n",
2756 		   fingerprint, email, tofu_policy_str (policy));
2757       trust_level = tofu_policy_to_trust_level (policy);
2758       goto out;
2759 
2760     case TOFU_POLICY_ASK:
2761       /* We need to ask the user what to do.  */
2762       break;
2763 
2764     case _tofu_GET_POLICY_ERROR:
2765       trust_level = _tofu_GET_TRUST_ERROR;
2766       goto out;
2767 
2768     default:
2769       log_bug ("%s: Impossible value for policy (%d)\n", __func__, policy);
2770     }
2771 
2772 
2773   /* We get here if:
2774    *
2775    *   1. The saved policy is auto and the default policy is ask
2776    *      (get_policy() == TOFU_POLICY_AUTO
2777    *       && opt.tofu_default_policy == TOFU_POLICY_ASK)
2778    *
2779    *   2. The saved policy is ask (either last time the user selected
2780    *      accept once or reject once or there was a conflict and this
2781    *      binding's policy was changed from auto to ask)
2782    *      (policy == TOFU_POLICY_ASK).
2783    */
2784   log_assert (policy == TOFU_POLICY_ASK);
2785 
2786   if (may_ask)
2787     {
2788       /* We can't be in a normal transaction in ask_about_binding.  */
2789       end_transaction (ctrl, 0);
2790       in_transaction = 0;
2791 
2792       /* If we get here, we need to ask the user about the binding.  */
2793       ask_about_binding (ctrl,
2794                          &policy,
2795                          &trust_level,
2796                          conflict_set,
2797                          fingerprint,
2798                          email,
2799                          user_id,
2800                          now);
2801     }
2802   else
2803     {
2804       trust_level = TRUST_UNDEFINED;
2805     }
2806 
2807   /* Mark any conflicting bindings that have an automatic policy as
2808    * now requiring confirmation.  Note: we do this after we ask for
2809    * confirmation so that when the current policy is printed, it is
2810    * correct.  */
2811   if (! in_transaction)
2812     {
2813       begin_transaction (ctrl, 0);
2814       in_transaction = 1;
2815     }
2816 
2817   /* The conflict set should always contain at least one element:
2818    * the current key.  */
2819   log_assert (conflict_set);
2820 
2821   for (iter = conflict_set->next; iter; iter = iter->next)
2822     {
2823       /* We don't immediately set the effective policy to 'ask,
2824          because  */
2825       rc = gpgsql_exec_printf
2826         (dbs->db, NULL, NULL, &sqerr,
2827          "update bindings set effective_policy = %d, conflict = %Q"
2828          " where email = %Q and fingerprint = %Q and effective_policy != %d;",
2829          TOFU_POLICY_NONE, fingerprint,
2830          email, iter->d, TOFU_POLICY_ASK);
2831       if (rc)
2832         {
2833           log_error (_("error changing TOFU policy: %s\n"), sqerr);
2834           print_further_info ("binding: <key: %s, user id: %s>",
2835                               fingerprint, user_id);
2836           sqlite3_free (sqerr);
2837           sqerr = NULL;
2838           rc = gpg_error (GPG_ERR_GENERAL);
2839         }
2840       else if (DBG_TRUST)
2841         log_debug ("Set %s to conflict with %s\n",
2842                    iter->d, fingerprint);
2843     }
2844 
2845  out:
2846   if (in_transaction)
2847     end_transaction (ctrl, 0);
2848 
2849   if (policyp)
2850     *policyp = policy;
2851 
2852   if (conflict_setp)
2853     *conflict_setp = conflict_set;
2854   else
2855     free_strlist (conflict_set);
2856 
2857   return trust_level;
2858 }
2859 
2860 
2861 /* Return a malloced string of the form
2862  *    "7~months"
2863  * The caller should replace all '~' in the returned string by a space
2864  * and also free the returned string.
2865  *
2866  * This is actually a bad hack which may not work correctly with all
2867  * languages.
2868  */
2869 static char *
time_ago_str(long long int t)2870 time_ago_str (long long int t)
2871 {
2872   /* It would be nice to use a macro to do this, but gettext
2873      works on the unpreprocessed code.  */
2874 #define MIN_SECS (60)
2875 #define HOUR_SECS (60 * MIN_SECS)
2876 #define DAY_SECS (24 * HOUR_SECS)
2877 #define WEEK_SECS (7 * DAY_SECS)
2878 #define MONTH_SECS (30 * DAY_SECS)
2879 #define YEAR_SECS (365 * DAY_SECS)
2880 
2881   if (t > 2 * YEAR_SECS)
2882     {
2883       long long int c = t / YEAR_SECS;
2884       return xtryasprintf (ngettext("%lld~year", "%lld~years", c), c);
2885     }
2886   if (t > 2 * MONTH_SECS)
2887     {
2888       long long int c = t / MONTH_SECS;
2889       return xtryasprintf (ngettext("%lld~month", "%lld~months", c), c);
2890     }
2891   if (t > 2 * WEEK_SECS)
2892     {
2893       long long int c = t / WEEK_SECS;
2894       return xtryasprintf (ngettext("%lld~week", "%lld~weeks", c), c);
2895     }
2896   if (t > 2 * DAY_SECS)
2897     {
2898       long long int c = t / DAY_SECS;
2899       return xtryasprintf (ngettext("%lld~day", "%lld~days", c), c);
2900     }
2901   if (t > 2 * HOUR_SECS)
2902     {
2903       long long int c = t / HOUR_SECS;
2904       return xtryasprintf (ngettext("%lld~hour", "%lld~hours", c), c);
2905     }
2906   if (t > 2 * MIN_SECS)
2907     {
2908       long long int c = t / MIN_SECS;
2909       return xtryasprintf (ngettext("%lld~minute", "%lld~minutes", c), c);
2910     }
2911   return xtryasprintf (ngettext("%lld~second", "%lld~seconds", t), t);
2912 }
2913 
2914 
2915 /* If FP is NULL, write TOFU_STATS status line.  If FP is not NULL
2916  * write a "tfs" record to that stream. */
2917 static void
write_stats_status(estream_t fp,enum tofu_policy policy,unsigned long signature_count,unsigned long signature_first_seen,unsigned long signature_most_recent,unsigned long signature_days,unsigned long encryption_count,unsigned long encryption_first_done,unsigned long encryption_most_recent,unsigned long encryption_days)2918 write_stats_status (estream_t fp,
2919                     enum tofu_policy policy,
2920                     unsigned long signature_count,
2921                     unsigned long signature_first_seen,
2922                     unsigned long signature_most_recent,
2923                     unsigned long signature_days,
2924                     unsigned long encryption_count,
2925                     unsigned long encryption_first_done,
2926                     unsigned long encryption_most_recent,
2927                     unsigned long encryption_days)
2928 {
2929   int summary;
2930   int validity;
2931   unsigned long days_sq;
2932 
2933   /* Use the euclidean distance (m = sqrt(a^2 + b^2)) rather then the
2934      sum of the magnitudes (m = a + b) to ensure a balance between
2935      verified signatures and encrypted messages.  */
2936   days_sq = signature_days * signature_days + encryption_days * encryption_days;
2937 
2938   if (days_sq < 1)
2939     validity = 1; /* Key without history.  */
2940   else if (days_sq < (2 * BASIC_TRUST_THRESHOLD) * (2 * BASIC_TRUST_THRESHOLD))
2941     validity = 2; /* Key with too little history.  */
2942   else if (days_sq < (2 * FULL_TRUST_THRESHOLD) * (2 * FULL_TRUST_THRESHOLD))
2943     validity = 3; /* Key with enough history for basic trust.  */
2944   else
2945     validity = 4; /* Key with a lot of history.  */
2946 
2947   if (policy == TOFU_POLICY_ASK)
2948     summary = 0; /* Key requires attention.  */
2949   else
2950     summary = validity;
2951 
2952   if (fp)
2953     {
2954       es_fprintf (fp, "tfs:1:%d:%lu:%lu:%s:%lu:%lu:%lu:%lu:%d:%lu:%lu:\n",
2955                   summary, signature_count, encryption_count,
2956                   tofu_policy_str (policy),
2957                   signature_first_seen, signature_most_recent,
2958                   encryption_first_done, encryption_most_recent,
2959                   validity, signature_days, encryption_days);
2960     }
2961   else
2962     {
2963       write_status_printf (STATUS_TOFU_STATS,
2964                            "%d %lu %lu %s %lu %lu %lu %lu %d %lu %lu",
2965                            summary,
2966                            signature_count,
2967                            encryption_count,
2968                            tofu_policy_str (policy),
2969                            signature_first_seen,
2970                            signature_most_recent,
2971                            encryption_first_done,
2972                            encryption_most_recent,
2973                            validity,
2974                            signature_days, encryption_days);
2975     }
2976 }
2977 
2978 /* Note: If OUTFP is not NULL, this function merely prints a "tfs" record
2979  * to OUTFP.
2980  *
2981  * POLICY is the key's policy (as returned by get_policy).
2982  *
2983  * Returns 0 if ONLY_STATUS_FD is set.  Otherwise, returns whether
2984  * the caller should call show_warning after iterating over all user
2985  * ids.
2986  */
2987 static int
show_statistics(tofu_dbs_t dbs,const char * fingerprint,const char * email,enum tofu_policy policy,estream_t outfp,int only_status_fd,time_t now)2988 show_statistics (tofu_dbs_t dbs,
2989                  const char *fingerprint, const char *email,
2990                  enum tofu_policy policy,
2991 		 estream_t outfp, int only_status_fd, time_t now)
2992 {
2993   char *fingerprint_pp;
2994   int rc;
2995   strlist_t strlist = NULL;
2996   char *err = NULL;
2997 
2998   unsigned long signature_first_seen = 0;
2999   unsigned long signature_most_recent = 0;
3000   unsigned long signature_count = 0;
3001   unsigned long signature_days = 0;
3002   unsigned long encryption_first_done = 0;
3003   unsigned long encryption_most_recent = 0;
3004   unsigned long encryption_count = 0;
3005   unsigned long encryption_days = 0;
3006 
3007   int show_warning = 0;
3008 
3009   if (only_status_fd && ! is_status_enabled ())
3010     return 0;
3011 
3012   fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
3013 
3014   /* Get the signature stats.  */
3015   rc = gpgsql_exec_printf
3016     (dbs->db, strings_collect_cb, &strlist, &err,
3017      "select count (*), coalesce (min (signatures.time), 0),\n"
3018      "  coalesce (max (signatures.time), 0)\n"
3019      " from signatures\n"
3020      " left join bindings on signatures.binding = bindings.oid\n"
3021      " where fingerprint = %Q and email = %Q;",
3022      fingerprint, email);
3023   if (rc)
3024     {
3025       log_error (_("error reading TOFU database: %s\n"), err);
3026       print_further_info ("getting signature statistics");
3027       sqlite3_free (err);
3028       rc = gpg_error (GPG_ERR_GENERAL);
3029       goto out;
3030     }
3031   rc = gpgsql_exec_printf
3032     (dbs->db, strings_collect_cb, &strlist, &err,
3033      "select count (*) from\n"
3034      "  (select round(signatures.time / (24 * 60 * 60)) day\n"
3035      "    from signatures\n"
3036      "    left join bindings on signatures.binding = bindings.oid\n"
3037      "    where fingerprint = %Q and email = %Q\n"
3038      "    group by day);",
3039      fingerprint, email);
3040   if (rc)
3041     {
3042       log_error (_("error reading TOFU database: %s\n"), err);
3043       print_further_info ("getting signature statistics (by day)");
3044       sqlite3_free (err);
3045       rc = gpg_error (GPG_ERR_GENERAL);
3046       goto out;
3047     }
3048 
3049   if (strlist)
3050     {
3051       /* We expect exactly 4 elements.  */
3052       log_assert (strlist->next);
3053       log_assert (strlist->next->next);
3054       log_assert (strlist->next->next->next);
3055       log_assert (! strlist->next->next->next->next);
3056 
3057       string_to_ulong (&signature_days, strlist->d, -1, __LINE__);
3058       string_to_ulong (&signature_count, strlist->next->d, -1, __LINE__);
3059       string_to_ulong (&signature_first_seen,
3060                        strlist->next->next->d, -1, __LINE__);
3061       string_to_ulong (&signature_most_recent,
3062                        strlist->next->next->next->d, -1, __LINE__);
3063 
3064       free_strlist (strlist);
3065       strlist = NULL;
3066     }
3067 
3068   /* Get the encryption stats.  */
3069   rc = gpgsql_exec_printf
3070     (dbs->db, strings_collect_cb, &strlist, &err,
3071      "select count (*), coalesce (min (encryptions.time), 0),\n"
3072      "  coalesce (max (encryptions.time), 0)\n"
3073      " from encryptions\n"
3074      " left join bindings on encryptions.binding = bindings.oid\n"
3075      " where fingerprint = %Q and email = %Q;",
3076      fingerprint, email);
3077   if (rc)
3078     {
3079       log_error (_("error reading TOFU database: %s\n"), err);
3080       print_further_info ("getting encryption statistics");
3081       sqlite3_free (err);
3082       rc = gpg_error (GPG_ERR_GENERAL);
3083       goto out;
3084     }
3085   rc = gpgsql_exec_printf
3086     (dbs->db, strings_collect_cb, &strlist, &err,
3087      "select count (*) from\n"
3088      "  (select round(encryptions.time / (24 * 60 * 60)) day\n"
3089      "    from encryptions\n"
3090      "    left join bindings on encryptions.binding = bindings.oid\n"
3091      "    where fingerprint = %Q and email = %Q\n"
3092      "    group by day);",
3093      fingerprint, email);
3094   if (rc)
3095     {
3096       log_error (_("error reading TOFU database: %s\n"), err);
3097       print_further_info ("getting encryption statistics (by day)");
3098       sqlite3_free (err);
3099       rc = gpg_error (GPG_ERR_GENERAL);
3100       goto out;
3101     }
3102 
3103   if (strlist)
3104     {
3105       /* We expect exactly 4 elements.  */
3106       log_assert (strlist->next);
3107       log_assert (strlist->next->next);
3108       log_assert (strlist->next->next->next);
3109       log_assert (! strlist->next->next->next->next);
3110 
3111       string_to_ulong (&encryption_days, strlist->d, -1, __LINE__);
3112       string_to_ulong (&encryption_count, strlist->next->d, -1, __LINE__);
3113       string_to_ulong (&encryption_first_done,
3114                        strlist->next->next->d, -1, __LINE__);
3115       string_to_ulong (&encryption_most_recent,
3116                        strlist->next->next->next->d, -1, __LINE__);
3117 
3118       free_strlist (strlist);
3119       strlist = NULL;
3120     }
3121 
3122   if (!outfp)
3123     write_status_text_and_buffer (STATUS_TOFU_USER, fingerprint,
3124                                   email, strlen (email), 0);
3125 
3126   write_stats_status (outfp, policy,
3127                       signature_count,
3128                       signature_first_seen,
3129                       signature_most_recent,
3130                       signature_days,
3131                       encryption_count,
3132                       encryption_first_done,
3133                       encryption_most_recent,
3134                       encryption_days);
3135 
3136   if (!outfp && !only_status_fd)
3137     {
3138       estream_t fp;
3139       char *msg;
3140 
3141       fp = es_fopenmem (0, "rw,samethread");
3142       if (! fp)
3143         log_fatal ("error creating memory stream: %s\n",
3144                    gpg_strerror (gpg_error_from_syserror()));
3145 
3146       if (signature_count == 0 && encryption_count == 0)
3147         {
3148           es_fprintf (fp,
3149                       _("%s: Verified 0~signatures and encrypted 0~messages."),
3150                       email);
3151         }
3152       else
3153         {
3154           if (signature_count == 0)
3155             es_fprintf (fp, _("%s: Verified 0 signatures."), email);
3156           else
3157             {
3158               /* Note: Translation not possible with that wording.  */
3159               char *ago_str = time_ago_str (now - signature_first_seen);
3160               es_fprintf
3161                 (fp, "%s: Verified %ld~signatures in the past %s.",
3162                  email, signature_count, ago_str);
3163               xfree (ago_str);
3164             }
3165 
3166           es_fputs ("  ", fp);
3167 
3168           if (encryption_count == 0)
3169             es_fprintf (fp, _("Encrypted 0 messages."));
3170           else
3171             {
3172               char *ago_str = time_ago_str (now - encryption_first_done);
3173 
3174               /* Note: Translation not possible with this kind of
3175                * composition.  */
3176               es_fprintf (fp, "Encrypted %ld~messages in the past %s.",
3177                           encryption_count, ago_str);
3178               xfree (ago_str);
3179             }
3180         }
3181 
3182       if (opt.verbose)
3183         {
3184           es_fputs ("  ", fp);
3185           es_fprintf (fp, _("(policy: %s)"), tofu_policy_str (policy));
3186         }
3187       es_fputs ("\n", fp);
3188 
3189 
3190       {
3191         char *tmpmsg, *p;
3192         es_fputc (0, fp);
3193         if (es_fclose_snatch (fp, (void **) &tmpmsg, NULL))
3194           log_fatal ("error snatching memory stream\n");
3195         msg = format_text (tmpmsg, 72, 80);
3196         if (!msg) /* FIXME: Return the error all the way up.  */
3197           log_fatal ("format failed: %s\n",
3198                      gpg_strerror (gpg_error_from_syserror()));
3199         es_free (tmpmsg);
3200 
3201         /* Print a status line but suppress the trailing LF.
3202          * Spaces are not percent escaped. */
3203         if (*msg)
3204           write_status_buffer (STATUS_TOFU_STATS_LONG,
3205                                msg, strlen (msg)-1, -1);
3206 
3207         /* Remove the non-breaking space markers.  */
3208         for (p=msg; *p; p++)
3209           if (*p == '~')
3210             *p = ' ';
3211       }
3212 
3213       log_string (GPGRT_LOGLVL_INFO, msg);
3214       xfree (msg);
3215 
3216       if (policy == TOFU_POLICY_AUTO)
3217         {
3218           if (signature_count == 0)
3219             log_info (_("Warning: we have yet to see"
3220                         " a message signed using this key and user id!\n"));
3221           else if (signature_count == 1)
3222             log_info (_("Warning: we've only seen one message"
3223                         " signed using this key and user id!\n"));
3224 
3225           if (encryption_count == 0)
3226             log_info (_("Warning: you have yet to encrypt"
3227                         " a message to this key!\n"));
3228           else if (encryption_count == 1)
3229             log_info (_("Warning: you have only encrypted"
3230                         " one message to this key!\n"));
3231 
3232           /* Cf. write_stats_status  */
3233           if ((encryption_count * encryption_count
3234 	       + signature_count * signature_count)
3235 	      < ((2 * BASIC_TRUST_THRESHOLD) * (2 * BASIC_TRUST_THRESHOLD)))
3236             show_warning = 1;
3237         }
3238     }
3239 
3240  out:
3241   xfree (fingerprint_pp);
3242 
3243   return show_warning;
3244 }
3245 
3246 static void
show_warning(const char * fingerprint,strlist_t user_id_list)3247 show_warning (const char *fingerprint, strlist_t user_id_list)
3248 {
3249   char *set_policy_command;
3250   char *text;
3251   char *tmpmsg;
3252 
3253   set_policy_command =
3254     xasprintf ("gpg --tofu-policy bad %s", fingerprint);
3255 
3256   tmpmsg = xasprintf
3257     (ngettext
3258      ("Warning: if you think you've seen more signatures "
3259       "by this key and user id, then this key might be a "
3260       "forgery!  Carefully examine the email address for small "
3261       "variations.  If the key is suspect, then use\n"
3262       "  %s\n"
3263       "to mark it as being bad.\n",
3264       "Warning: if you think you've seen more signatures "
3265       "by this key and these user ids, then this key might be a "
3266       "forgery!  Carefully examine the email addresses for small "
3267       "variations.  If the key is suspect, then use\n"
3268       "  %s\n"
3269       "to mark it as being bad.\n",
3270       strlist_length (user_id_list)),
3271      set_policy_command);
3272 
3273   text = format_text (tmpmsg, 72, 80);
3274   if (!text) /* FIXME: Return the error all the way up.  */
3275     log_fatal ("format failed: %s\n",
3276                gpg_strerror (gpg_error_from_syserror()));
3277   xfree (tmpmsg);
3278   log_string (GPGRT_LOGLVL_INFO, text);
3279   xfree (text);
3280 
3281   es_free (set_policy_command);
3282 }
3283 
3284 
3285 /* Extract the email address from a user id and normalize it.  If the
3286    user id doesn't contain an email address, then we use the whole
3287    user_id and normalize that.  The returned string must be freed.  */
3288 static char *
email_from_user_id(const char * user_id)3289 email_from_user_id (const char *user_id)
3290 {
3291   char *email = mailbox_from_userid (user_id, 0);
3292   if (! email)
3293     {
3294       /* Hmm, no email address was provided or we are out of core.  Just
3295          take the lower-case version of the whole user id.  It could be
3296          a hostname, for instance.  */
3297       email = ascii_strlwr (xstrdup (user_id));
3298     }
3299 
3300   return email;
3301 }
3302 
3303 /* Register the signature with the bindings <fingerprint, USER_ID>,
3304    for each USER_ID in USER_ID_LIST.  The fingerprint is taken from
3305    the primary key packet PK.
3306 
3307    SIG_DIGEST_BIN is the binary representation of the message's
3308    digest.  SIG_DIGEST_BIN_LEN is its length.
3309 
3310    SIG_TIME is the time that the signature was generated.
3311 
3312    ORIGIN is a free-formed string describing the origin of the
3313    signature.  If this was from an email and the Claws MUA was used,
3314    then this should be something like: "email:claws".  If this is
3315    NULL, the default is simply "unknown".
3316 
3317    If MAY_ASK is 1, then this function may interact with the user.
3318    This is necessary if there is a conflict or the binding's policy is
3319    TOFU_POLICY_ASK.
3320 
3321    This function returns 0 on success and an error code if an error
3322    occurred.  */
3323 gpg_error_t
tofu_register_signature(ctrl_t ctrl,PKT_public_key * pk,strlist_t user_id_list,const byte * sig_digest_bin,int sig_digest_bin_len,time_t sig_time,const char * origin)3324 tofu_register_signature (ctrl_t ctrl,
3325                          PKT_public_key *pk, strlist_t user_id_list,
3326                          const byte *sig_digest_bin, int sig_digest_bin_len,
3327                          time_t sig_time, const char *origin)
3328 {
3329   time_t now = gnupg_get_time ();
3330   gpg_error_t rc;
3331   tofu_dbs_t dbs;
3332   char *fingerprint = NULL;
3333   strlist_t user_id;
3334   char *email = NULL;
3335   char *sqlerr = NULL;
3336   char *sig_digest = NULL;
3337   unsigned long c;
3338 
3339   dbs = opendbs (ctrl);
3340   if (! dbs)
3341     {
3342       rc = gpg_error (GPG_ERR_GENERAL);
3343       log_error (_("error opening TOFU database: %s\n"),
3344                  gpg_strerror (rc));
3345       return rc;
3346     }
3347 
3348   /* We do a query and then an insert.  Make sure they are atomic
3349      by wrapping them in a transaction.  */
3350   rc = begin_transaction (ctrl, 0);
3351   if (rc)
3352     return rc;
3353 
3354   log_assert (pk_is_primary (pk));
3355 
3356   sig_digest = make_radix64_string (sig_digest_bin, sig_digest_bin_len);
3357   if (!sig_digest)
3358     {
3359       rc = gpg_error_from_syserror ();
3360       goto leave;
3361     }
3362   fingerprint = hexfingerprint (pk, NULL, 0);
3363   if (!fingerprint)
3364     {
3365       rc = gpg_error_from_syserror ();
3366       goto leave;
3367     }
3368 
3369   if (! origin)
3370     origin = "unknown";  /* The default origin is simply "unknown".  */
3371 
3372   for (user_id = user_id_list; user_id; user_id = user_id->next)
3373     {
3374       email = email_from_user_id (user_id->d);
3375 
3376       if (DBG_TRUST)
3377 	log_debug ("TOFU: Registering signature %s with binding"
3378                    " <key: %s, user id: %s>\n",
3379 		   sig_digest, fingerprint, email);
3380 
3381       /* Make sure the binding exists and record any TOFU
3382          conflicts.  */
3383       if (get_trust (ctrl, pk, fingerprint, email, user_id->d,
3384                      0, NULL, NULL, now)
3385           == _tofu_GET_TRUST_ERROR)
3386         {
3387           rc = gpg_error (GPG_ERR_GENERAL);
3388           xfree (email);
3389           break;
3390         }
3391 
3392       /* If we've already seen this signature before, then don't add
3393          it again.  */
3394       rc = gpgsql_stepx
3395         (dbs->db, &dbs->s.register_already_seen,
3396          get_single_unsigned_long_cb2, &c, &sqlerr,
3397          "select count (*)\n"
3398          " from signatures left join bindings\n"
3399          "  on signatures.binding = bindings.oid\n"
3400          " where fingerprint = ? and email = ? and sig_time = ?\n"
3401          "  and sig_digest = ?",
3402          GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3403          GPGSQL_ARG_LONG_LONG, (long long) sig_time,
3404          GPGSQL_ARG_STRING, sig_digest,
3405          GPGSQL_ARG_END);
3406       if (rc)
3407         {
3408           log_error (_("error reading TOFU database: %s\n"), sqlerr);
3409           print_further_info ("checking existence");
3410           sqlite3_free (sqlerr);
3411           rc = gpg_error (GPG_ERR_GENERAL);
3412         }
3413       else if (c > 1)
3414         /* Duplicates!  This should not happen.  In particular,
3415            because <fingerprint, email, sig_time, sig_digest> is the
3416            primary key!  */
3417         log_debug ("SIGNATURES DB contains duplicate records"
3418                    " <key: %s, email: %s, time: 0x%lx, sig: %s,"
3419                    " origin: %s>."
3420                    "  Please report.\n",
3421                    fingerprint, email, (unsigned long) sig_time,
3422                    sig_digest, origin);
3423       else if (c == 1)
3424         {
3425           if (DBG_TRUST)
3426             log_debug ("Already observed the signature and binding"
3427                        " <key: %s, email: %s, time: 0x%lx, sig: %s,"
3428                        " origin: %s>\n",
3429                        fingerprint, email, (unsigned long) sig_time,
3430                        sig_digest, origin);
3431         }
3432       else if (opt.dry_run)
3433         {
3434           log_info ("TOFU database update skipped due to --dry-run\n");
3435         }
3436       else
3437         /* This is the first time that we've seen this signature and
3438            binding.  Record it.  */
3439         {
3440           if (DBG_TRUST)
3441             log_debug ("TOFU: Saving signature"
3442                        " <key: %s, user id: %s, sig: %s>\n",
3443                        fingerprint, email, sig_digest);
3444 
3445           log_assert (c == 0);
3446 
3447           rc = gpgsql_stepx
3448             (dbs->db, &dbs->s.register_signature, NULL, NULL, &sqlerr,
3449              "insert into signatures\n"
3450              " (binding, sig_digest, origin, sig_time, time)\n"
3451              " values\n"
3452              " ((select oid from bindings\n"
3453              "    where fingerprint = ? and email = ?),\n"
3454              "  ?, ?, ?, ?);",
3455              GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3456              GPGSQL_ARG_STRING, sig_digest, GPGSQL_ARG_STRING, origin,
3457              GPGSQL_ARG_LONG_LONG, (long long) sig_time,
3458              GPGSQL_ARG_LONG_LONG, (long long) now,
3459              GPGSQL_ARG_END);
3460           if (rc)
3461             {
3462               log_error (_("error updating TOFU database: %s\n"), sqlerr);
3463               print_further_info ("insert signatures");
3464               sqlite3_free (sqlerr);
3465               rc = gpg_error (GPG_ERR_GENERAL);
3466             }
3467         }
3468 
3469       xfree (email);
3470 
3471       if (rc)
3472         break;
3473     }
3474 
3475  leave:
3476   if (rc)
3477     rollback_transaction (ctrl);
3478   else
3479     rc = end_transaction (ctrl, 0);
3480 
3481   xfree (fingerprint);
3482   xfree (sig_digest);
3483 
3484   return rc;
3485 }
3486 
3487 gpg_error_t
tofu_register_encryption(ctrl_t ctrl,PKT_public_key * pk,strlist_t user_id_list,int may_ask)3488 tofu_register_encryption (ctrl_t ctrl,
3489                           PKT_public_key *pk, strlist_t user_id_list,
3490                           int may_ask)
3491 {
3492   time_t now = gnupg_get_time ();
3493   gpg_error_t rc = 0;
3494   tofu_dbs_t dbs;
3495   kbnode_t kb = NULL;
3496   int free_user_id_list = 0;
3497   char *fingerprint = NULL;
3498   strlist_t user_id;
3499   char *sqlerr = NULL;
3500   int in_batch = 0;
3501 
3502   dbs = opendbs (ctrl);
3503   if (! dbs)
3504     {
3505       rc = gpg_error (GPG_ERR_GENERAL);
3506       log_error (_("error opening TOFU database: %s\n"),
3507                  gpg_strerror (rc));
3508       return rc;
3509     }
3510 
3511   if (/* We need the key block to find the primary key.  */
3512       ! pk_is_primary (pk)
3513       /* We need the key block to find all user ids.  */
3514       || ! user_id_list)
3515     kb = get_pubkeyblock (ctrl, pk->keyid);
3516 
3517   /* Make sure PK is a primary key.  */
3518   if (! pk_is_primary (pk))
3519     pk = kb->pkt->pkt.public_key;
3520 
3521   if (! user_id_list)
3522     {
3523       /* Use all non-revoked user ids.  Do use expired user ids.  */
3524       kbnode_t n = kb;
3525 
3526       while ((n = find_next_kbnode (n, PKT_USER_ID)))
3527         {
3528 	  PKT_user_id *uid = n->pkt->pkt.user_id;
3529 
3530           if (uid->flags.revoked)
3531             continue;
3532 
3533           add_to_strlist (&user_id_list, uid->name);
3534         }
3535 
3536       free_user_id_list = 1;
3537 
3538       if (! user_id_list)
3539         log_info (_("WARNING: Encrypting to %s, which has no "
3540                     "non-revoked user ids\n"),
3541                   keystr (pk->keyid));
3542     }
3543 
3544   fingerprint = hexfingerprint (pk, NULL, 0);
3545   if (!fingerprint)
3546     {
3547       rc = gpg_error_from_syserror ();
3548       goto leave;
3549     }
3550 
3551   tofu_begin_batch_update (ctrl);
3552   in_batch = 1;
3553   tofu_resume_batch_transaction (ctrl);
3554 
3555   for (user_id = user_id_list; user_id; user_id = user_id->next)
3556     {
3557       char *email = email_from_user_id (user_id->d);
3558       strlist_t conflict_set = NULL;
3559       enum tofu_policy policy;
3560 
3561       /* Make sure the binding exists and that we recognize any
3562          conflicts.  */
3563       int tl = get_trust (ctrl, pk, fingerprint, email, user_id->d,
3564                           may_ask, &policy, &conflict_set, now);
3565       if (tl == _tofu_GET_TRUST_ERROR)
3566         {
3567           /* An error.  */
3568           rc = gpg_error (GPG_ERR_GENERAL);
3569           xfree (email);
3570           goto leave;
3571         }
3572 
3573 
3574       /* If there is a conflict and MAY_ASK is true, we need to show
3575        * the TOFU statistics for the current binding and the
3576        * conflicting bindings.  But, if we are not in batch mode, then
3577        * they have already been printed (this is required to make sure
3578        * the information is available to the caller before cpr_get is
3579        * called).  */
3580       if (policy == TOFU_POLICY_ASK && may_ask && opt.batch)
3581         {
3582           strlist_t iter;
3583 
3584           /* The conflict set should contain at least the current
3585            * key.  */
3586           log_assert (conflict_set);
3587 
3588           for (iter = conflict_set; iter; iter = iter->next)
3589             show_statistics (dbs, iter->d, email,
3590                              TOFU_POLICY_ASK, NULL, 1, now);
3591         }
3592 
3593       free_strlist (conflict_set);
3594 
3595       rc = gpgsql_stepx
3596         (dbs->db, &dbs->s.register_encryption, NULL, NULL, &sqlerr,
3597          "insert into encryptions\n"
3598          " (binding, time)\n"
3599          " values\n"
3600          " ((select oid from bindings\n"
3601          "    where fingerprint = ? and email = ?),\n"
3602          "  ?);",
3603          GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3604          GPGSQL_ARG_LONG_LONG, (long long) now,
3605          GPGSQL_ARG_END);
3606       if (rc)
3607         {
3608           log_error (_("error updating TOFU database: %s\n"), sqlerr);
3609           print_further_info ("insert encryption");
3610           sqlite3_free (sqlerr);
3611           rc = gpg_error (GPG_ERR_GENERAL);
3612         }
3613 
3614       xfree (email);
3615     }
3616 
3617  leave:
3618   if (in_batch)
3619     tofu_end_batch_update (ctrl);
3620 
3621   release_kbnode (kb);
3622   if (free_user_id_list)
3623     free_strlist (user_id_list);
3624   xfree (fingerprint);
3625 
3626   return rc;
3627 }
3628 
3629 
3630 /* Combine a trust level returned from the TOFU trust model with a
3631    trust level returned by the PGP trust model.  This is primarily of
3632    interest when the trust model is tofu+pgp (TM_TOFU_PGP).
3633 
3634    This function ors together the upper bits (the values not covered
3635    by TRUST_MASK, i.e., TRUST_FLAG_REVOKED, etc.).  */
3636 int
tofu_wot_trust_combine(int tofu_base,int wot_base)3637 tofu_wot_trust_combine (int tofu_base, int wot_base)
3638 {
3639   int tofu = tofu_base & TRUST_MASK;
3640   int wot = wot_base & TRUST_MASK;
3641   int upper = (tofu_base & ~TRUST_MASK) | (wot_base & ~TRUST_MASK);
3642 
3643   log_assert (tofu == TRUST_UNKNOWN
3644               || tofu == TRUST_EXPIRED
3645               || tofu == TRUST_UNDEFINED
3646               || tofu == TRUST_NEVER
3647               || tofu == TRUST_MARGINAL
3648               || tofu == TRUST_FULLY
3649               || tofu == TRUST_ULTIMATE);
3650   log_assert (wot == TRUST_UNKNOWN
3651               || wot == TRUST_EXPIRED
3652               || wot == TRUST_UNDEFINED
3653               || wot == TRUST_NEVER
3654               || wot == TRUST_MARGINAL
3655               || wot == TRUST_FULLY
3656               || wot == TRUST_ULTIMATE);
3657 
3658   /* We first consider negative trust policys.  These trump positive
3659      trust policies.  */
3660   if (tofu == TRUST_NEVER || wot == TRUST_NEVER)
3661     /* TRUST_NEVER trumps everything else.  */
3662     return upper | TRUST_NEVER;
3663   if (tofu == TRUST_EXPIRED || wot == TRUST_EXPIRED)
3664     /* TRUST_EXPIRED trumps everything but TRUST_NEVER.  */
3665     return upper | TRUST_EXPIRED;
3666 
3667   /* Now we only have positive or neutral trust policies.  We take
3668      the max.  */
3669   if (tofu == TRUST_ULTIMATE)
3670     return upper | TRUST_ULTIMATE | TRUST_FLAG_TOFU_BASED;
3671   if (wot == TRUST_ULTIMATE)
3672     return upper | TRUST_ULTIMATE;
3673 
3674   if (tofu == TRUST_FULLY)
3675     return upper | TRUST_FULLY | TRUST_FLAG_TOFU_BASED;
3676   if (wot == TRUST_FULLY)
3677     return upper | TRUST_FULLY;
3678 
3679   if (tofu == TRUST_MARGINAL)
3680     return upper | TRUST_MARGINAL | TRUST_FLAG_TOFU_BASED;
3681   if (wot == TRUST_MARGINAL)
3682     return upper | TRUST_MARGINAL;
3683 
3684   if (tofu == TRUST_UNDEFINED)
3685     return upper | TRUST_UNDEFINED | TRUST_FLAG_TOFU_BASED;
3686   if (wot == TRUST_UNDEFINED)
3687     return upper | TRUST_UNDEFINED;
3688 
3689   return upper | TRUST_UNKNOWN;
3690 }
3691 
3692 
3693 /* Write a "tfs" record for a --with-colons listing.  */
3694 gpg_error_t
tofu_write_tfs_record(ctrl_t ctrl,estream_t fp,PKT_public_key * pk,const char * user_id)3695 tofu_write_tfs_record (ctrl_t ctrl, estream_t fp,
3696                        PKT_public_key *pk, const char *user_id)
3697 {
3698   time_t now = gnupg_get_time ();
3699   gpg_error_t err = 0;
3700   tofu_dbs_t dbs;
3701   char *fingerprint;
3702   char *email = NULL;
3703   enum tofu_policy policy;
3704 
3705   if (!*user_id)
3706     return 0;  /* No TOFU stats possible for an empty ID.  */
3707 
3708   dbs = opendbs (ctrl);
3709   if (!dbs)
3710     {
3711       err = gpg_error (GPG_ERR_GENERAL);
3712       log_error (_("error opening TOFU database: %s\n"), gpg_strerror (err));
3713       return err;
3714     }
3715 
3716   fingerprint = hexfingerprint (pk, NULL, 0);
3717   if (!fingerprint)
3718     {
3719       err = gpg_error_from_syserror ();
3720       goto leave;
3721     }
3722   email = email_from_user_id (user_id);
3723   policy = get_policy (ctrl, dbs, pk, fingerprint, user_id, email, NULL, now);
3724 
3725   show_statistics (dbs, fingerprint, email, policy, fp, 0, now);
3726 
3727  leave:
3728   xfree (email);
3729   xfree (fingerprint);
3730   return err;
3731 }
3732 
3733 
3734 /* Return the validity (TRUST_NEVER, etc.) of the bindings
3735    <FINGERPRINT, USER_ID>, for each USER_ID in USER_ID_LIST.  If
3736    USER_ID_LIST->FLAG is set, then the id is considered to be expired.
3737 
3738    PK is the primary key packet.
3739 
3740    If MAY_ASK is 1 and the policy is TOFU_POLICY_ASK, then the user
3741    will be prompted to choose a policy.  If MAY_ASK is 0 and the
3742    policy is TOFU_POLICY_ASK, then TRUST_UNKNOWN is returned.
3743 
3744    Returns TRUST_UNDEFINED if an error occurs.
3745 
3746    Fixme: eturn an error code
3747   */
3748 int
tofu_get_validity(ctrl_t ctrl,PKT_public_key * pk,strlist_t user_id_list,int may_ask)3749 tofu_get_validity (ctrl_t ctrl, PKT_public_key *pk, strlist_t user_id_list,
3750 		   int may_ask)
3751 {
3752   time_t now = gnupg_get_time ();
3753   tofu_dbs_t dbs;
3754   char *fingerprint = NULL;
3755   strlist_t user_id;
3756   int trust_level = TRUST_UNKNOWN;
3757   int bindings = 0;
3758   int bindings_valid = 0;
3759   int need_warning = 0;
3760   int had_conflict = 0;
3761 
3762   dbs = opendbs (ctrl);
3763   if (! dbs)
3764     {
3765       log_error (_("error opening TOFU database: %s\n"),
3766                  gpg_strerror (GPG_ERR_GENERAL));
3767       return TRUST_UNDEFINED;
3768     }
3769 
3770   fingerprint = hexfingerprint (pk, NULL, 0);
3771   if (!fingerprint)
3772     log_fatal ("%s: malloc failed\n", __func__);
3773 
3774   tofu_begin_batch_update (ctrl);
3775   /* Start the batch transaction now.  */
3776   tofu_resume_batch_transaction (ctrl);
3777 
3778   for (user_id = user_id_list; user_id; user_id = user_id->next, bindings ++)
3779     {
3780       char *email = email_from_user_id (user_id->d);
3781       strlist_t conflict_set = NULL;
3782       enum tofu_policy policy;
3783 
3784       /* Always call get_trust to make sure the binding is
3785          registered.  */
3786       int tl = get_trust (ctrl, pk, fingerprint, email, user_id->d,
3787                           may_ask, &policy, &conflict_set, now);
3788       if (tl == _tofu_GET_TRUST_ERROR)
3789         {
3790           /* An error.  */
3791           trust_level = TRUST_UNDEFINED;
3792           xfree (email);
3793           goto die;
3794         }
3795 
3796       if (DBG_TRUST)
3797 	log_debug ("TOFU: validity for <key: %s, user id: %s>: %s%s.\n",
3798 		   fingerprint, email,
3799                    trust_value_to_string (tl),
3800                    user_id->flags ? " (but expired)" : "");
3801 
3802       if (user_id->flags)
3803         tl = TRUST_EXPIRED;
3804 
3805       if (tl != TRUST_EXPIRED)
3806         bindings_valid ++;
3807 
3808       if (may_ask && tl != TRUST_ULTIMATE && tl != TRUST_EXPIRED)
3809         {
3810           /* If policy is ask, then we already printed out the
3811            * conflict information in ask_about_binding or will do so
3812            * in a moment.  */
3813           if (policy != TOFU_POLICY_ASK)
3814             need_warning |=
3815               show_statistics (dbs, fingerprint, email, policy, NULL, 0, now);
3816 
3817           /* If there is a conflict and MAY_ASK is true, we need to
3818            * show the TOFU statistics for the current binding and the
3819            * conflicting bindings.  But, if we are not in batch mode,
3820            * then they have already been printed (this is required to
3821            * make sure the information is available to the caller
3822            * before cpr_get is called).  */
3823           if (policy == TOFU_POLICY_ASK && opt.batch)
3824             {
3825               strlist_t iter;
3826 
3827               /* The conflict set should contain at least the current
3828                * key.  */
3829               log_assert (conflict_set);
3830 
3831               had_conflict = 1;
3832               for (iter = conflict_set; iter; iter = iter->next)
3833                 show_statistics (dbs, iter->d, email,
3834                                  TOFU_POLICY_ASK, NULL, 1, now);
3835             }
3836         }
3837 
3838       free_strlist (conflict_set);
3839 
3840       if (tl == TRUST_NEVER)
3841         trust_level = TRUST_NEVER;
3842       else if (tl == TRUST_EXPIRED)
3843         /* Ignore expired bindings in the trust calculation.  */
3844         ;
3845       else if (tl > trust_level)
3846         {
3847           /* The expected values: */
3848           log_assert (tl == TRUST_UNKNOWN || tl == TRUST_UNDEFINED
3849                       || tl == TRUST_MARGINAL || tl == TRUST_FULLY
3850                       || tl == TRUST_ULTIMATE);
3851 
3852           /* We assume the following ordering:  */
3853           log_assert (TRUST_UNKNOWN < TRUST_UNDEFINED);
3854           log_assert (TRUST_UNDEFINED < TRUST_MARGINAL);
3855           log_assert (TRUST_MARGINAL < TRUST_FULLY);
3856           log_assert (TRUST_FULLY < TRUST_ULTIMATE);
3857 
3858           trust_level = tl;
3859         }
3860 
3861       xfree (email);
3862     }
3863 
3864   if (need_warning && ! had_conflict)
3865     show_warning (fingerprint, user_id_list);
3866 
3867  die:
3868   tofu_end_batch_update (ctrl);
3869 
3870   xfree (fingerprint);
3871 
3872   if (bindings_valid == 0)
3873     {
3874       if (DBG_TRUST)
3875         log_debug ("no (of %d) valid bindings."
3876                    "  Can't get TOFU validity for this set of user ids.\n",
3877                    bindings);
3878       return TRUST_NEVER;
3879     }
3880 
3881   return trust_level;
3882 }
3883 
3884 /* Set the policy for all non-revoked user ids in the keyblock KB to
3885    POLICY.
3886 
3887    If no key is available with the specified key id, then this
3888    function returns GPG_ERR_NO_PUBKEY.
3889 
3890    Returns 0 on success and an error code otherwise.  */
3891 gpg_error_t
tofu_set_policy(ctrl_t ctrl,kbnode_t kb,enum tofu_policy policy)3892 tofu_set_policy (ctrl_t ctrl, kbnode_t kb, enum tofu_policy policy)
3893 {
3894   gpg_error_t err = 0;
3895   time_t now = gnupg_get_time ();
3896   tofu_dbs_t dbs;
3897   PKT_public_key *pk;
3898   char *fingerprint = NULL;
3899 
3900   log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
3901   pk = kb->pkt->pkt.public_key;
3902 
3903   dbs = opendbs (ctrl);
3904   if (! dbs)
3905     {
3906       log_error (_("error opening TOFU database: %s\n"),
3907                  gpg_strerror (GPG_ERR_GENERAL));
3908       return gpg_error (GPG_ERR_GENERAL);
3909     }
3910 
3911   if (DBG_TRUST)
3912     log_debug ("Setting TOFU policy for %s to %s\n",
3913 	       keystr (pk->keyid), tofu_policy_str (policy));
3914   if (! pk_is_primary (pk))
3915     log_bug ("%s: Passed a subkey, but expecting a primary key.\n", __func__);
3916 
3917   fingerprint = hexfingerprint (pk, NULL, 0);
3918   if (!fingerprint)
3919     return gpg_error_from_syserror ();
3920 
3921   begin_transaction (ctrl, 0);
3922 
3923   for (; kb; kb = kb->next)
3924     {
3925       PKT_user_id *user_id;
3926       char *email;
3927 
3928       if (kb->pkt->pkttype != PKT_USER_ID)
3929 	continue;
3930 
3931       user_id = kb->pkt->pkt.user_id;
3932       if (user_id->flags.revoked)
3933 	/* Skip revoked user ids.  (Don't skip expired user ids, the
3934 	   expiry can be changed.)  */
3935 	continue;
3936 
3937       email = email_from_user_id (user_id->name);
3938 
3939       err = record_binding (dbs, fingerprint, email, user_id->name,
3940                             policy, TOFU_POLICY_NONE, NULL, 0, 1, now);
3941       if (err)
3942         {
3943           log_error ("error setting policy for key %s, user id \"%s\": %s",
3944                      fingerprint, email, gpg_strerror (err));
3945           xfree (email);
3946           break;
3947         }
3948 
3949       xfree (email);
3950     }
3951 
3952   if (err)
3953     rollback_transaction (ctrl);
3954   else
3955     end_transaction (ctrl, 0);
3956 
3957   xfree (fingerprint);
3958   return err;
3959 }
3960 
3961 /* Return the TOFU policy for the specified binding in *POLICY.  If no
3962    policy has been set for the binding, sets *POLICY to
3963    TOFU_POLICY_NONE.
3964 
3965    PK is a primary public key and USER_ID is a user id.
3966 
3967    Returns 0 on success and an error code otherwise.  */
3968 gpg_error_t
tofu_get_policy(ctrl_t ctrl,PKT_public_key * pk,PKT_user_id * user_id,enum tofu_policy * policy)3969 tofu_get_policy (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *user_id,
3970 		 enum tofu_policy *policy)
3971 {
3972   time_t now = gnupg_get_time ();
3973   tofu_dbs_t dbs;
3974   char *fingerprint;
3975   char *email;
3976 
3977   /* Make sure PK is a primary key.  */
3978   log_assert (pk_is_primary (pk));
3979 
3980   dbs = opendbs (ctrl);
3981   if (! dbs)
3982     {
3983       log_error (_("error opening TOFU database: %s\n"),
3984                  gpg_strerror (GPG_ERR_GENERAL));
3985       return gpg_error (GPG_ERR_GENERAL);
3986     }
3987 
3988   fingerprint = hexfingerprint (pk, NULL, 0);
3989   if (!fingerprint)
3990     return gpg_error_from_syserror ();
3991 
3992   email = email_from_user_id (user_id->name);
3993 
3994   *policy = get_policy (ctrl, dbs, pk, fingerprint,
3995                         user_id->name, email, NULL, now);
3996 
3997   xfree (email);
3998   xfree (fingerprint);
3999   if (*policy == _tofu_GET_POLICY_ERROR)
4000     return gpg_error (GPG_ERR_GENERAL);
4001   return 0;
4002 }
4003 
4004 gpg_error_t
tofu_notice_key_changed(ctrl_t ctrl,kbnode_t kb)4005 tofu_notice_key_changed (ctrl_t ctrl, kbnode_t kb)
4006 {
4007   tofu_dbs_t dbs;
4008   PKT_public_key *pk;
4009   char *fingerprint;
4010   char *sqlerr = NULL;
4011   int rc;
4012 
4013   /* Make sure PK is a primary key.  */
4014   setup_main_keyids (kb);
4015   pk = kb->pkt->pkt.public_key;
4016   log_assert (pk_is_primary (pk));
4017 
4018   dbs = opendbs (ctrl);
4019   if (! dbs)
4020     {
4021       log_error (_("error opening TOFU database: %s\n"),
4022                  gpg_strerror (GPG_ERR_GENERAL));
4023       return gpg_error (GPG_ERR_GENERAL);
4024     }
4025 
4026   fingerprint = hexfingerprint (pk, NULL, 0);
4027   if (!fingerprint)
4028     return gpg_error_from_syserror ();
4029 
4030   rc = gpgsql_stepx (dbs->db, NULL, NULL, NULL, &sqlerr,
4031                      "update bindings set effective_policy = ?"
4032                      " where fingerprint = ?;",
4033                      GPGSQL_ARG_INT, (int) TOFU_POLICY_NONE,
4034                      GPGSQL_ARG_STRING, fingerprint,
4035                      GPGSQL_ARG_END);
4036   xfree (fingerprint);
4037 
4038   if (rc == _tofu_GET_POLICY_ERROR)
4039     return gpg_error (GPG_ERR_GENERAL);
4040   return 0;
4041 }
4042