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