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