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