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