src/pgp_sequoia.c
author Krista 'DarthMama' Bennett <krista@pep.foundation>
Tue, 25 Jun 2019 14:33:14 +0200
branchENGINE-581
changeset 3870 018251280dbf
parent 3869 48fe5cb98a93
child 3871 d1d515455192
child 3885 843f7c599a97
permissions -rw-r--r--
exclusive transaction instead of locking_mode - still not sure it does anything, but...
     1 // This file is under GNU General Public License 3.0
     2 // see LICENSE.txt
     3 
     4 #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
     5 
     6 #define _GNU_SOURCE 1
     7 
     8 #include "platform.h"
     9 #include "pEp_internal.h"
    10 #include "pgp_gpg.h"
    11 
    12 #include <limits.h>
    13 #include <sys/stat.h>
    14 #include <sys/types.h>
    15 
    16 #include "wrappers.h"
    17 
    18 #define TRACING 0
    19 #ifndef TRACING
    20 #  ifndef NDEBUG
    21 #    define TRACING 0
    22 #  else
    23 #    define TRACING 1
    24 #  endif
    25 #endif
    26 
    27 // enable tracing if in debugging mode
    28 #if TRACING
    29 #include "status_to_string.h"
    30 
    31 #  ifdef ANDROID
    32 #    include <android/log.h>
    33 #    define _T(...) do {                                                \
    34         __android_log_print(ANDROID_LOG_DEBUG, "pEpEngine-sequoia",     \
    35                             ##__VA_ARGS__);                             \
    36     } while (0)
    37 #  else
    38 #    define _T(...) do {                        \
    39         fprintf(stderr, ##__VA_ARGS__);         \
    40     } while (0)
    41 #  endif
    42 #else
    43 #  define _T(...) do { } while (0)
    44 #endif
    45 
    46 // Show the start of a tracepoint (i.e., don't print a newline).
    47 #define TC(...) do {       \
    48     _T("%s: ", __func__);  \
    49     _T(__VA_ARGS__);       \
    50 } while (0)
    51 
    52 // Show a trace point.
    53 #  define T(...) do {  \
    54     TC(__VA_ARGS__); \
    55     _T("\n");          \
    56 } while(0)
    57 
    58 // Verbosely displays errors.
    59 #  define DUMP_STATUS(__de_sq_status, __de_pep_status, ...) do { \
    60     TC(__VA_ARGS__);                                            \
    61     _T(": ");                                                   \
    62     if (__de_sq_status) {                                       \
    63         _T("Sequoia: %s => ", pgp_status_to_string(__de_sq_status));   \
    64     }                                                           \
    65     _T("%s\n", pEp_status_to_string(__de_pep_status));          \
    66 } while(0)
    67 
    68 #  define DUMP_ERR(__de_err, __de_status, ...) do {             \
    69     TC(__VA_ARGS__);                                            \
    70     _T(": ");                                                   \
    71     if (__de_err) {                                             \
    72         _T("Sequoia: %s => ", pgp_error_to_string(__de_err));   \
    73         pgp_error_free(__de_err);                               \
    74     }                                                           \
    75     _T("%s\n", pEp_status_to_string(__de_status));              \
    76 } while(0)
    77 
    78 // If __ec_status is an error, then disable the error, set 'status' to
    79 // it, and jump to 'out'.
    80 #define ERROR_OUT(__e_err, __ec_status, ...) do {                   \
    81     PEP_STATUS ___ec_status = (__ec_status);                        \
    82     if ((___ec_status) != PEP_STATUS_OK) {                          \
    83         DUMP_ERR((__e_err), (___ec_status), ##__VA_ARGS__);         \
    84         status = (___ec_status);                                    \
    85         goto out;                                                   \
    86     }                                                               \
    87 } while(0)
    88 
    89 PEP_STATUS pgp_config_cipher_suite(PEP_SESSION session,
    90         PEP_CIPHER_SUITE suite)
    91 {
    92     switch (suite) {
    93         // supported cipher suites
    94         case PEP_CIPHER_SUITE_RSA2K:
    95         case PEP_CIPHER_SUITE_RSA3K:
    96         case PEP_CIPHER_SUITE_CV25519:
    97         case PEP_CIPHER_SUITE_P256:
    98         case PEP_CIPHER_SUITE_P384:
    99         case PEP_CIPHER_SUITE_P521:
   100             session->cipher_suite = suite;
   101             return PEP_STATUS_OK;
   102 
   103         case PEP_CIPHER_SUITE_DEFAULT:
   104             session->cipher_suite = PEP_CIPHER_SUITE_RSA2K;
   105             return PEP_STATUS_OK;
   106 
   107         // unsupported cipher suites
   108         default:
   109             session->cipher_suite = PEP_CIPHER_SUITE_RSA2K;
   110             return PEP_CANNOT_CONFIG;
   111     }
   112 }
   113 
   114 static pgp_tpk_cipher_suite_t cipher_suite(PEP_CIPHER_SUITE suite)
   115 {
   116     switch (suite) {
   117         // supported cipher suites
   118         case PEP_CIPHER_SUITE_RSA2K:
   119             return PGP_TPK_CIPHER_SUITE_RSA2K;
   120         case PEP_CIPHER_SUITE_RSA3K:
   121             return PGP_TPK_CIPHER_SUITE_RSA3K;
   122         case PEP_CIPHER_SUITE_CV25519:
   123             return PGP_TPK_CIPHER_SUITE_CV25519;
   124         case PEP_CIPHER_SUITE_P256:
   125             return PGP_TPK_CIPHER_SUITE_P256;
   126         case PEP_CIPHER_SUITE_P384:
   127             return PGP_TPK_CIPHER_SUITE_P384;
   128         case PEP_CIPHER_SUITE_P521:
   129             return PGP_TPK_CIPHER_SUITE_P521;
   130         default:
   131             return PGP_TPK_CIPHER_SUITE_RSA2K;
   132     }
   133 }
   134 
   135 int email_cmp(void *cookie, int a_len, const void *a, int b_len, const void *b)
   136 {
   137     pgp_packet_t a_userid = pgp_user_id_from_raw (a, a_len);
   138     pgp_packet_t b_userid = pgp_user_id_from_raw (b, b_len);
   139 
   140     T("(%.*s, %.*s)", a_len, (const char *) a, b_len, (const char *) b);
   141 
   142     char *a_address = NULL;
   143     pgp_user_id_address_normalized(NULL, a_userid, &a_address);
   144     if (!a_address)
   145         pgp_user_id_other(NULL, a_userid, &a_address);
   146 
   147     char *b_address = NULL;
   148     pgp_user_id_address_normalized(NULL, b_userid, &b_address);
   149     if (!b_address)
   150         pgp_user_id_other(NULL, b_userid, &b_address);
   151 
   152     pgp_packet_free(a_userid);
   153     pgp_packet_free(b_userid);
   154 
   155     // return an integer that is negative, zero, or positive if the
   156     // first string is less than, equal to, or greater than the
   157     // second, respectively.
   158     int result;
   159     if (!a_address && !b_address)
   160         result = 0;
   161     else if (!a_address)
   162         result = -1;
   163     else if (!b_address)
   164         result = 1;
   165     else
   166         result = strcmp(a_address, b_address);
   167 
   168     if (true) {
   169         T("'%s' %s '%s'",
   170           a_address,
   171           result == 0 ? "==" : result < 0 ? "<" : ">",
   172           b_address);
   173     }
   174 
   175     free(a_address);
   176     free(b_address);
   177 
   178     return result;
   179 }
   180 
   181 PEP_STATUS pgp_init(PEP_SESSION session, bool in_first)
   182 {
   183     PEP_STATUS status = PEP_STATUS_OK;
   184 
   185 #define PEP_KEYS_PATH "/.pEp_keys.db"
   186 
   187     // Create the home directory.
   188     char *home_env = NULL;
   189 #ifndef NDEBUG
   190     home_env = getenv("PEP_HOME");
   191 #endif
   192     if (!home_env)
   193         home_env = getenv("HOME");
   194     if (!home_env)
   195         ERROR_OUT(NULL, PEP_INIT_GPGME_INIT_FAILED, "HOME unset");
   196 
   197     // Create the DB and initialize it.
   198     size_t path_size = strlen(home_env) + sizeof(PEP_KEYS_PATH);
   199     char *path = (char *) calloc(1, path_size);
   200     assert(path);
   201     if (!path)
   202         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   203 
   204     int r = snprintf(path, path_size, "%s" PEP_KEYS_PATH, home_env);
   205     assert(r >= 0 && r < path_size);
   206     if (r < 0)
   207         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "snprintf");
   208 
   209     int sqlite_result;
   210     sqlite_result = sqlite3_open_v2(path,
   211                                     &session->key_db,
   212                                     SQLITE_OPEN_READWRITE
   213                                     | SQLITE_OPEN_CREATE
   214                                     | SQLITE_OPEN_FULLMUTEX
   215                                     | SQLITE_OPEN_PRIVATECACHE,
   216                                     NULL);
   217     free(path);
   218     if (sqlite_result != SQLITE_OK)
   219         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   220                   "opening keys DB: %s", sqlite3_errmsg(session->key_db));
   221 
   222     sqlite3_busy_timeout(session->key_db, BUSY_WAIT_TIME);
   223 
   224     sqlite_result = sqlite3_exec(session->key_db,
   225                                  "PRAGMA secure_delete=true;\n"
   226                                  "PRAGMA foreign_keys=true;\n"
   227                                  "PRAGMA locking_mode=NORMAL;\n"
   228                                  "PRAGMA journal_mode=WAL;\n",
   229                                  NULL, NULL, NULL);
   230     if (sqlite_result != SQLITE_OK)
   231         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   232                   "setting pragmas: %s", sqlite3_errmsg(session->key_db));
   233 
   234     sqlite3_busy_timeout(session->key_db, BUSY_WAIT_TIME);
   235 
   236     sqlite_result =
   237         sqlite3_create_collation(session->key_db,
   238                                 "EMAIL",
   239                                 SQLITE_UTF8,
   240                                 /* pArg (cookie) */ NULL,
   241                                 email_cmp);
   242     if (sqlite_result != SQLITE_OK)
   243         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   244                   "registering EMAIL collation function: %s",
   245                   sqlite3_errmsg(session->key_db));
   246 
   247     sqlite_result = sqlite3_exec(session->key_db,
   248                                  "CREATE TABLE IF NOT EXISTS keys (\n"
   249                                  "   primary_key TEXT UNIQUE PRIMARY KEY,\n"
   250                                  "   secret BOOLEAN,\n"
   251                                  "   tpk BLOB\n"
   252                                  ");\n"
   253                                  "CREATE INDEX IF NOT EXISTS keys_index\n"
   254                                  "  ON keys (primary_key, secret)\n",
   255                                  NULL, NULL, NULL);
   256     if (sqlite_result != SQLITE_OK)
   257         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   258                   "creating keys table: %s",
   259                   sqlite3_errmsg(session->key_db));
   260 
   261     sqlite_result = sqlite3_exec(session->key_db,
   262                                  "CREATE TABLE IF NOT EXISTS subkeys (\n"
   263                                  "   subkey TEXT NOT NULL,\n"
   264                                  "   primary_key TEXT NOT NULL,\n"
   265                                  "   UNIQUE(subkey, primary_key),\n"
   266                                  "   FOREIGN KEY (primary_key)\n"
   267                                  "       REFERENCES keys(primary_key)\n"
   268                                  "     ON DELETE CASCADE\n"
   269                                  ");\n"
   270                                  "CREATE INDEX IF NOT EXISTS subkeys_index\n"
   271                                  "  ON subkeys (subkey, primary_key)\n",
   272                                  NULL, NULL, NULL);
   273     if (sqlite_result != SQLITE_OK)
   274         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   275                   "creating subkeys table: %s",
   276                   sqlite3_errmsg(session->key_db));
   277 
   278     sqlite_result = sqlite3_exec(session->key_db,
   279                                  "CREATE TABLE IF NOT EXISTS userids (\n"
   280                                  "   userid TEXT NOT NULL COLLATE EMAIL,\n"
   281                                  "   primary_key TEXT NOT NULL,\n"
   282                                  "   UNIQUE(userid, primary_key),\n"
   283                                  "   FOREIGN KEY (primary_key)\n"
   284                                  "       REFERENCES keys(primary_key)\n"
   285                                  "     ON DELETE CASCADE\n"
   286                                  ");\n"
   287                                  "CREATE INDEX IF NOT EXISTS userids_index\n"
   288                                  "  ON userids (userid COLLATE EMAIL, primary_key)\n",
   289                                  NULL, NULL, NULL);
   290     if (sqlite_result != SQLITE_OK)
   291         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   292                   "creating userids table: %s",
   293                   sqlite3_errmsg(session->key_db));
   294 
   295     sqlite_result
   296         = sqlite3_prepare_v2(session->key_db, "begin transaction",
   297                              -1, &session->sq_sql.begin_transaction, NULL);
   298     assert(sqlite_result == SQLITE_OK);
   299 
   300     sqlite_result
   301         = sqlite3_prepare_v2(session->key_db, "begin transaction exclusive",
   302                              -1, &session->sq_sql.begin_transaction_excl, NULL);
   303     assert(sqlite_result == SQLITE_OK);
   304 
   305     sqlite_result
   306         = sqlite3_prepare_v2(session->key_db, "commit transaction",
   307                              -1, &session->sq_sql.commit_transaction, NULL);
   308     assert(sqlite_result == SQLITE_OK);
   309 
   310     sqlite_result
   311         = sqlite3_prepare_v2(session->key_db, "rollback transaction",
   312                              -1, &session->sq_sql.rollback_transaction, NULL);
   313     assert(sqlite_result == SQLITE_OK);
   314 
   315     sqlite_result
   316         = sqlite3_prepare_v2(session->key_db,
   317                              "SELECT tpk, secret FROM keys"
   318                              " WHERE primary_key == ?",
   319                              -1, &session->sq_sql.tpk_find, NULL);
   320     assert(sqlite_result == SQLITE_OK);
   321 
   322     sqlite_result
   323         = sqlite3_prepare_v2(session->key_db,
   324                              "SELECT tpk, secret FROM keys"
   325                              " WHERE primary_key == ? and secret == 1",
   326                              -1, &session->sq_sql.tsk_find, NULL);
   327     assert(sqlite_result == SQLITE_OK);
   328 
   329     sqlite_result
   330         = sqlite3_prepare_v2(session->key_db,
   331                              "SELECT tpk, secret FROM subkeys"
   332                              " LEFT JOIN keys"
   333                              "  ON subkeys.primary_key == keys.primary_key"
   334                              " WHERE subkey == ?",
   335                              -1, &session->sq_sql.tpk_find_by_keyid, NULL);
   336     assert(sqlite_result == SQLITE_OK);
   337 
   338     sqlite_result
   339         = sqlite3_prepare_v2(session->key_db,
   340                              "SELECT tpk, secret FROM subkeys"
   341                              " LEFT JOIN keys"
   342                              "  ON subkeys.primary_key == keys.primary_key"
   343                              " WHERE subkey == ?",
   344                              -1, &session->sq_sql.tpk_find_by_keyid, NULL);
   345     assert(sqlite_result == SQLITE_OK);
   346 
   347     sqlite_result
   348         = sqlite3_prepare_v2(session->key_db,
   349                              "SELECT tpk, secret FROM subkeys"
   350                              " LEFT JOIN keys"
   351                              "  ON subkeys.primary_key == keys.primary_key"
   352                              " WHERE subkey == ? and keys.secret == 1",
   353                              -1, &session->sq_sql.tsk_find_by_keyid, NULL);
   354     assert(sqlite_result == SQLITE_OK);
   355 
   356     sqlite_result
   357         = sqlite3_prepare_v2(session->key_db,
   358                              "SELECT tpk, secret FROM userids"
   359                              " LEFT JOIN keys"
   360                              "  ON userids.primary_key == keys.primary_key"
   361                              " WHERE userid == ?",
   362                              -1, &session->sq_sql.tpk_find_by_email, NULL);
   363     assert(sqlite_result == SQLITE_OK);
   364 
   365     sqlite_result
   366         = sqlite3_prepare_v2(session->key_db,
   367                              "SELECT tpk, secret FROM userids"
   368                              " LEFT JOIN keys"
   369                              "  ON userids.primary_key == keys.primary_key"
   370                              " WHERE userid == ? and keys.secret == 1",
   371                              -1, &session->sq_sql.tsk_find_by_email, NULL);
   372     assert(sqlite_result == SQLITE_OK);
   373 
   374     sqlite_result
   375         = sqlite3_prepare_v2(session->key_db,
   376                              "select tpk, secret from keys",
   377                              -1, &session->sq_sql.tpk_all, NULL);
   378     assert(sqlite_result == SQLITE_OK);
   379 
   380     sqlite_result
   381         = sqlite3_prepare_v2(session->key_db,
   382                              "select tpk, secret from keys where secret = 1",
   383                              -1, &session->sq_sql.tsk_all, NULL);
   384     assert(sqlite_result == SQLITE_OK);
   385 
   386     sqlite_result
   387         = sqlite3_prepare_v2(session->key_db,
   388                              "INSERT OR REPLACE INTO keys"
   389                              "   (primary_key, secret, tpk)"
   390                              " VALUES (?, ?, ?)",
   391                              -1, &session->sq_sql.tpk_save_insert_primary, NULL);
   392     assert(sqlite_result == SQLITE_OK);
   393 
   394     sqlite_result
   395         = sqlite3_prepare_v2(session->key_db,
   396                              "INSERT OR REPLACE INTO subkeys"
   397                              "   (subkey, primary_key)"
   398                              " VALUES (?, ?)",
   399                              -1, &session->sq_sql.tpk_save_insert_subkeys, NULL);
   400     assert(sqlite_result == SQLITE_OK);
   401 
   402     sqlite_result
   403         = sqlite3_prepare_v2(session->key_db,
   404                              "INSERT OR REPLACE INTO userids"
   405                              "   (userid, primary_key)"
   406                              " VALUES (?, ?)",
   407                              -1, &session->sq_sql.tpk_save_insert_userids, NULL);
   408     assert(sqlite_result == SQLITE_OK);
   409 
   410     sqlite_result
   411         = sqlite3_prepare_v2(session->key_db,
   412                              "DELETE FROM keys WHERE primary_key = ?",
   413                              -1, &session->sq_sql.delete_keypair, NULL);
   414     assert(sqlite_result == SQLITE_OK);
   415 
   416  out:
   417     if (status != PEP_STATUS_OK)
   418         pgp_release(session, in_first);
   419     return status;
   420 }
   421 
   422 void pgp_release(PEP_SESSION session, bool out_last)
   423 {
   424     sqlite3_stmt **stmts = (sqlite3_stmt **) &session->sq_sql;
   425     for (int i = 0; i < sizeof(session->sq_sql) / sizeof(*stmts); i ++)
   426         if (stmts[i]) {
   427             sqlite3_finalize(stmts[i]);
   428             stmts[i] = NULL;
   429         }
   430 
   431     if (session->key_db) {
   432         int result = sqlite3_close_v2(session->key_db);
   433         if (result != 0)
   434             DUMP_ERR(NULL, PEP_UNKNOWN_ERROR,
   435                      "Closing key DB: sqlite3_close_v2: %s",
   436                      sqlite3_errstr(result));
   437         session->key_db = NULL;
   438     }
   439 }
   440 
   441 // Ensures that a fingerprint is in canonical form.  A canonical
   442 // fingerprint doesn't contain any white space.
   443 //
   444 // This function does *not* consume fpr.
   445 static char *pgp_fingerprint_canonicalize(const char *) __attribute__((nonnull));
   446 static char *pgp_fingerprint_canonicalize(const char *fpr)
   447 {
   448     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
   449     char *fpr_canonicalized = pgp_fingerprint_to_hex(pgp_fpr);
   450     pgp_fingerprint_free(pgp_fpr);
   451 
   452     return fpr_canonicalized;
   453 }
   454 
   455 // step statement and load the tpk and secret.
   456 static PEP_STATUS key_load(PEP_SESSION, sqlite3_stmt *, pgp_tpk_t *, int *)
   457     __attribute__((nonnull(1, 2)));
   458 static PEP_STATUS key_load(PEP_SESSION session, sqlite3_stmt *stmt,
   459                            pgp_tpk_t *tpkp, int *secretp)
   460 {
   461     PEP_STATUS status = PEP_STATUS_OK;
   462     int sqlite_result = Sqlite3_step(stmt);
   463     switch (sqlite_result) {
   464     case SQLITE_ROW:
   465         if (tpkp) {
   466             int data_len = sqlite3_column_bytes(stmt, 0);
   467             const void *data = sqlite3_column_blob(stmt, 0);
   468 
   469             pgp_error_t err = NULL;
   470             *tpkp = pgp_tpk_from_bytes(&err, data, data_len);
   471             if (!*tpkp)
   472                 ERROR_OUT(err, PEP_GET_KEY_FAILED, "parsing TPK");
   473         }
   474 
   475         if (secretp)
   476             *secretp = sqlite3_column_int(stmt, 1);
   477 
   478         break;
   479     case SQLITE_DONE:
   480         // Got nothing.
   481         status = PEP_KEY_NOT_FOUND;
   482         break;
   483     default:
   484         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   485                   "stepping: %s", sqlite3_errmsg(session->key_db));
   486     }
   487 
   488  out:
   489     T(" -> %s", pEp_status_to_string(status));
   490     return status;
   491 }
   492 
   493 // step statement until exhausted and load the tpks.
   494 static PEP_STATUS key_loadn(PEP_SESSION, sqlite3_stmt *, pgp_tpk_t **, int *)
   495     __attribute__((nonnull));
   496 static PEP_STATUS key_loadn(PEP_SESSION session, sqlite3_stmt *stmt,
   497                             pgp_tpk_t **tpksp, int *tpks_countp)
   498 {
   499     PEP_STATUS status = PEP_STATUS_OK;
   500     int tpks_count = 0;
   501     int tpks_capacity = 8;
   502     pgp_tpk_t *tpks = calloc(tpks_capacity, sizeof(pgp_tpk_t));
   503     if (!tpks)
   504         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   505 
   506     for (;;) {
   507         pgp_tpk_t tpk = NULL;
   508         status = key_load(session, stmt, &tpk, NULL);
   509         if (status == PEP_KEY_NOT_FOUND) {
   510             status = PEP_STATUS_OK;
   511             break;
   512         }
   513         ERROR_OUT(NULL, status, "loading TPK");
   514 
   515         if (tpks_count == tpks_capacity) {
   516             tpks_capacity *= 2;
   517             tpks = realloc(tpks, sizeof(tpks[0]) * tpks_capacity);
   518             if (!tpks)
   519                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "tpks");
   520         }
   521         tpks[tpks_count ++] = tpk;
   522     }
   523 
   524  out:
   525     if (status != PEP_STATUS_OK) {
   526         for (int i = 0; i < tpks_count; i ++)
   527             pgp_tpk_free(tpks[i]);
   528         free(tpks);
   529     } else {
   530         *tpksp = tpks;
   531         *tpks_countp = tpks_count;
   532     }
   533 
   534     T(" -> %s (%d tpks)", pEp_status_to_string(status), *tpks_countp);
   535     return status;
   536 }
   537 
   538 // Returns the TPK identified by the provided fingerprint.
   539 //
   540 // This function only matches on the primary key!
   541 static PEP_STATUS tpk_find(PEP_SESSION, pgp_fingerprint_t, int, pgp_tpk_t *, int *)
   542     __attribute__((nonnull(1, 2)));
   543 static PEP_STATUS tpk_find(PEP_SESSION session,
   544                            pgp_fingerprint_t fpr, int private_only,
   545                            pgp_tpk_t *tpk, int *secret)
   546 {
   547     PEP_STATUS status = PEP_STATUS_OK;
   548     char *fpr_str = pgp_fingerprint_to_hex(fpr);
   549 
   550     T("(%s, %d)", fpr_str, private_only);
   551 
   552     sqlite3_stmt *stmt
   553         = private_only ? session->sq_sql.tsk_find : session->sq_sql.tpk_find;
   554     sqlite3_bind_text(stmt, 1, fpr_str, -1, SQLITE_STATIC);
   555 
   556     status = key_load(session, stmt, tpk, secret);
   557     ERROR_OUT(NULL, status, "Looking up %s", fpr_str);
   558 
   559  out:
   560     sqlite3_reset(stmt);
   561     T("(%s, %d) -> %s", fpr_str, private_only, pEp_status_to_string(status));
   562     free(fpr_str);
   563     return status;
   564 }
   565 
   566 // Returns the TPK identified by the provided keyid.
   567 //
   568 // This function matches on both primary keys and subkeys!
   569 //
   570 // Note: There can be multiple TPKs for a given keyid.  This can
   571 // occur, because an encryption subkey can be bound to multiple TPKs.
   572 // Also, it is possible to collide key ids.  If there are multiple key
   573 // ids for a given key, this just returns one of them.
   574 //
   575 // If private_only is set, this will only consider TPKs with some
   576 // secret key material.
   577 static PEP_STATUS tpk_find_by_keyid_hex(PEP_SESSION, const char *, int, pgp_tpk_t *, int *)
   578   __attribute__((nonnull(1, 2)));
   579 static PEP_STATUS tpk_find_by_keyid_hex(
   580         PEP_SESSION session, const char *keyid_hex, int private_only,
   581         pgp_tpk_t *tpkp, int *secretp)
   582 {
   583     PEP_STATUS status = PEP_STATUS_OK;
   584     T("(%s, %d)", keyid_hex, private_only);
   585 
   586     sqlite3_stmt *stmt
   587         = private_only ? session->sq_sql.tsk_find_by_keyid : session->sq_sql.tpk_find_by_keyid;
   588     sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   589 
   590     status = key_load(session, stmt, tpkp, secretp);
   591     ERROR_OUT(NULL, status, "Looking up %s", keyid_hex);
   592 
   593  out:
   594     sqlite3_reset(stmt);
   595     T("(%s, %d) -> %s", keyid_hex, private_only, pEp_status_to_string(status));
   596     return status;
   597 }
   598 
   599 // See tpk_find_by_keyid_hex.
   600 PEP_STATUS tpk_find_by_keyid(PEP_SESSION, pgp_keyid_t, int, pgp_tpk_t *, int *)
   601     __attribute__((nonnull(1, 2)));
   602 PEP_STATUS tpk_find_by_keyid(PEP_SESSION session,
   603                              pgp_keyid_t keyid, int private_only,
   604                              pgp_tpk_t *tpkp, int *secretp)
   605 {
   606     char *keyid_hex = pgp_keyid_to_hex(keyid);
   607     if (! keyid_hex)
   608         return PEP_OUT_OF_MEMORY;
   609     PEP_STATUS status
   610         = tpk_find_by_keyid_hex(session, keyid_hex, private_only, tpkp, secretp);
   611     free(keyid_hex);
   612     return status;
   613 }
   614 
   615 // See tpk_find_by_keyid_hex.
   616 static PEP_STATUS tpk_find_by_fpr(PEP_SESSION, pgp_fingerprint_t, int,
   617                                   pgp_tpk_t *, int *)
   618     __attribute__((nonnull(1, 2)));
   619 static PEP_STATUS tpk_find_by_fpr(
   620     PEP_SESSION session, pgp_fingerprint_t fpr, int private_only,
   621     pgp_tpk_t *tpkp, int *secretp)
   622 {
   623     pgp_keyid_t keyid = pgp_fingerprint_to_keyid(fpr);
   624     if (! keyid)
   625         return PEP_OUT_OF_MEMORY;
   626     PEP_STATUS status
   627         = tpk_find_by_keyid(session, keyid, private_only, tpkp, secretp);
   628     pgp_keyid_free(keyid);
   629     return status;
   630 }
   631 
   632 // See tpk_find_by_keyid_hex.
   633 static PEP_STATUS tpk_find_by_fpr_hex(PEP_SESSION, const char *, int, pgp_tpk_t *, int *secret)
   634     __attribute__((nonnull(1, 2)));
   635 static PEP_STATUS tpk_find_by_fpr_hex(
   636     PEP_SESSION session, const char *fpr, int private_only,
   637     pgp_tpk_t *tpkp, int *secretp)
   638 {
   639     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
   640     if (! pgp_fpr)
   641         return PEP_OUT_OF_MEMORY;
   642     PEP_STATUS status
   643         = tpk_find_by_fpr(session, pgp_fpr, private_only, tpkp, secretp);
   644     pgp_fingerprint_free(pgp_fpr);
   645     return status;
   646 }
   647 
   648 // Returns all known TPKs.
   649 static PEP_STATUS tpk_all(PEP_SESSION, int, pgp_tpk_t **, int *) __attribute__((nonnull));
   650 static PEP_STATUS tpk_all(PEP_SESSION session, int private_only,
   651                           pgp_tpk_t **tpksp, int *tpks_countp) {
   652     PEP_STATUS status = PEP_STATUS_OK;
   653     sqlite3_stmt *stmt = private_only ? session->sq_sql.tsk_all : session->sq_sql.tpk_all;
   654     status = key_loadn(session, stmt, tpksp, tpks_countp);
   655     ERROR_OUT(NULL, status, "loading TPKs");
   656  out:
   657     sqlite3_reset(stmt);
   658     return status;
   659 }
   660 
   661 // Returns keys that have a user id that matches the specified pattern.
   662 //
   663 // The keys returned must be freed using pgp_tpk_free.
   664 static PEP_STATUS tpk_find_by_email(PEP_SESSION, const char *, int, pgp_tpk_t **, int *)
   665     __attribute__((nonnull));
   666 static PEP_STATUS tpk_find_by_email(PEP_SESSION session,
   667                                     const char *pattern, int private_only,
   668                                     pgp_tpk_t **tpksp, int *countp)
   669 {
   670     PEP_STATUS status = PEP_STATUS_OK;
   671     T("(%s)", pattern);
   672 
   673     sqlite3_stmt *stmt
   674         = private_only ? session->sq_sql.tsk_find_by_email : session->sq_sql.tpk_find_by_email;
   675     sqlite3_bind_text(stmt, 1, pattern, -1, SQLITE_STATIC);
   676 
   677     status = key_loadn(session, stmt, tpksp, countp);
   678     ERROR_OUT(NULL, status, "Searching for '%s'", pattern);
   679 
   680  out:
   681     sqlite3_reset(stmt);
   682     T("(%s) -> %s (%d results)", pattern, pEp_status_to_string(status), *countp);
   683     return status;
   684 }
   685 
   686 
   687 // Saves the specified TPK.
   688 //
   689 // This function takes ownership of TPK.
   690 static PEP_STATUS tpk_save(PEP_SESSION, pgp_tpk_t, identity_list **)
   691     __attribute__((nonnull(1, 2)));
   692 static PEP_STATUS tpk_save(PEP_SESSION session, pgp_tpk_t tpk,
   693                            identity_list **private_idents)
   694 {
   695     PEP_STATUS status = PEP_STATUS_OK;
   696     pgp_error_t err = NULL;
   697     pgp_fingerprint_t pgp_fpr = NULL;
   698     char *fpr = NULL;
   699     void *tsk_buffer = NULL;
   700     size_t tsk_buffer_len = 0;
   701     int tried_commit = 0;
   702     pgp_tpk_key_iter_t key_iter = NULL;
   703     pgp_user_id_binding_iter_t user_id_iter = NULL;
   704     char *email = NULL;
   705     char *name = NULL;
   706 
   707     sqlite3_stmt *stmt = session->sq_sql.begin_transaction_excl;
   708     int sqlite_result = Sqlite3_step(stmt);
   709     sqlite3_reset(stmt);
   710     if (sqlite_result != SQLITE_DONE)
   711         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   712                   "begin transaction failed: %s",
   713                   sqlite3_errmsg(session->key_db));
   714 
   715     pgp_fpr = pgp_tpk_fingerprint(tpk);
   716     fpr = pgp_fingerprint_to_hex(pgp_fpr);
   717     T("(%s, private_idents: %s)", fpr, private_idents ? "yes" : "no");
   718 
   719     // Merge any existing data into TPK.
   720     pgp_tpk_t current = NULL;
   721     status = tpk_find(session, pgp_fpr, false, &current, NULL);
   722     if (status == PEP_KEY_NOT_FOUND)
   723         status = PEP_STATUS_OK;
   724     else
   725         ERROR_OUT(NULL, status, "Looking up %s", fpr);
   726     if (current) {
   727         tpk = pgp_tpk_merge(&err, tpk, current);
   728         if (! tpk)
   729             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Merging TPKs");
   730     }
   731 
   732     int is_tsk = pgp_tpk_is_tsk(tpk);
   733 
   734     // Serialize it.
   735     pgp_writer_t writer = pgp_writer_alloc(&tsk_buffer, &tsk_buffer_len);
   736     if (! writer)
   737         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   738 
   739     pgp_status_t pgp_status;
   740     pgp_tsk_t tsk = pgp_tpk_as_tsk(tpk);
   741     pgp_status = pgp_tsk_serialize(&err, tsk, writer);
   742     pgp_tsk_free(tsk);
   743     //pgp_writer_free(writer);
   744     if (pgp_status != 0)
   745         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Serializing TPK");
   746 
   747 
   748     // Insert the TSK into the DB.
   749     stmt = session->sq_sql.tpk_save_insert_primary;
   750     sqlite3_bind_text(stmt, 1, fpr, -1, SQLITE_STATIC);
   751     sqlite3_bind_int(stmt, 2, is_tsk);
   752     sqlite3_bind_blob(stmt, 3, tsk_buffer, tsk_buffer_len, SQLITE_STATIC);
   753 
   754     sqlite_result = Sqlite3_step(stmt);
   755     sqlite3_reset(stmt);
   756     if (sqlite_result != SQLITE_DONE)
   757         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   758                   "Saving TPK: %s", sqlite3_errmsg(session->key_db));
   759 
   760     // Insert the "subkeys" (the primary key and the subkeys).
   761     stmt = session->sq_sql.tpk_save_insert_subkeys;
   762     // This inserts all of the keys in the TPK, i.e., revoked and
   763     // expired keys, which is what we want.
   764     key_iter = pgp_tpk_key_iter_all(tpk);
   765     pgp_key_t key;
   766     while ((key = pgp_tpk_key_iter_next(key_iter, NULL, NULL))) {
   767         pgp_keyid_t keyid = pgp_key_keyid(key);
   768         char *keyid_hex = pgp_keyid_to_hex(keyid);
   769         sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   770         sqlite3_bind_text(stmt, 2, fpr, -1, SQLITE_STATIC);
   771 
   772         sqlite_result = Sqlite3_step(stmt);
   773         sqlite3_reset(stmt);
   774         free(keyid_hex);
   775         pgp_keyid_free(keyid);
   776         if (sqlite_result != SQLITE_DONE) {
   777             pgp_tpk_key_iter_free(key_iter);
   778             ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   779                       "Updating subkeys: %s", sqlite3_errmsg(session->key_db));
   780         }
   781     }
   782     pgp_tpk_key_iter_free(key_iter);
   783     key_iter = NULL;
   784 
   785     // Insert the "userids".
   786     stmt = session->sq_sql.tpk_save_insert_userids;
   787     user_id_iter = pgp_tpk_user_id_binding_iter(tpk);
   788     pgp_user_id_binding_t binding;
   789     int first = 1;
   790     while ((binding = pgp_user_id_binding_iter_next(user_id_iter))) {
   791         char *user_id_value = pgp_user_id_binding_user_id(binding);
   792         if (!user_id_value || !*user_id_value)
   793             continue;
   794 
   795         // Ignore bindings with a self-revocation certificate, but no
   796         // self-signature.
   797         if (!pgp_user_id_binding_selfsig(binding)) {
   798             free(user_id_value);
   799             continue;
   800         }
   801 
   802         free(name);
   803         name = NULL;
   804         free(email);
   805         email = NULL;
   806 
   807         pgp_packet_t userid = pgp_user_id_new (user_id_value);
   808         pgp_user_id_name(NULL, userid, &name);
   809         pgp_user_id_address_or_other(NULL, userid, &email);
   810         pgp_packet_free(userid);
   811         free(user_id_value);
   812 
   813         if (email) {
   814             T("  userid: %s", email);
   815 
   816             sqlite3_bind_text(stmt, 1, email, -1, SQLITE_STATIC);
   817             sqlite3_bind_text(stmt, 2, fpr, -1, SQLITE_STATIC);
   818 
   819             sqlite_result = Sqlite3_step(stmt);
   820             sqlite3_reset(stmt);
   821 
   822             if (sqlite_result != SQLITE_DONE) {
   823                 pgp_user_id_binding_iter_free(user_id_iter);
   824                 ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   825                           "Updating userids: %s", sqlite3_errmsg(session->key_db));
   826             }
   827         }
   828 
   829         if (first && private_idents && is_tsk) {
   830             first = 0;
   831 
   832             // Create an identity for the primary user id.
   833             pEp_identity *ident = new_identity(email, fpr, NULL, name);
   834             if (ident == NULL)
   835                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_identity");
   836 
   837             *private_idents = identity_list_add(*private_idents, ident);
   838             if (*private_idents == NULL)
   839                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "identity_list_add");
   840         }
   841 
   842     }
   843     pgp_user_id_binding_iter_free(user_id_iter);
   844     user_id_iter = NULL;
   845 
   846  out:
   847     // Prevent ERROR_OUT from causing an infinite loop.
   848     if (! tried_commit) {
   849         tried_commit = 1;
   850         stmt = status == PEP_STATUS_OK
   851             ? session->sq_sql.commit_transaction
   852             : session->sq_sql.rollback_transaction;
   853         int sqlite_result = Sqlite3_step(stmt);
   854         sqlite3_reset(stmt);
   855         if (sqlite_result != SQLITE_DONE)
   856             ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   857                       status == PEP_STATUS_OK
   858                       ? "commit failed: %s" : "rollback failed: %s",
   859                       sqlite3_errmsg(session->key_db));
   860     }
   861 
   862 
   863     T("(%s) -> %s", fpr, pEp_status_to_string(status));
   864 
   865     free(email);
   866     free(name);
   867     pgp_user_id_binding_iter_free(user_id_iter);
   868     pgp_tpk_key_iter_free(key_iter);
   869     if (stmt)
   870       sqlite3_reset(stmt);
   871     free(tsk_buffer);
   872     pgp_tpk_free(tpk);
   873     free(fpr);
   874     pgp_fingerprint_free(pgp_fpr);
   875 
   876     return status;
   877 }
   878 
   879 struct decrypt_cookie {
   880     PEP_SESSION session;
   881     int get_secret_keys_called;
   882     stringlist_t *recipient_keylist;
   883     stringlist_t *signer_keylist;
   884     int good_checksums;
   885     int good_but_expired;
   886     int good_but_revoked;
   887     int missing_keys;
   888     int bad_checksums;
   889 
   890     // Whether we decrypted anything.
   891     int decrypted;
   892 
   893     // The filename stored in the literal data packet.  Note: this is
   894     // *not* protected by the signature and should not be trusted!!!
   895     char *filename;
   896 };
   897 
   898 static pgp_status_t
   899 get_public_keys_cb(void *cookie_raw,
   900                    pgp_keyid_t *keyids, size_t keyids_len,
   901                    pgp_tpk_t **tpks, size_t *tpk_len,
   902                    void (**our_free)(void *))
   903 {
   904     struct decrypt_cookie *cookie = cookie_raw;
   905     PEP_SESSION session = cookie->session;
   906 
   907     *tpks = calloc(keyids_len, sizeof(*tpks));
   908     if (!*tpks)
   909         return PGP_STATUS_UNKNOWN_ERROR;
   910     *our_free = free;
   911 
   912     int i, j;
   913     j = 0;
   914     for (i = 0; i < keyids_len; i ++) {
   915         pgp_tpk_t tpk = NULL;
   916         PEP_STATUS status
   917             = tpk_find_by_keyid(session, keyids[i], false, &tpk, NULL);
   918         if (status == PEP_STATUS_OK)
   919             (*tpks)[j ++] = tpk;
   920     }
   921     *tpk_len = j;
   922     return PGP_STATUS_SUCCESS;
   923 }
   924 
   925 static pgp_status_t
   926 decrypt_cb(void *cookie_opaque,
   927            pgp_pkesk_t *pkesks, size_t pkesk_count,
   928            pgp_skesk_t *skesks, size_t skesk_count,
   929            pgp_decryptor_do_decrypt_cb_t *decrypt,
   930            void *decrypt_cookie,
   931            pgp_fingerprint_t *identity_out)
   932 {
   933     pgp_error_t err = NULL;
   934     struct decrypt_cookie *cookie = cookie_opaque;
   935     PEP_SESSION session = cookie->session;
   936     pgp_tpk_t *tsks = NULL;
   937     int tsks_count = 0;
   938     int wildcards = 0;
   939 
   940     if (cookie->get_secret_keys_called)
   941         // Prevent iterations, which isn't needed since we don't
   942         // support SKESKs.
   943         return PGP_STATUS_UNKNOWN_ERROR;
   944     cookie->get_secret_keys_called = 1;
   945 
   946     T("%zd PKESKs", pkesk_count);
   947 
   948     for (int i = 0; i < pkesk_count; i ++) {
   949         pgp_pkesk_t pkesk = pkesks[i];
   950         pgp_keyid_t keyid = pgp_pkesk_recipient(pkesk); /* Reference. */
   951         char *keyid_str = pgp_keyid_to_hex(keyid);
   952         pgp_tpk_key_iter_t key_iter = NULL;
   953         pgp_session_key_t sk = NULL;
   954 
   955         T("Considering PKESK for %s", keyid_str);
   956 
   957         if (strcmp(keyid_str, "0000000000000000") == 0) {
   958             // Initially ignore wildcards.
   959             wildcards = 1;
   960             goto eol;
   961         }
   962 
   963         // Collect the recipients.  Note: we must return the primary
   964         // key's fingerprint.
   965         pgp_tpk_t tpk = NULL;
   966         int is_tsk = 0;
   967         if (tpk_find_by_keyid(session, keyid, false, &tpk, &is_tsk) != PEP_STATUS_OK)
   968             goto eol;
   969 
   970         pgp_fingerprint_t fp = pgp_tpk_fingerprint(tpk);
   971         char *fp_string = pgp_fingerprint_to_hex(fp);
   972         stringlist_add_unique(cookie->recipient_keylist, fp_string);
   973         free(fp_string);
   974         pgp_fingerprint_free(fp);
   975 
   976         if (cookie->decrypted)
   977             goto eol;
   978 
   979         // See if we have the secret key.
   980         assert(is_tsk == pgp_tpk_is_tsk(tpk));
   981         if (! is_tsk)
   982             goto eol;
   983 
   984         key_iter = pgp_tpk_key_iter_all(tpk);
   985         pgp_key_t key;
   986         while ((key = pgp_tpk_key_iter_next(key_iter, NULL, NULL))) {
   987             pgp_keyid_t this_keyid = pgp_key_keyid(key);
   988             char *this_keyid_hex = pgp_keyid_to_hex(this_keyid);
   989             pgp_keyid_free(this_keyid);
   990 
   991             int match = strcmp(keyid_str, this_keyid_hex) == 0;
   992             free(this_keyid_hex);
   993             if (match)
   994                 break;
   995         }
   996 
   997         if (key == NULL) {
   998             assert(!"Inconsistent DB: key doesn't contain a subkey with keyid!");
   999             goto eol;
  1000         }
  1001 
  1002         uint8_t algo;
  1003         uint8_t session_key[1024];
  1004         size_t session_key_len = sizeof(session_key);
  1005         if (pgp_pkesk_decrypt(&err, pkesk, key, &algo,
  1006                               session_key, &session_key_len) != 0) {
  1007             DUMP_ERR(err, PEP_UNKNOWN_ERROR, "pgp_pkesk_decrypt");
  1008             goto eol;
  1009         }
  1010 
  1011         sk = pgp_session_key_from_bytes (session_key, session_key_len);
  1012         pgp_status_t status;
  1013         if ((status = decrypt (decrypt_cookie, algo, sk))) {
  1014             DUMP_STATUS(status, PEP_UNKNOWN_ERROR, "decrypt_cb");
  1015             goto eol;
  1016         }
  1017 
  1018         T("Decrypted PKESK for %s", keyid_str);
  1019 
  1020         *identity_out = pgp_tpk_fingerprint(tpk);
  1021         cookie->decrypted = 1;
  1022 
  1023     eol:
  1024         pgp_session_key_free (sk);
  1025         free(keyid_str);
  1026         pgp_tpk_key_iter_free(key_iter);
  1027         pgp_tpk_free(tpk);
  1028     }
  1029 
  1030     // Consider wildcard recipients.
  1031     if (wildcards) for (int i = 0; i < pkesk_count && !cookie->decrypted; i ++) {
  1032         pgp_pkesk_t pkesk = pkesks[i];
  1033         pgp_keyid_t keyid = pgp_pkesk_recipient(pkesk); /* Reference. */
  1034         char *keyid_str = pgp_keyid_to_hex(keyid);
  1035         pgp_tpk_key_iter_t key_iter = NULL;
  1036         pgp_session_key_t sk = NULL;
  1037 
  1038         if (strcmp(keyid_str, "0000000000000000") != 0)
  1039             goto eol2;
  1040 
  1041         if (!tsks) {
  1042             if (tpk_all(session, true, &tsks, &tsks_count) != PEP_STATUS_OK) {
  1043                 DUMP_ERR(NULL, PEP_UNKNOWN_ERROR, "Getting all tsks");
  1044             }
  1045         }
  1046 
  1047         for (int j = 0; j < tsks_count; j ++) {
  1048             pgp_tpk_t tsk = tsks[j];
  1049 
  1050             key_iter = pgp_tpk_key_iter_all(tsk);
  1051             pgp_key_t key;
  1052             pgp_signature_t selfsig;
  1053             while ((key = pgp_tpk_key_iter_next(key_iter, &selfsig, NULL))) {
  1054                 if (! (pgp_signature_can_encrypt_at_rest(selfsig)
  1055                        || pgp_signature_can_encrypt_for_transport(selfsig)))
  1056                     continue;
  1057 
  1058                 fprintf(stderr, "key: %s\n", pgp_key_debug(key));
  1059 
  1060                 // Note: for decryption to appear to succeed, we must
  1061                 // get a valid algorithm (8 of 256 values) and a
  1062                 // 16-bit checksum must match.  Thus, we have about a
  1063                 // 1 in 2**21 chance of having a false positive here.
  1064                 uint8_t algo;
  1065                 uint8_t session_key[1024];
  1066                 size_t session_key_len = sizeof(session_key);
  1067                 if (pgp_pkesk_decrypt(&err, pkesk, key,
  1068                                       &algo, session_key, &session_key_len)) {
  1069                     pgp_error_free(err);
  1070                     err = NULL;
  1071                     continue;
  1072                 }
  1073 
  1074                 // Add it to the recipient list.
  1075                 pgp_fingerprint_t fp = pgp_tpk_fingerprint(tsk);
  1076                 char *fp_string = pgp_fingerprint_to_hex(fp);
  1077                 T("wildcard recipient appears to be %s", fp_string);
  1078                 stringlist_add_unique(cookie->recipient_keylist, fp_string);
  1079                 free(fp_string);
  1080                 pgp_fingerprint_free(fp);
  1081 
  1082                 pgp_session_key_t sk = pgp_session_key_from_bytes (session_key,
  1083                                                                    session_key_len);
  1084                 pgp_status_t status;
  1085                 if ((status = decrypt (decrypt_cookie, algo, sk))) {
  1086                     DUMP_STATUS(status, PEP_UNKNOWN_ERROR, "decrypt_cb");
  1087                     goto eol2;
  1088                 }
  1089 
  1090                 *identity_out = pgp_tpk_fingerprint(tsk);
  1091                 cookie->decrypted = 1;
  1092 
  1093                 break;
  1094             }
  1095 
  1096             pgp_tpk_key_iter_free(key_iter);
  1097             key_iter = NULL;
  1098         }
  1099     eol2:
  1100         pgp_session_key_free (sk);
  1101         free(keyid_str);
  1102         pgp_tpk_key_iter_free(key_iter);
  1103     }
  1104 
  1105     if (tsks) {
  1106         for (int i = 0; i < tsks_count; i ++)
  1107             pgp_tpk_free(tsks[i]);
  1108         free(tsks);
  1109     }
  1110 
  1111     return cookie->decrypted ? PGP_STATUS_SUCCESS : PGP_STATUS_UNKNOWN_ERROR;
  1112 }
  1113 
  1114 static pgp_status_t
  1115 check_signatures_cb(void *cookie_opaque, pgp_message_structure_t structure)
  1116 {
  1117     struct decrypt_cookie *cookie = cookie_opaque;
  1118     PEP_SESSION session = cookie->session;
  1119 
  1120     pgp_message_structure_iter_t iter
  1121         = pgp_message_structure_iter (structure);
  1122     for (pgp_message_layer_t layer = pgp_message_structure_iter_next (iter);
  1123          layer;
  1124          layer = pgp_message_structure_iter_next (iter)) {
  1125         pgp_verification_result_iter_t results;
  1126 
  1127         switch (pgp_message_layer_variant (layer)) {
  1128         case PGP_MESSAGE_LAYER_COMPRESSION:
  1129         case PGP_MESSAGE_LAYER_ENCRYPTION:
  1130             break;
  1131 
  1132         case PGP_MESSAGE_LAYER_SIGNATURE_GROUP:
  1133             pgp_message_layer_signature_group(layer, &results);
  1134             pgp_verification_result_t result;
  1135             while ((result = pgp_verification_result_iter_next (results))) {
  1136                 pgp_signature_t sig;
  1137                 pgp_keyid_t keyid = NULL;
  1138                 char *keyid_str = NULL;
  1139 
  1140                 switch (pgp_verification_result_variant (result)) {
  1141                 case PGP_VERIFICATION_RESULT_GOOD_CHECKSUM:
  1142                     // We need to add the fingerprint of the primary
  1143                     // key to cookie->signer_keylist.
  1144 
  1145                     pgp_verification_result_good_checksum (result, &sig, NULL,
  1146                                                            NULL, NULL, NULL);
  1147 
  1148                     // First try looking up by the TPK using the
  1149                     // IssuerFingerprint subpacket.
  1150                     pgp_fingerprint_t fpr
  1151                         = pgp_signature_issuer_fingerprint(sig);
  1152                     if (fpr) {
  1153                         // Even though we have a fingerprint, we have
  1154                         // to look the key up by keyid, because we
  1155                         // want to match on subkeys and we only store
  1156                         // keyids for subkeys.
  1157                         keyid = pgp_fingerprint_to_keyid(fpr);
  1158                         pgp_fingerprint_free(fpr);
  1159                     } else {
  1160                         // That is not available, try using the Issuer
  1161                         // subpacket.
  1162                         keyid = pgp_signature_issuer(sig);
  1163                     }
  1164 
  1165                     if (! keyid) {
  1166                         T("signature with no Issuer or Issuer Fingerprint subpacket!");
  1167                         goto eol;
  1168                     }
  1169 
  1170                     pgp_tpk_t tpk;
  1171                     if (tpk_find_by_keyid(session, keyid, false,
  1172                                           &tpk, NULL) != PEP_STATUS_OK)
  1173                         ; // Soft error.  Ignore.
  1174 
  1175                     keyid_str = pgp_keyid_to_string (keyid);
  1176 
  1177                     if (tpk) {
  1178                         // Ok, we have a TPK.
  1179 
  1180                         // We need the primary key's fingerprint (not
  1181                         // the issuer fingerprint).
  1182                         pgp_fingerprint_t primary_fpr
  1183                             = pgp_tpk_fingerprint(tpk);
  1184                         char *primary_fpr_str
  1185                             = pgp_fingerprint_to_hex(primary_fpr);
  1186 
  1187                         bool good = true;
  1188 
  1189                         // Make sure the TPK is not revoked, it's
  1190                         // creation time is <= now, and it hasn't
  1191                         // expired.
  1192                         pgp_revocation_status_t rs = pgp_tpk_revocation_status(tpk);
  1193                         bool revoked = (pgp_revocation_status_variant(rs)
  1194                                         == PGP_REVOCATION_STATUS_REVOKED);
  1195                         pgp_revocation_status_free(rs);
  1196                         if (revoked) {
  1197                             T("TPK %s is revoked.", primary_fpr_str);
  1198                             good = false;
  1199                             cookie->good_but_revoked ++;
  1200                         } else if (! pgp_tpk_alive(tpk)) {
  1201                             T("TPK %s is not alive.", primary_fpr_str);
  1202                             good = false;
  1203                             cookie->good_but_expired ++;
  1204                         }
  1205 
  1206                         // Same thing for the signing key.
  1207                         if (good) {
  1208                             pgp_tpk_key_iter_t iter = pgp_tpk_key_iter_all(tpk);
  1209                             pgp_key_t key;
  1210                             pgp_signature_t sig;
  1211                             while ((key = pgp_tpk_key_iter_next(iter, &sig, &rs))
  1212                                    && good) {
  1213                                 pgp_keyid_t x = pgp_key_keyid(key);
  1214                                 if (pgp_keyid_equal(keyid, x)) {
  1215                                     // Found the signing key.  Let's make
  1216                                     // sure it is valid.
  1217 
  1218                                     revoked = (pgp_revocation_status_variant(rs)
  1219                                                == PGP_REVOCATION_STATUS_REVOKED);
  1220                                     if (revoked) {
  1221                                         T("TPK %s's signing key %s is revoked.",
  1222                                           primary_fpr_str, keyid_str);
  1223                                         good = false;
  1224                                         cookie->good_but_revoked ++;
  1225                                     } else if (! pgp_signature_key_alive(sig, key)) {
  1226                                         T("TPK %s's signing key %s is expired.",
  1227                                           primary_fpr_str, keyid_str);
  1228                                         good = false;
  1229                                         cookie->good_but_expired ++;
  1230                                     }
  1231                                 }
  1232                                 pgp_keyid_free(x);
  1233                                 pgp_revocation_status_free(rs);
  1234                                 pgp_signature_free(sig);
  1235                                 pgp_key_free(key);
  1236                             }
  1237                             pgp_tpk_key_iter_free(iter);
  1238                         }
  1239 
  1240                         if (good) {
  1241                             stringlist_add_unique(cookie->signer_keylist,
  1242                                                   primary_fpr_str);
  1243 
  1244                             T("Good signature from %s", primary_fpr_str);
  1245 
  1246                             cookie->good_checksums ++;
  1247                         }
  1248 
  1249                         free(primary_fpr_str);
  1250                         pgp_fingerprint_free(primary_fpr);
  1251                         pgp_tpk_free(tpk);
  1252                     } else {
  1253                         // If we get
  1254                         // PGP_VERIFICATION_RESULT_CODE_GOOD_CHECKSUM,
  1255                         // then the TPK should be available.  But,
  1256                         // another process could have deleted the key
  1257                         // from the store in the mean time, so be
  1258                         // tolerant.
  1259                         T("Key to check signature from %s disappeared",
  1260                           keyid_str);
  1261                         cookie->missing_keys ++;
  1262                     }
  1263                     break;
  1264 
  1265                 case PGP_VERIFICATION_RESULT_MISSING_KEY:
  1266                     pgp_verification_result_missing_key (result, &sig);
  1267                     keyid = pgp_signature_issuer (sig);
  1268                     keyid_str = pgp_keyid_to_string (keyid);
  1269                     T("No key to check signature from %s", keyid_str);
  1270 
  1271                     cookie->missing_keys ++;
  1272                     break;
  1273 
  1274                 case PGP_VERIFICATION_RESULT_BAD_CHECKSUM:
  1275                     pgp_verification_result_bad_checksum (result, &sig);
  1276                     keyid = pgp_signature_issuer (sig);
  1277                     if (keyid) {
  1278                         keyid_str = pgp_keyid_to_string (keyid);
  1279                         T("Bad signature from %s", keyid_str);
  1280                     } else {
  1281                         T("Bad signature without issuer information");
  1282                     }
  1283 
  1284                     cookie->bad_checksums ++;
  1285                     break;
  1286 
  1287                 default:
  1288                     assert (! "reachable");
  1289                 }
  1290 
  1291             eol:
  1292                 free (keyid_str);
  1293                 pgp_signature_free (sig);
  1294                 pgp_verification_result_free (result);
  1295             }
  1296             pgp_verification_result_iter_free (results);
  1297             break;
  1298 
  1299         default:
  1300             assert (! "reachable");
  1301         }
  1302 
  1303         pgp_message_layer_free (layer);
  1304     }
  1305 
  1306     pgp_message_structure_iter_free (iter);
  1307     pgp_message_structure_free (structure);
  1308 
  1309     return PGP_STATUS_SUCCESS;
  1310 }
  1311 
  1312 static pgp_status_t inspect_cb(
  1313     void *cookie_opaque, pgp_packet_parser_t pp)
  1314 {
  1315     struct decrypt_cookie *cookie = cookie_opaque;
  1316 
  1317     pgp_packet_t packet = pgp_packet_parser_packet(pp);
  1318     assert(packet);
  1319 
  1320     pgp_tag_t tag = pgp_packet_tag(packet);
  1321 
  1322     T("%s", pgp_tag_to_string(tag));
  1323 
  1324     if (tag == PGP_TAG_LITERAL) {
  1325         pgp_literal_t literal = pgp_packet_ref_literal(packet);
  1326         cookie->filename = pgp_literal_filename(literal);
  1327         pgp_literal_free(literal);
  1328     }
  1329 
  1330     pgp_packet_free(packet);
  1331 
  1332     return 0;
  1333 }
  1334 
  1335 PEP_STATUS pgp_decrypt_and_verify(
  1336     PEP_SESSION session, const char *ctext, size_t csize,
  1337     const char *dsigtext, size_t dsigsize,
  1338     char **ptext, size_t *psize, stringlist_t **keylist,
  1339     char** filename_ptr)
  1340 {
  1341     PEP_STATUS status = PEP_STATUS_OK;
  1342     struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, NULL };
  1343     pgp_reader_t reader = NULL;
  1344     pgp_writer_t writer = NULL;
  1345     pgp_reader_t decryptor = NULL;
  1346     *ptext = NULL;
  1347     *psize = 0;
  1348 
  1349     // XXX: We don't yet handle detached signatures over encrypted
  1350     // messages.
  1351     assert(!dsigtext);
  1352 
  1353     cookie.recipient_keylist = new_stringlist(NULL);
  1354     if (!cookie.recipient_keylist)
  1355         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "recipient_keylist");
  1356 
  1357     cookie.signer_keylist = new_stringlist(NULL);
  1358     if (!cookie.signer_keylist)
  1359         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "signer_keylist");
  1360 
  1361     reader = pgp_reader_from_bytes((const uint8_t *) ctext, csize);
  1362     if (! reader)
  1363         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating reader");
  1364 
  1365     writer = pgp_writer_alloc((void **) ptext, psize);
  1366     if (! writer)
  1367         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "Creating writer");
  1368 
  1369     pgp_error_t err = NULL;
  1370     decryptor = pgp_decryptor_new(&err, reader,
  1371                                   get_public_keys_cb, decrypt_cb,
  1372                                   check_signatures_cb, inspect_cb,
  1373                                   &cookie, 0);
  1374     if (! decryptor)
  1375         ERROR_OUT(err, PEP_DECRYPT_NO_KEY, "pgp_decryptor_new");
  1376 
  1377     // Copy 128 MB at a time.
  1378     ssize_t nread;
  1379     while ((nread = pgp_reader_copy (&err, decryptor, writer,
  1380                                      128 * 1024 * 1024) > 0))
  1381         ;
  1382     if (nread < 0)
  1383         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "pgp_reader_read");
  1384 
  1385     // Add a terminating NUL for naive users
  1386     pgp_writer_write(&err, writer, (const uint8_t *) &""[0], 1);
  1387 
  1388     if (! cookie.decrypted)
  1389         ERROR_OUT(err, PEP_DECRYPT_NO_KEY, "Decryption failed");
  1390 
  1391     if (! cookie.signer_keylist) {
  1392         cookie.signer_keylist = new_stringlist("");
  1393         if (! cookie.signer_keylist)
  1394             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  1395     }
  1396     if (!cookie.signer_keylist->value)
  1397         stringlist_add(cookie.signer_keylist, "");
  1398 
  1399     *keylist = cookie.signer_keylist;
  1400     stringlist_append(*keylist, cookie.recipient_keylist);
  1401 
  1402     if (filename_ptr)
  1403         *filename_ptr = cookie.filename;
  1404 
  1405  out:
  1406     if (status == PEP_STATUS_OK) {
  1407         // **********************************
  1408         // Sync changes with pgp_verify_text.
  1409         // **********************************
  1410 
  1411         if (cookie.good_checksums) {
  1412             // If there is at least one signature that we can verify,
  1413             // succeed.
  1414             status = PEP_DECRYPTED_AND_VERIFIED;
  1415         } else if (cookie.good_but_revoked) {
  1416             // If there are any signatures from revoked keys, fail.
  1417             status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1418         } else if (cookie.bad_checksums) {
  1419             // If there are any bad signatures, fail.
  1420             status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1421         } else if (cookie.good_but_expired) {
  1422             // If there are any signatures from expired keys, fail.
  1423             status = PEP_DECRYPTED;
  1424         } else {
  1425             // We couldn't verify any signatures (possibly because we
  1426             // don't have the keys).
  1427             status = PEP_DECRYPTED;
  1428         }
  1429     } else {
  1430         free_stringlist(cookie.recipient_keylist);
  1431         free_stringlist(cookie.signer_keylist);
  1432         free(cookie.filename);
  1433         free(*ptext);
  1434     }
  1435 
  1436     pgp_reader_free(reader);
  1437     pgp_reader_free(decryptor);
  1438     pgp_writer_free(writer);
  1439 
  1440     T("-> %s", pEp_status_to_string(status));
  1441     return status;
  1442 }
  1443 
  1444 PEP_STATUS pgp_verify_text(
  1445     PEP_SESSION session, const char *text, size_t size,
  1446     const char *signature, size_t sig_size, stringlist_t **keylist)
  1447 {
  1448     PEP_STATUS status = PEP_STATUS_OK;
  1449     pgp_error_t err = NULL;
  1450     struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, };
  1451     pgp_reader_t reader = NULL;
  1452     pgp_reader_t dsig_reader = NULL;
  1453     pgp_reader_t verifier = NULL;
  1454 
  1455     if (size == 0 || sig_size == 0)
  1456         return PEP_DECRYPT_WRONG_FORMAT;
  1457 
  1458     cookie.recipient_keylist = new_stringlist(NULL);
  1459     if (!cookie.recipient_keylist)
  1460         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1461 
  1462     cookie.signer_keylist = new_stringlist(NULL);
  1463     if (!cookie.signer_keylist)
  1464         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1465 
  1466     reader = pgp_reader_from_bytes((const uint8_t *) text, size);
  1467     if (! reader)
  1468         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating reader");
  1469 
  1470     dsig_reader = NULL;
  1471     if (signature) {
  1472         dsig_reader = pgp_reader_from_bytes((uint8_t *) signature, sig_size);
  1473         if (! dsig_reader)
  1474             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating signature reader");
  1475     }
  1476 
  1477     if (dsig_reader)
  1478         verifier = pgp_detached_verifier_new(&err, dsig_reader, reader,
  1479                                              get_public_keys_cb,
  1480                                              check_signatures_cb,
  1481                                              &cookie, 0);
  1482     else
  1483         verifier = pgp_verifier_new(&err, reader,
  1484                                     get_public_keys_cb,
  1485                                     check_signatures_cb,
  1486                                     &cookie, 0);
  1487     if (! verifier)
  1488         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Creating verifier");
  1489     if (pgp_reader_discard(&err, verifier) < 0)
  1490         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "verifier");
  1491 
  1492     if (! cookie.signer_keylist) {
  1493         cookie.signer_keylist = new_stringlist("");
  1494         if (! cookie.signer_keylist)
  1495             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  1496     }
  1497     if (!cookie.signer_keylist->value)
  1498         stringlist_add(cookie.signer_keylist, "");
  1499 
  1500     *keylist = cookie.signer_keylist;
  1501     stringlist_append(*keylist, cookie.recipient_keylist);
  1502 
  1503  out:
  1504     if (status == PEP_STATUS_OK) {
  1505         // *****************************************
  1506         // Sync changes with pgp_decrypt_and_verify.
  1507         // *****************************************
  1508 
  1509         if (cookie.good_but_expired) {
  1510             // If there are any signatures from expired keys, fail.
  1511             status = PEP_UNENCRYPTED;
  1512         } else if (cookie.good_but_revoked) {
  1513             // If there are any signatures from revoked keys, fail.
  1514             status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1515         } else if (cookie.bad_checksums) {
  1516             // If there are any bad signatures, fail.
  1517             status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1518         } else if (cookie.good_checksums) {
  1519             // If there is at least one signature that we can verify,
  1520             // succeed.
  1521             status = PEP_VERIFIED;
  1522         } else {
  1523             // We couldn't verify any signatures (possibly because we
  1524             // don't have the keys).
  1525             status = PEP_UNENCRYPTED;
  1526         }
  1527     } else {
  1528         free_stringlist(cookie.recipient_keylist);
  1529         free_stringlist(cookie.signer_keylist);
  1530     }
  1531 
  1532     pgp_reader_free(verifier);
  1533     pgp_reader_free(reader);
  1534     pgp_reader_free(dsig_reader);
  1535 
  1536     T("-> %s", pEp_status_to_string(status));
  1537     return status;
  1538 }
  1539 
  1540 
  1541 PEP_STATUS pgp_sign_only(
  1542     PEP_SESSION session, const char* fpr, const char *ptext,
  1543     size_t psize, char **stext, size_t *ssize)
  1544 {
  1545     assert(session);
  1546     assert(fpr && fpr[0]);
  1547     assert(ptext);
  1548     assert(psize);
  1549     assert(stext);
  1550     assert(ssize);
  1551     *stext = NULL;
  1552     *ssize = 0;
  1553 
  1554     PEP_STATUS status = PEP_STATUS_OK;
  1555     pgp_error_t err = NULL;
  1556     pgp_tpk_t signer_tpk = NULL;
  1557     pgp_tpk_key_iter_t iter = NULL;
  1558     pgp_key_pair_t signing_keypair = NULL;
  1559     pgp_signer_t signer = NULL;
  1560     pgp_writer_stack_t ws = NULL;
  1561 
  1562     status = tpk_find_by_fpr_hex(session, fpr, true, &signer_tpk, NULL);
  1563     ERROR_OUT(NULL, status, "Looking up key '%s'", fpr);
  1564 
  1565     iter = pgp_tpk_key_iter_valid(signer_tpk);
  1566     pgp_tpk_key_iter_signing_capable (iter);
  1567     pgp_tpk_key_iter_unencrypted_secret (iter, true);
  1568 
  1569     // If there are multiple signing capable subkeys, we just take
  1570     // the first one, whichever one that happens to be.
  1571     pgp_key_t key = pgp_tpk_key_iter_next (iter, NULL, NULL);
  1572     if (! key)
  1573         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  1574                    "%s has no signing capable key", fpr);
  1575 
  1576     signing_keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  1577     if (! signing_keypair)
  1578         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  1579 
  1580     signer = pgp_key_pair_as_signer (signing_keypair);
  1581     if (! signer)
  1582         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  1583 
  1584 
  1585     pgp_writer_t writer = pgp_writer_alloc((void **) stext, ssize);
  1586     writer = pgp_armor_writer_new(&err, writer,
  1587                                   PGP_ARMOR_KIND_MESSAGE, NULL, 0);
  1588     if (!writer)
  1589         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  1590 
  1591     ws = pgp_writer_stack_message(writer);
  1592 
  1593     ws = pgp_signer_new_detached(&err, ws, &signer, 1, 0);
  1594     if (!ws)
  1595         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up signer");
  1596 
  1597     pgp_status_t write_status =
  1598         pgp_writer_stack_write_all (&err, ws,
  1599                                     (uint8_t *) ptext, psize);
  1600     if (write_status != 0)
  1601         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Encrypting message");
  1602 
  1603     pgp_status_t pgp_status = pgp_writer_stack_finalize (&err, ws);
  1604     ws = NULL;
  1605     if (pgp_status != 0)
  1606         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Flushing writer");
  1607 
  1608     // Add a terminating NUL for naive users
  1609     void *t = realloc(*stext, *ssize + 1);
  1610     if (! t)
  1611         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1612     *stext = t;
  1613     (*stext)[*ssize] = 0;
  1614 
  1615  out:
  1616     pgp_signer_free (signer);
  1617     pgp_key_pair_free (signing_keypair);
  1618     pgp_tpk_key_iter_free (iter);
  1619     pgp_tpk_free(signer_tpk);
  1620 
  1621     T("(%s)-> %s", fpr, pEp_status_to_string(status));
  1622     return status;
  1623 }
  1624 
  1625 static PEP_STATUS pgp_encrypt_sign_optional(
  1626     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1627     size_t psize, char **ctext, size_t *csize, bool sign)
  1628 {
  1629     PEP_STATUS status = PEP_STATUS_OK;
  1630     pgp_error_t err = NULL;
  1631     int keys_count = 0;
  1632     pgp_tpk_t *keys = NULL;
  1633     pgp_tpk_t signer_tpk = NULL;
  1634     pgp_writer_stack_t ws = NULL;
  1635     pgp_tpk_key_iter_t iter = NULL;
  1636     pgp_key_pair_t signing_keypair = NULL;
  1637     pgp_signer_t signer = NULL;
  1638 
  1639     assert(session);
  1640     assert(keylist);
  1641     assert(ptext);
  1642     assert(psize);
  1643     assert(ctext);
  1644     assert(csize);
  1645 
  1646     *ctext = NULL;
  1647     *csize = 0;
  1648 
  1649     keys = calloc(stringlist_length(keylist), sizeof(*keys));
  1650     if (keys == NULL)
  1651         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1652 
  1653     // Get the keys for the recipients.
  1654     const stringlist_t *_keylist;
  1655     for (_keylist = keylist; _keylist != NULL; _keylist = _keylist->next) {
  1656         assert(_keylist->value);
  1657         pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(_keylist->value);
  1658         status = tpk_find_by_fpr(session, pgp_fpr, false, &keys[keys_count ++], NULL);
  1659         pgp_fingerprint_free(pgp_fpr);
  1660         ERROR_OUT(NULL, status, "Looking up key for recipient '%s'", _keylist->value);
  1661     }
  1662 
  1663     if (sign) {
  1664         // The first key in the keylist is the signer.
  1665         status = tpk_find_by_fpr_hex(session, keylist->value, true, &signer_tpk, NULL);
  1666         ERROR_OUT(NULL, status, "Looking up key for signing '%s'", keylist->value);
  1667     }
  1668 
  1669     pgp_writer_t writer = pgp_writer_alloc((void **) ctext, csize);
  1670     writer = pgp_armor_writer_new(&err, writer,
  1671                                   PGP_ARMOR_KIND_MESSAGE, NULL, 0);
  1672     if (!writer)
  1673         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  1674 
  1675     ws = pgp_writer_stack_message(writer);
  1676     ws = pgp_encryptor_new (&err, ws,
  1677                             NULL, 0, keys, keys_count,
  1678                             PGP_ENCRYPTION_MODE_FOR_TRANSPORT, 0);
  1679     if (!ws)
  1680         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up encryptor");
  1681 
  1682     if (sign) {
  1683         iter = pgp_tpk_key_iter_valid(signer_tpk);
  1684         pgp_tpk_key_iter_signing_capable (iter);
  1685         pgp_tpk_key_iter_unencrypted_secret (iter, true);
  1686 
  1687         // If there are multiple signing capable subkeys, we just take
  1688         // the first one, whichever one that happens to be.
  1689         pgp_key_t key = pgp_tpk_key_iter_next (iter, NULL, NULL);
  1690         if (! key)
  1691             ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  1692                        "%s has no signing capable key", keylist->value);
  1693 
  1694         signing_keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  1695         if (! signing_keypair)
  1696             ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  1697 
  1698         signer = pgp_key_pair_as_signer (signing_keypair);
  1699         if (! signer)
  1700             ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  1701 
  1702         ws = pgp_signer_new(&err, ws, &signer, 1, 0);
  1703         if (!ws)
  1704             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up signer");
  1705     }
  1706 
  1707     ws = pgp_literal_writer_new (&err, ws);
  1708     if (!ws)
  1709         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up literal writer");
  1710 
  1711     pgp_status_t write_status =
  1712         pgp_writer_stack_write_all (&err, ws,
  1713                                     (uint8_t *) ptext, psize);
  1714     if (write_status != 0)
  1715         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Encrypting message");
  1716 
  1717     pgp_status_t pgp_status = pgp_writer_stack_finalize (&err, ws);
  1718     ws = NULL;
  1719     if (pgp_status != 0)
  1720         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Flushing writer");
  1721 
  1722     // Add a terminating NUL for naive users
  1723     void *t = realloc(*ctext, *csize + 1);
  1724     if (! t) {
  1725         free(*ctext);
  1726         *ctext = NULL;
  1727         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1728     }
  1729     *ctext = t;
  1730     (*ctext)[*csize] = 0;
  1731 
  1732  out:
  1733     pgp_signer_free (signer);
  1734     pgp_key_pair_free (signing_keypair);
  1735     pgp_tpk_key_iter_free (iter);
  1736     pgp_tpk_free(signer_tpk);
  1737 
  1738     for (int i = 0; i < keys_count; i ++)
  1739         pgp_tpk_free(keys[i]);
  1740     free(keys);
  1741 
  1742     T("-> %s", pEp_status_to_string(status));
  1743     return status;
  1744 }
  1745 
  1746 PEP_STATUS pgp_encrypt_only(
  1747     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1748     size_t psize, char **ctext, size_t *csize)
  1749 {
  1750     return pgp_encrypt_sign_optional(session, keylist, ptext,
  1751         psize, ctext, csize, false);
  1752 }
  1753 
  1754 PEP_STATUS pgp_encrypt_and_sign(
  1755     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1756     size_t psize, char **ctext, size_t *csize)
  1757 {
  1758     return pgp_encrypt_sign_optional(session, keylist, ptext,
  1759         psize, ctext, csize, true);
  1760 }
  1761 
  1762 
  1763 PEP_STATUS pgp_generate_keypair(PEP_SESSION session, pEp_identity *identity)
  1764 {
  1765     PEP_STATUS status = PEP_STATUS_OK;
  1766     pgp_error_t err = NULL;
  1767     pgp_packet_t userid_packet = NULL;
  1768     char *userid = NULL;
  1769     pgp_tpk_t tpk = NULL;
  1770     pgp_fingerprint_t pgp_fpr = NULL;
  1771     char *fpr = NULL;
  1772 
  1773     assert(session);
  1774     assert(identity);
  1775     assert(identity->address);
  1776     assert(identity->fpr == NULL || identity->fpr[0] == 0);
  1777     assert(identity->username);
  1778 
  1779     userid_packet = pgp_user_id_from_unchecked_address(&err,
  1780                                                        identity->username, NULL,
  1781                                                        identity->address);
  1782     if (!userid_packet)
  1783         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "pgp_user_id_from_other_address");
  1784 
  1785     size_t userid_len = 0;
  1786     const uint8_t *raw = pgp_user_id_value(userid_packet, &userid_len);
  1787 
  1788     // NUL terminate it.
  1789     userid = malloc(userid_len + 1);
  1790     if (!userid)
  1791         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1792 
  1793     memcpy(userid, raw, userid_len);
  1794     userid[userid_len] = 0;
  1795 
  1796     T("(%s)", userid);
  1797 
  1798     // Generate a key.
  1799     pgp_tpk_builder_t tpkb = pgp_tpk_builder_general_purpose(
  1800         cipher_suite(session->cipher_suite), userid);
  1801     pgp_signature_t rev;
  1802     if (pgp_tpk_builder_generate(&err, tpkb, &tpk, &rev))
  1803         ERROR_OUT(err, PEP_CANNOT_CREATE_KEY, "Generating a key pair");
  1804 
  1805     // XXX: We should return this.
  1806     pgp_signature_free(rev);
  1807 
  1808     // Get the fingerprint.
  1809     pgp_fpr = pgp_tpk_fingerprint(tpk);
  1810     fpr = pgp_fingerprint_to_hex(pgp_fpr);
  1811 
  1812     status = tpk_save(session, tpk, NULL);
  1813     tpk = NULL;
  1814     if (status != 0)
  1815         ERROR_OUT(NULL, PEP_CANNOT_CREATE_KEY, "saving TSK");
  1816 
  1817     free(identity->fpr);
  1818     identity->fpr = fpr;
  1819     fpr = NULL;
  1820 
  1821  out:
  1822     pgp_fingerprint_free(pgp_fpr);
  1823     free(fpr);
  1824     pgp_tpk_free(tpk);
  1825     free(userid);
  1826     pgp_packet_free(userid_packet);
  1827 
  1828     T("-> %s", pEp_status_to_string(status));
  1829     return status;
  1830 }
  1831 
  1832 PEP_STATUS pgp_delete_keypair(PEP_SESSION session, const char *fpr_raw)
  1833 {
  1834     PEP_STATUS status = PEP_STATUS_OK;
  1835 
  1836     assert(session && fpr_raw && fpr_raw[0]);
  1837     if (!(session && fpr_raw && fpr_raw[0]))
  1838         ERROR_OUT(NULL, PEP_ILLEGAL_VALUE, "invalid arguments");
  1839 
  1840     char *fpr = pgp_fingerprint_canonicalize(fpr_raw);
  1841     if (! fpr)
  1842         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1843 
  1844     T("Deleting %s", fpr);
  1845 
  1846     sqlite3_stmt *stmt = session->sq_sql.delete_keypair;
  1847     sqlite3_bind_text(stmt, 1, fpr, -1, free);
  1848 
  1849     int sqlite_result = Sqlite3_step(stmt);
  1850     sqlite3_reset(stmt);
  1851     if (sqlite_result != SQLITE_DONE)
  1852         ERROR_OUT(NULL, PEP_CANNOT_DELETE_KEY,
  1853                   "deletion failed: %s", sqlite3_errmsg(session->key_db));
  1854 
  1855     sqlite_result = sqlite3_changes(session->key_db);
  1856     assert(sqlite_result >= 0 && sqlite_result < 2);
  1857     if (sqlite_result < 1)
  1858         ERROR_OUT(NULL, PEP_KEY_NOT_FOUND,
  1859                   "attempt to delete non-existent key: %s", fpr_raw);
  1860 
  1861  out:
  1862     return status;
  1863 }
  1864 
  1865 PEP_STATUS pgp_import_keydata(PEP_SESSION session, const char *key_data,
  1866                               size_t size, identity_list **private_idents)
  1867 {
  1868     PEP_STATUS status = PEP_NO_KEY_IMPORTED;
  1869     pgp_error_t err;
  1870     pgp_tpk_parser_t parser = NULL;
  1871 
  1872     if (private_idents)
  1873         *private_idents = NULL;
  1874 
  1875     T("parsing %zd bytes", size);
  1876 
  1877     pgp_packet_parser_result_t ppr
  1878         = pgp_packet_parser_from_bytes(&err, (uint8_t *) key_data, size);
  1879     if (! ppr)
  1880         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Creating packet parser");
  1881 
  1882     pgp_tag_t tag = pgp_packet_parser_result_tag(ppr);
  1883     switch (tag) {
  1884     case PGP_TAG_SIGNATURE: {
  1885         // The following asserts can't fail, because
  1886         // pgp_packet_parser_result_tag succeeded and the tag is
  1887         // right.
  1888         pgp_packet_parser_t pp = pgp_packet_parser_result_packet_parser (ppr);
  1889         assert(pp);
  1890 
  1891         pgp_packet_t packet = NULL;
  1892         if (pgp_packet_parser_next(&err, pp, &packet, &ppr))
  1893             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Getting signature packet");
  1894 
  1895         pgp_signature_t sig = pgp_packet_ref_signature (packet);
  1896         assert(sig);
  1897 
  1898         pgp_tpk_t tpk = NULL;
  1899 
  1900         pgp_fingerprint_t issuer_fpr = pgp_signature_issuer_fingerprint(sig);
  1901         if (issuer_fpr) {
  1902             char *issuer_fpr_hex = pgp_fingerprint_to_hex(issuer_fpr);
  1903             T("Importing a signature issued by %s", issuer_fpr_hex);
  1904 
  1905             status = tpk_find_by_fpr_hex(session, issuer_fpr_hex,
  1906                                          false, &tpk, NULL);
  1907             if (status && status != PEP_KEY_NOT_FOUND)
  1908                 DUMP_ERR(NULL, status, "Looking up %s", issuer_fpr_hex);
  1909 
  1910             free(issuer_fpr_hex);
  1911             pgp_fingerprint_free(issuer_fpr);
  1912         }
  1913 
  1914         if (! tpk) {
  1915             pgp_keyid_t issuer = pgp_signature_issuer(sig);
  1916             if (issuer) {
  1917                 char *issuer_hex = pgp_keyid_to_hex(issuer);
  1918                 T("Importing a signature issued by %s", issuer_hex);
  1919 
  1920                 status = tpk_find_by_keyid_hex(session, issuer_hex,
  1921                                                false, &tpk, NULL);
  1922                 if (status && status != PEP_KEY_NOT_FOUND)
  1923                     DUMP_ERR(NULL, status, "Looking up %s", issuer_hex);
  1924 
  1925                 free(issuer_hex);
  1926                 pgp_keyid_free(issuer);
  1927             }
  1928         }
  1929 
  1930         // We need a packet.  sig is only a reference, so we just need
  1931         // to free it.
  1932         pgp_signature_free(sig);
  1933 
  1934         if (tpk) {
  1935             T("Merging packet: %s", pgp_packet_debug(packet));
  1936 
  1937             tpk = pgp_tpk_merge_packets (&err, tpk, &packet, 1);
  1938             if (! tpk)
  1939                 ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Merging signature");
  1940 
  1941             status = tpk_save(session, tpk, NULL);
  1942             if (status)
  1943                 ERROR_OUT(NULL, status, "saving merged TPK");
  1944             status = PEP_KEY_IMPORTED;
  1945         }
  1946         break;
  1947     }
  1948     case PGP_TAG_PUBLIC_KEY:
  1949     case PGP_TAG_SECRET_KEY: {
  1950         parser = pgp_tpk_parser_from_packet_parser(ppr);
  1951         pgp_tpk_t tpk;
  1952         int count = 0;
  1953         err = NULL;
  1954         while ((tpk = pgp_tpk_parser_next(&err, parser))) {
  1955             count ++;
  1956 
  1957             T("#%d. TPK for %s, %s",
  1958               count, pgp_tpk_primary_user_id(tpk),
  1959               pgp_fingerprint_to_hex(pgp_tpk_fingerprint(tpk)));
  1960 
  1961             // If private_idents is not NULL and there is any private key
  1962             // material, it will be saved.
  1963             status = tpk_save(session, tpk, private_idents);
  1964             if (status == PEP_STATUS_OK)
  1965                 status = PEP_KEY_IMPORTED;
  1966             else
  1967                 ERROR_OUT(NULL, status, "saving TPK");
  1968         }
  1969         if (err || count == 0)
  1970             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "parsing key data");
  1971         break;
  1972     }
  1973     default:
  1974         ERROR_OUT(NULL, PEP_NO_KEY_IMPORTED,
  1975                   "Can't import %s", pgp_tag_to_string(tag));
  1976         break;
  1977     }
  1978 
  1979     int int_result = sqlite3_exec(
  1980         session->key_db,
  1981         "PRAGMA wal_checkpoint(FULL);\n"
  1982         ,
  1983         NULL,
  1984         NULL,
  1985         NULL
  1986     );
  1987     if (int_result != SQLITE_OK)
  1988         status = PEP_UNKNOWN_DB_ERROR;
  1989 
  1990  out:
  1991     pgp_tpk_parser_free(parser);
  1992 
  1993     T("-> %s", pEp_status_to_string(status));
  1994     return status;
  1995 }
  1996 
  1997 PEP_STATUS pgp_export_keydata(
  1998         PEP_SESSION session, const char *fpr, char **key_data, size_t *size,
  1999         bool secret)
  2000 {
  2001     PEP_STATUS status = PEP_STATUS_OK;
  2002     pgp_error_t err = NULL;
  2003     pgp_tpk_t tpk = NULL;
  2004     pgp_writer_t armor_writer = NULL;
  2005     pgp_writer_t memory_writer = NULL;
  2006 
  2007     assert(session);
  2008     assert(fpr);
  2009     assert(key_data);
  2010     assert(*key_data == NULL);
  2011     assert(size);
  2012 
  2013     *size = 0;
  2014 
  2015     T("(%s, %s)", fpr, secret ? "secret" : "public");
  2016 
  2017     // If the caller asks for a secret key and we only have a
  2018     // public key, then we return an error.
  2019     status = tpk_find_by_fpr_hex(session, fpr, secret, &tpk, NULL);
  2020     ERROR_OUT(NULL, status, "Looking up TSK for %s", fpr);
  2021 
  2022     memory_writer = pgp_writer_alloc((void **) key_data, size);
  2023     if (! memory_writer)
  2024         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "creating memory writer");
  2025     armor_writer = pgp_armor_writer_new(&err, memory_writer,
  2026                                         PGP_ARMOR_KIND_PUBLICKEY, NULL, 0);
  2027     if (! armor_writer) {
  2028         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "creating armored writer");
  2029     }
  2030 
  2031     if (secret) {
  2032         pgp_tsk_t tsk = pgp_tpk_as_tsk(tpk);
  2033         if (pgp_tsk_serialize(&err, tsk, armor_writer))
  2034             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "serializing TSK");
  2035         pgp_tsk_free(tsk);
  2036     } else {
  2037         if (pgp_tpk_serialize(&err, tpk, armor_writer))
  2038             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "serializing TPK");
  2039     }
  2040 
  2041  out:
  2042     if (armor_writer)
  2043         pgp_writer_free(armor_writer);
  2044 
  2045     if (memory_writer) {
  2046         if (status == PEP_STATUS_OK) {
  2047             // Add a trailing NUL.
  2048             pgp_writer_write(NULL, memory_writer, (const uint8_t *) "", 1);
  2049         }
  2050 
  2051         pgp_writer_free(memory_writer);
  2052     }
  2053 
  2054     if (tpk)
  2055         pgp_tpk_free(tpk);
  2056 
  2057     (*size)--;  // Sequoia is delivering the 0 byte at the end with size, but
  2058                 // pEp is expecting it without
  2059     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2060     return status;
  2061 }
  2062 
  2063 static char *_undot_address(const char* address) {
  2064     if (!address)
  2065         return NULL;
  2066 
  2067     int addr_len = strlen(address);
  2068     const char* at = memchr(address, '@', addr_len);
  2069 
  2070     if (!at)
  2071         at = address + addr_len;
  2072 
  2073     char* retval = calloc(1, addr_len + 1);
  2074 
  2075     const char* addr_curr = address;
  2076     char* retval_curr = retval;
  2077 
  2078     while (addr_curr < at) {
  2079         if (*addr_curr == '.') {
  2080             addr_curr++;
  2081             continue;
  2082         }
  2083         *retval_curr = *addr_curr;
  2084         retval_curr++;
  2085         addr_curr++;
  2086     }
  2087     if (*addr_curr == '@')
  2088         strcat(retval_curr, addr_curr);
  2089 
  2090     return retval;
  2091 }
  2092 
  2093 static stringpair_list_t *add_key(PEP_SESSION session,
  2094                                   stringpair_list_t *keyinfo_list,
  2095                                   stringlist_t* keylist,
  2096                                   pgp_tpk_t tpk, pgp_fingerprint_t fpr) {
  2097     bool revoked = false;
  2098     // Don't add revoked keys to the keyinfo_list.
  2099     if (keyinfo_list) {
  2100         pgp_revocation_status_t rs = pgp_tpk_revocation_status(tpk);
  2101         pgp_revocation_status_variant_t rsv = pgp_revocation_status_variant(rs);
  2102         pgp_revocation_status_free(rs);
  2103         if (rsv == PGP_REVOCATION_STATUS_REVOKED)
  2104             revoked = true;
  2105     }
  2106 
  2107     if (revoked && ! keylist)
  2108         return keyinfo_list;
  2109 
  2110     int dealloc_fpr = 0;
  2111     if (!fpr) {
  2112         dealloc_fpr = 1;
  2113         fpr = pgp_tpk_fingerprint(tpk);
  2114     }
  2115     char *fpr_str = pgp_fingerprint_to_hex(fpr);
  2116 
  2117     if (!revoked && keyinfo_list) {
  2118         char *user_id = pgp_tpk_primary_user_id(tpk);
  2119         if (user_id)
  2120             keyinfo_list = stringpair_list_add(keyinfo_list,
  2121                                                new_stringpair(fpr_str, user_id));
  2122         free(user_id);
  2123     }
  2124 
  2125     if (keylist)
  2126         keylist = stringlist_add(keylist, fpr_str);
  2127 
  2128     free(fpr_str);
  2129     if (dealloc_fpr)
  2130         pgp_fingerprint_free(fpr);
  2131 
  2132     return keyinfo_list;
  2133 }
  2134 
  2135 static PEP_STATUS list_keys(PEP_SESSION session,
  2136                             const char* pattern, int private_only,
  2137                             stringpair_list_t** keyinfo_list, stringlist_t** keylist)
  2138 {
  2139     PEP_STATUS status = PEP_STATUS_OK;
  2140     pgp_tpk_t tpk = NULL;
  2141     pgp_fingerprint_t fpr = NULL;
  2142 
  2143     T("('%s', private: %d)", pattern, private_only);
  2144 
  2145     stringpair_list_t* _keyinfo_list = NULL;
  2146     if (keyinfo_list) {
  2147         _keyinfo_list = new_stringpair_list(NULL);
  2148         if (!_keyinfo_list)
  2149             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_stringpair_list");
  2150     }
  2151     stringlist_t* _keylist = NULL;
  2152     if (keylist) {
  2153         _keylist = new_stringlist(NULL);
  2154         if (!_keylist)
  2155             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_string_list");
  2156     }
  2157 
  2158     // Trim any leading space.  This also makes it easier to recognize
  2159     // a string that is only whitespace.
  2160     while (*pattern == ' ')
  2161         pattern ++;
  2162 
  2163     if (strchr(pattern, '@')) {
  2164         // Looks like a mailbox.
  2165         pgp_tpk_t *tpks = NULL;
  2166         int count = 0;
  2167         status = tpk_find_by_email(session, pattern, private_only, &tpks, &count);
  2168         ERROR_OUT(NULL, status, "Looking up '%s'", pattern);
  2169         for (int i = 0; i < count; i ++) {
  2170             add_key(session, _keyinfo_list, _keylist, tpks[i], NULL);
  2171             pgp_tpk_free(tpks[i]);
  2172         }
  2173         free(tpks);
  2174 
  2175         if (count == 0) {
  2176             // If match failed, check to see if we've got a dotted
  2177             // address in the pattern.  If so, try again without dots.
  2178             const char* dotpos = strstr(pattern, ".");
  2179             const char* atpos = strstr(pattern, "@");
  2180             if (dotpos && atpos && (dotpos < atpos)) {
  2181                 char* undotted = _undot_address(pattern);
  2182                 if (undotted) {
  2183                     PEP_STATUS status = list_keys(session, undotted, private_only,
  2184                                                   keyinfo_list, keylist);
  2185                     free(undotted);
  2186                     return status;
  2187                 }
  2188             }
  2189         }
  2190     } else if (// Only hex characters and spaces
  2191                pattern[strspn(pattern, "0123456789aAbBcCdDeEfF ")] == 0
  2192                // And a fair amount of them.
  2193                && strlen(pattern) >= 16) {
  2194         // Fingerprint.  Note: the pep engine never looks keys up by
  2195         // keyid, so we don't handle them.
  2196         fpr = pgp_fingerprint_from_hex(pattern);
  2197         status = tpk_find_by_fpr(session, fpr, false, &tpk, NULL);
  2198         ERROR_OUT(NULL, status, "Looking up key");
  2199         add_key(session, _keyinfo_list, _keylist, tpk, fpr);
  2200     } else if (pattern[0] == 0) {
  2201         // Empty string.
  2202 
  2203         pgp_tpk_t *tpks = NULL;
  2204         int count = 0;
  2205         status = tpk_all(session, private_only, &tpks, &count);
  2206         ERROR_OUT(NULL, status, "Looking up '%s'", pattern);
  2207         for (int i = 0; i < count; i ++) {
  2208             add_key(session, _keyinfo_list, _keylist, tpks[i], NULL);
  2209             pgp_tpk_free(tpks[i]);
  2210         }
  2211         free(tpks);
  2212     } else {
  2213         T("unsupported pattern '%s'", pattern);
  2214     }
  2215 
  2216  out:
  2217     pgp_tpk_free(tpk);
  2218     pgp_fingerprint_free(fpr);
  2219 
  2220     if (status == PEP_KEY_NOT_FOUND)
  2221         status = PEP_STATUS_OK;
  2222 
  2223     if (status != PEP_STATUS_OK || (_keyinfo_list && !_keyinfo_list->value)) {
  2224         free_stringpair_list(_keyinfo_list);
  2225         _keyinfo_list = NULL;
  2226     }
  2227     if (keyinfo_list)
  2228         *keyinfo_list = _keyinfo_list;
  2229 
  2230     if (status != PEP_STATUS_OK || (_keylist && !_keylist->value)) {
  2231         free_stringlist(_keylist);
  2232         _keylist = NULL;
  2233     }
  2234     if (keylist)
  2235         *keylist = _keylist;
  2236 
  2237     int len = -1;
  2238     if (keylist)
  2239         len = stringlist_length(*keylist);
  2240     else if (keyinfo_list)
  2241         len = stringpair_list_length(*keyinfo_list);
  2242     T("(%s) -> %s (%d keys)", pattern, pEp_status_to_string(status), len);
  2243     return status;
  2244 }
  2245 
  2246 // pattern could be empty, an fpr, or a mailbox.
  2247 //
  2248 // keyinfo_list is a list of <fpr, openpgp userid> tuples for the
  2249 // matching keys.
  2250 //
  2251 // This function filters out revoked key, but not expired keys.
  2252 PEP_STATUS pgp_list_keyinfo(PEP_SESSION session,
  2253                             const char* pattern,
  2254                             stringpair_list_t** keyinfo_list)
  2255 {
  2256     return list_keys(session, pattern, false, keyinfo_list, NULL);
  2257 }
  2258 
  2259 PEP_STATUS pgp_recv_key(PEP_SESSION session, const char *pattern)
  2260 {
  2261     assert(!"pgp_recv_key not implemented");
  2262     return PEP_UNKNOWN_ERROR;
  2263 }
  2264 
  2265 // Unlike pgp_list_keyinfo, this function returns revoked keys.
  2266 PEP_STATUS pgp_find_keys(
  2267     PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  2268 {
  2269     return list_keys(session, pattern, false, NULL, keylist);
  2270 }
  2271 
  2272 // Unlike pgp_list_keyinfo, this function returns revoked keys.
  2273 PEP_STATUS pgp_find_private_keys(
  2274     PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  2275 {
  2276     return list_keys(session, pattern, true, NULL, keylist);
  2277 }
  2278 
  2279 PEP_STATUS pgp_send_key(PEP_SESSION session, const char *pattern)
  2280 {
  2281     assert(!"pgp_send_key not implemented");
  2282     return PEP_UNKNOWN_ERROR;
  2283 }
  2284 
  2285 PEP_STATUS pgp_get_key_rating(
  2286     PEP_SESSION session, const char *fpr, PEP_comm_type *comm_type)
  2287 {
  2288     PEP_STATUS status = PEP_STATUS_OK;
  2289     pgp_tpk_t tpk = NULL;
  2290 
  2291     assert(session);
  2292     assert(fpr);
  2293     assert(comm_type);
  2294 
  2295     *comm_type = PEP_ct_unknown;
  2296 
  2297     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2298     status = tpk_find_by_fpr(session, pgp_fpr, false, &tpk, NULL);
  2299     pgp_fingerprint_free(pgp_fpr);
  2300     ERROR_OUT(NULL, status, "Looking up key: %s", fpr);
  2301 
  2302     *comm_type = PEP_ct_OpenPGP_unconfirmed;
  2303 
  2304     if (pgp_tpk_expired(tpk)) {
  2305         *comm_type = PEP_ct_key_expired;
  2306         goto out;
  2307     }
  2308 
  2309     pgp_revocation_status_t rs = pgp_tpk_revocation_status(tpk);
  2310     pgp_revocation_status_variant_t rsv = pgp_revocation_status_variant(rs);
  2311     pgp_revocation_status_free(rs);
  2312     if (rsv == PGP_REVOCATION_STATUS_REVOKED) {
  2313         *comm_type = PEP_ct_key_revoked;
  2314         goto out;
  2315     }
  2316 
  2317     PEP_comm_type best_enc = PEP_ct_no_encryption, best_sign = PEP_ct_no_encryption;
  2318     pgp_tpk_key_iter_t key_iter = pgp_tpk_key_iter_valid(tpk);
  2319     pgp_key_t key;
  2320     pgp_signature_t sig;
  2321     pgp_revocation_status_t rev;
  2322     while ((key = pgp_tpk_key_iter_next(key_iter, &sig, &rev))) {
  2323         if (! sig)
  2324             continue;
  2325 
  2326         PEP_comm_type curr = PEP_ct_no_encryption;
  2327 
  2328         int can_enc = pgp_signature_can_encrypt_for_transport(sig)
  2329             || pgp_signature_can_encrypt_at_rest(sig);
  2330         int can_sign = pgp_signature_can_sign(sig);
  2331 
  2332         pgp_public_key_algo_t pk_algo = pgp_key_public_key_algo(key);
  2333         if (pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_ENCRYPT_SIGN
  2334             || pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_ENCRYPT
  2335             || pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_SIGN) {
  2336             int bits = pgp_key_public_key_bits(key);
  2337             if (bits < 1024)
  2338                 curr = PEP_ct_key_too_short;
  2339             else if (bits == 1024)
  2340                 curr = PEP_ct_OpenPGP_weak_unconfirmed;
  2341             else
  2342                 curr = PEP_ct_OpenPGP_unconfirmed;
  2343         } else {
  2344             curr = PEP_ct_OpenPGP_unconfirmed;
  2345         }
  2346 
  2347         if (can_enc)
  2348             best_enc = _MAX(best_enc, curr);
  2349 
  2350         if (can_sign)
  2351             best_sign = _MAX(best_sign, curr);
  2352     }
  2353     pgp_tpk_key_iter_free(key_iter);
  2354 
  2355     if (best_enc == PEP_ct_no_encryption || best_sign == PEP_ct_no_encryption) {
  2356         *comm_type = PEP_ct_key_b0rken;
  2357         goto out;
  2358     } else {
  2359         *comm_type = _MIN(best_enc, best_sign);
  2360     }
  2361 
  2362  out:
  2363     pgp_tpk_free(tpk);
  2364 
  2365     T("(%s) -> %s", fpr, pEp_comm_type_to_string(*comm_type));
  2366     return status;
  2367 }
  2368 
  2369 
  2370 PEP_STATUS pgp_renew_key(
  2371     PEP_SESSION session, const char *fpr, const timestamp *ts)
  2372 {
  2373     PEP_STATUS status = PEP_STATUS_OK;
  2374     pgp_error_t err = NULL;
  2375     pgp_tpk_t tpk = NULL;
  2376     pgp_tpk_key_iter_t iter = NULL;
  2377     pgp_key_pair_t keypair = NULL;
  2378     pgp_signer_t signer = NULL;
  2379     time_t t = mktime((struct tm *) ts);
  2380 
  2381     T("(%s)", fpr);
  2382 
  2383     status = tpk_find_by_fpr_hex(session, fpr, true, &tpk, NULL);
  2384     ERROR_OUT(NULL, status, "Looking up '%s'", fpr);
  2385 
  2386     uint32_t creation_time = pgp_key_creation_time(pgp_tpk_primary(tpk));
  2387     if (creation_time > t)
  2388         // The creation time is after the expiration time!
  2389         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
  2390                   "creation time can't be after expiration time");
  2391 
  2392     uint32_t delta = t - creation_time;
  2393 
  2394 
  2395     iter = pgp_tpk_key_iter_valid(tpk);
  2396     pgp_tpk_key_iter_certification_capable (iter);
  2397     pgp_tpk_key_iter_unencrypted_secret (iter, true);
  2398 
  2399     // If there are multiple certification capable subkeys, we just
  2400     // take the first one, whichever one that happens to be.
  2401     pgp_key_t key = pgp_tpk_key_iter_next (iter, NULL, NULL);
  2402     if (! key)
  2403         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  2404                    "%s has no usable certification capable key", fpr);
  2405 
  2406     keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  2407     if (! keypair)
  2408         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  2409 
  2410     signer = pgp_key_pair_as_signer (keypair);
  2411     if (! signer)
  2412         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  2413 
  2414     tpk = pgp_tpk_set_expiry(&err, tpk, signer, delta);
  2415     if (! tpk)
  2416         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "setting expiration");
  2417 
  2418     status = tpk_save(session, tpk, NULL);
  2419     tpk = NULL;
  2420     ERROR_OUT(NULL, status, "Saving %s", fpr);
  2421 
  2422  out:
  2423     pgp_signer_free (signer);
  2424     pgp_key_pair_free (keypair);
  2425     pgp_tpk_key_iter_free (iter);
  2426     pgp_tpk_free(tpk);
  2427 
  2428     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2429     return status;
  2430 }
  2431 
  2432 PEP_STATUS pgp_revoke_key(
  2433     PEP_SESSION session, const char *fpr, const char *reason)
  2434 {
  2435     PEP_STATUS status = PEP_STATUS_OK;
  2436     pgp_error_t err = NULL;
  2437     pgp_tpk_t tpk = NULL;
  2438     pgp_tpk_key_iter_t iter = NULL;
  2439     pgp_key_pair_t keypair = NULL;
  2440     pgp_signer_t signer = NULL;
  2441 
  2442     T("(%s)", fpr);
  2443 
  2444     status = tpk_find_by_fpr_hex(session, fpr, true, &tpk, NULL);
  2445     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2446 
  2447     iter = pgp_tpk_key_iter_valid(tpk);
  2448     pgp_tpk_key_iter_certification_capable (iter);
  2449     pgp_tpk_key_iter_unencrypted_secret (iter, true);
  2450 
  2451     // If there are multiple certification capable subkeys, we just
  2452     // take the first one, whichever one that happens to be.
  2453     pgp_key_t key = pgp_tpk_key_iter_next (iter, NULL, NULL);
  2454     if (! key)
  2455         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  2456                    "%s has no usable certification capable key", fpr);
  2457 
  2458     keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  2459     if (! keypair)
  2460         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  2461 
  2462     signer = pgp_key_pair_as_signer (keypair);
  2463     if (! signer)
  2464         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  2465 
  2466     tpk = pgp_tpk_revoke_in_place(&err, tpk, signer,
  2467                                   PGP_REASON_FOR_REVOCATION_UNSPECIFIED,
  2468                                   reason);
  2469     if (! tpk)
  2470         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "setting expiration");
  2471 
  2472     assert(pgp_revocation_status_variant(pgp_tpk_revocation_status(tpk))
  2473            == PGP_REVOCATION_STATUS_REVOKED);
  2474 
  2475     status = tpk_save(session, tpk, NULL);
  2476     tpk = NULL;
  2477     ERROR_OUT(NULL, status, "Saving %s", fpr);
  2478 
  2479  out:
  2480     pgp_signer_free (signer);
  2481     pgp_key_pair_free (keypair);
  2482     pgp_tpk_key_iter_free (iter);
  2483     pgp_tpk_free(tpk);
  2484 
  2485     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2486     return status;
  2487 }
  2488 
  2489 PEP_STATUS pgp_key_expired(PEP_SESSION session, const char *fpr,
  2490                            const time_t when, bool *expired)
  2491 {
  2492     PEP_STATUS status = PEP_STATUS_OK;
  2493     pgp_tpk_t tpk = NULL;
  2494     T("(%s)", fpr);
  2495 
  2496     assert(session);
  2497     assert(fpr);
  2498     assert(expired);
  2499 
  2500     *expired = false;
  2501 
  2502     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2503     status = tpk_find_by_fpr(session, pgp_fpr, false, &tpk, NULL);
  2504     pgp_fingerprint_free(pgp_fpr);
  2505     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2506 
  2507     // Is the TPK live?
  2508     *expired = !pgp_tpk_alive_at(tpk, when);
  2509     if (*expired)
  2510         goto out;
  2511 
  2512     // Are there at least one certification subkey, one signing subkey
  2513     // and one encryption subkey that are live?
  2514     int can_certify = 0, can_encrypt = 0, can_sign = 0;
  2515 
  2516     pgp_tpk_key_iter_t key_iter = pgp_tpk_key_iter_valid(tpk);
  2517     pgp_key_t key;
  2518     pgp_signature_t sig;
  2519     pgp_revocation_status_t rev;
  2520     while ((key = pgp_tpk_key_iter_next(key_iter, &sig, &rev))) {
  2521         if (! sig)
  2522             continue;
  2523 
  2524         if (pgp_signature_can_encrypt_for_transport(sig)
  2525             || pgp_signature_can_encrypt_at_rest(sig))
  2526             can_encrypt = 1;
  2527         if (pgp_signature_can_sign(sig))
  2528             can_sign = 1;
  2529         if (pgp_signature_can_certify(sig))
  2530             can_certify = 1;
  2531 
  2532         if (can_encrypt && can_sign && can_certify)
  2533             break;
  2534     }
  2535     pgp_tpk_key_iter_free(key_iter);
  2536 
  2537     *expired = !(can_encrypt && can_sign && can_certify);
  2538 
  2539  out:
  2540     pgp_tpk_free(tpk);
  2541     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2542     return status;
  2543 }
  2544 
  2545 PEP_STATUS pgp_key_revoked(PEP_SESSION session, const char *fpr, bool *revoked)
  2546 {
  2547     PEP_STATUS status = PEP_STATUS_OK;
  2548     pgp_tpk_t tpk;
  2549 
  2550     T("(%s)", fpr);
  2551 
  2552     assert(session);
  2553     assert(fpr);
  2554     assert(revoked);
  2555 
  2556     *revoked = false;
  2557 
  2558     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2559     status = tpk_find_by_fpr(session, pgp_fpr, false, &tpk, NULL);
  2560     pgp_fingerprint_free(pgp_fpr);
  2561     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2562 
  2563     pgp_revocation_status_t rs = pgp_tpk_revocation_status(tpk);
  2564     *revoked = pgp_revocation_status_variant(rs) == PGP_REVOCATION_STATUS_REVOKED;
  2565     pgp_revocation_status_free (rs);
  2566     pgp_tpk_free(tpk);
  2567 
  2568  out:
  2569     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2570     return status;
  2571 }
  2572 
  2573 PEP_STATUS pgp_key_created(PEP_SESSION session, const char *fpr, time_t *created)
  2574 {
  2575     PEP_STATUS status = PEP_STATUS_OK;
  2576     pgp_tpk_t tpk = NULL;
  2577     T("(%s)", fpr);
  2578 
  2579     *created = 0;
  2580 
  2581     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2582     status = tpk_find_by_fpr(session, pgp_fpr, false, &tpk, NULL);
  2583     pgp_fingerprint_free(pgp_fpr);
  2584     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2585 
  2586     pgp_key_t k = pgp_tpk_primary(tpk);
  2587     *created = pgp_key_creation_time(k);
  2588     pgp_tpk_free(tpk);
  2589 
  2590  out:
  2591     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2592     return status;
  2593 }
  2594 
  2595 PEP_STATUS pgp_binary(const char **path)
  2596 {
  2597     *path = NULL;
  2598     return PEP_STATUS_OK;
  2599 }
  2600 
  2601 PEP_STATUS pgp_contains_priv_key(PEP_SESSION session, const char *fpr,
  2602                                  bool *has_private)
  2603 {
  2604     T("(%s)", fpr);
  2605     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2606     PEP_STATUS status = tpk_find_by_fpr(session, pgp_fpr, true, NULL, NULL);
  2607     pgp_fingerprint_free(pgp_fpr);
  2608     if (status == PEP_STATUS_OK) {
  2609         *has_private = 1;
  2610     } else if (status == PEP_KEY_NOT_FOUND) {
  2611         *has_private = 0;
  2612         status = PEP_STATUS_OK;
  2613     }
  2614     T("(%s) -> %s, %s",
  2615       fpr, *has_private ? "priv" : "pub", pEp_status_to_string(status));
  2616     return status;
  2617 }