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