src/pEp_internal.h
author Roker <roker@pep-project.org>
Wed, 16 Sep 2020 18:14:33 +0200
changeset 5065 d6d23b414a93
parent 5003 15d7602d437a
child 5043 5990dbcfb506
child 5056 94459d08475f
permissions -rw-r--r--
also "install" libpEpEngine.a into $PREFIX/lib
     1 // This file is under GNU General Public License 3.0
     2 // see LICENSE.txt
     3 
     4 // maximum attachment size to import as key 1MB, maximum of 20 attachments
     5 
     6 #define MAX_KEY_SIZE (1024 * 1024)
     7 #define MAX_KEYS_TO_IMPORT  20
     8 
     9 #define KEY_EXPIRE_DELTA (60 * 60 * 24 * 365)
    10 
    11 // this is 20 trustwords with 79 chars max
    12 #define MAX_TRUSTWORDS_SPACE (20 * 80)
    13 
    14 // XML parameters string
    15 #define PARMS_MAX 32768
    16 
    17 // maximum busy wait time in ms
    18 #define BUSY_WAIT_TIME 5000
    19 
    20 // default keyserver
    21 #ifndef DEFAULT_KEYSERVER
    22 #define DEFAULT_KEYSERVER "hkps://keys.openpgp.org"
    23 #endif
    24 
    25 // crashdump constants
    26 #ifndef CRASHDUMP_DEFAULT_LINES
    27 #define CRASHDUMP_DEFAULT_LINES 100
    28 #endif
    29 #define CRASHDUMP_MAX_LINES 32767
    30 
    31 // p≡p full string, NUL-terminated
    32 #ifndef PEP_SUBJ_STRING
    33 #define PEP_SUBJ_STRING {0x70,0xE2,0x89,0xA1,0x70,0x00}
    34 #define PEP_SUBJ_BYTELEN 5
    35 #endif
    36 
    37 #ifndef PEP_SUBJ_KEY
    38 #define PEP_SUBJ_KEY "Subject: "
    39 #define PEP_SUBJ_KEY_LC "subject: "
    40 #define PEP_SUBJ_KEY_LEN 9
    41 #endif
    42 
    43 #ifndef PEP_MSG_WRAP_KEY
    44 #define PEP_MSG_WRAP_KEY "pEp-Wrapped-Message-Info: "
    45 #define PEP_MSG_WRAP_KEY_LC "pep-wrapped-message-info: "
    46 #define PEP_MSG_WRAP_KEY_LEN 26
    47 #endif
    48 
    49 #ifndef X_PEP_MSG_WRAP_KEY
    50 #define X_PEP_MSG_WRAP_KEY "X-pEp-Wrapped-Message-Info"
    51 #endif
    52 
    53 #ifndef X_PEP_SNDR_FPR_KEY
    54 #define X_PEP_SNDR_FPR_KEY "X-pEp-Sender-FPR"
    55 #endif
    56  
    57 #include "platform.h"
    58 
    59 #ifdef WIN32
    60 #define KEYS_DB windoze_keys_db()
    61 #define LOCAL_DB windoze_local_db()
    62 #define SYSTEM_DB windoze_system_db()
    63 #else // UNIX
    64 #define _POSIX_C_SOURCE 200809L
    65 #include <dlfcn.h>
    66 #ifdef NDEBUG
    67 #define LOCAL_DB unix_local_db()
    68 #else
    69 #define LOCAL_DB unix_local_db(false)
    70 #endif
    71 #ifdef ANDROID
    72 #define SYSTEM_DB android_system_db()
    73 #else
    74 #define SYSTEM_DB unix_system_db()
    75 #endif
    76 #endif
    77 
    78 #include <locale.h>
    79 #include <stdlib.h>
    80 #include <string.h>
    81 #include <assert.h>
    82 #include <stdio.h>
    83 #include <ctype.h>
    84 #include <math.h>
    85 
    86 #ifdef SQLITE3_FROM_OS
    87 #include <sqlite3.h>
    88 #else
    89 #include "sqlite3.h"
    90 #endif
    91 
    92 #include "pEpEngine.h"
    93 
    94 // If not specified, build for Sequoia
    95 #ifndef USE_SEQUOIA
    96 #define USE_SEQUOIA
    97 #endif
    98 
    99 #if defined(USE_SEQUOIA)
   100 #include "pgp_sequoia_internal.h"
   101 #endif
   102 
   103 #include "keymanagement.h"
   104 #include "cryptotech.h"
   105 #include "transport.h"
   106 #include "sync_api.h"
   107 #include "Sync_func.h"
   108 
   109 #include "key_reset.h"
   110 
   111 #define NOT_IMPLEMENTED assert(0); return PEP_UNKNOWN_ERROR;
   112 
   113 struct _pEpSession;
   114 typedef struct _pEpSession pEpSession;
   115 struct _pEpSession {
   116     const char *version;
   117     messageToSend_t messageToSend;
   118 
   119 #if defined(USE_SEQUOIA)
   120     sqlite3 *key_db;
   121     struct {
   122         sqlite3_stmt *begin_transaction;
   123         sqlite3_stmt *commit_transaction;
   124         sqlite3_stmt *rollback_transaction;
   125         sqlite3_stmt *cert_find;
   126         sqlite3_stmt *tsk_find;
   127         sqlite3_stmt *cert_find_by_keyid;
   128         sqlite3_stmt *tsk_find_by_keyid;
   129         sqlite3_stmt *cert_find_by_email;
   130         sqlite3_stmt *tsk_find_by_email;
   131         sqlite3_stmt *cert_all;
   132         sqlite3_stmt *tsk_all;
   133         sqlite3_stmt *cert_save_insert_primary;
   134         sqlite3_stmt *cert_save_insert_subkeys;
   135         sqlite3_stmt *cert_save_insert_userids;
   136         sqlite3_stmt *delete_keypair;
   137     } sq_sql;
   138 
   139     pgp_policy_t policy;
   140 #endif
   141 
   142     PEP_cryptotech_t *cryptotech;
   143     PEP_CIPHER_SUITE cipher_suite;
   144     
   145     char* curr_passphrase;
   146     bool new_key_pass_enable;
   147     char* generation_passphrase;
   148     
   149     PEP_transport_t *transports;
   150 
   151     sqlite3 *db;
   152     sqlite3 *system_db;
   153 
   154     sqlite3_stmt *log;
   155     sqlite3_stmt *trustword;
   156     sqlite3_stmt *get_identity;
   157     sqlite3_stmt *get_identity_without_trust_check;
   158     sqlite3_stmt *get_identities_by_address;
   159     sqlite3_stmt *get_identities_by_userid;
   160     sqlite3_stmt *get_identities_by_main_key_id;
   161     sqlite3_stmt *replace_identities_fpr;
   162     sqlite3_stmt *replace_main_user_fpr;
   163     sqlite3_stmt *replace_main_user_fpr_if_equal;
   164     sqlite3_stmt *get_main_user_fpr;
   165     sqlite3_stmt *refresh_userid_default_key;
   166     sqlite3_stmt *delete_key;
   167     sqlite3_stmt *remove_fpr_as_identity_default;
   168     sqlite3_stmt *remove_fpr_as_user_default;
   169     sqlite3_stmt *set_person;
   170     sqlite3_stmt *update_person;
   171     sqlite3_stmt *delete_person;
   172     sqlite3_stmt *exists_person;    
   173     sqlite3_stmt *set_as_pEp_user;
   174     sqlite3_stmt *is_pEp_user;
   175     sqlite3_stmt *upgrade_pEp_version_by_user_id;
   176     sqlite3_stmt *add_into_social_graph;
   177     sqlite3_stmt *get_own_address_binding_from_contact;
   178     sqlite3_stmt *set_revoke_contact_as_notified;
   179     sqlite3_stmt *get_contacted_ids_from_revoke_fpr;
   180     sqlite3_stmt *was_id_for_revoke_contacted;
   181     sqlite3_stmt *has_id_contacted_address;
   182     sqlite3_stmt *get_last_contacted;
   183     // sqlite3_stmt *set_device_group;
   184     // sqlite3_stmt *get_device_group;
   185     sqlite3_stmt *set_pgp_keypair;
   186     sqlite3_stmt *set_identity_entry;
   187     sqlite3_stmt *update_identity_entry;
   188     sqlite3_stmt *exists_identity_entry;        
   189     sqlite3_stmt *set_identity_flags;
   190     sqlite3_stmt *unset_identity_flags;
   191     sqlite3_stmt *set_ident_enc_format;
   192     sqlite3_stmt *set_pEp_version; 
   193     sqlite3_stmt *clear_trust_info;   
   194     sqlite3_stmt *set_trust;
   195     sqlite3_stmt *update_trust;
   196     sqlite3_stmt *exists_trust_entry;
   197     sqlite3_stmt *update_trust_to_pEp;
   198     sqlite3_stmt *update_trust_for_fpr;
   199     sqlite3_stmt *get_trust;
   200     sqlite3_stmt *get_trust_by_userid;
   201     sqlite3_stmt *least_trust;
   202     sqlite3_stmt *mark_compromised;
   203     sqlite3_stmt *reset_trust;
   204     sqlite3_stmt *crashdump;
   205     sqlite3_stmt *languagelist;
   206     sqlite3_stmt *i18n_token;
   207     sqlite3_stmt *replace_userid;
   208 
   209     // blacklist
   210     sqlite3_stmt *blacklist_add;
   211     sqlite3_stmt *blacklist_delete;
   212     sqlite3_stmt *blacklist_is_listed;
   213     sqlite3_stmt *blacklist_retrieve;
   214     
   215     // Keys
   216     sqlite3_stmt *own_key_is_listed;
   217     sqlite3_stmt *is_own_address;
   218     sqlite3_stmt *own_identities_retrieve;
   219     sqlite3_stmt *own_keys_retrieve;
   220     sqlite3_stmt *key_identities_retrieve;
   221     sqlite3_stmt *get_user_default_key;
   222     sqlite3_stmt *get_all_keys_for_user;
   223         
   224     sqlite3_stmt *get_default_own_userid;
   225 
   226 
   227 //    sqlite3_stmt *set_own_key;
   228 
   229     // sequence value
   230     sqlite3_stmt *sequence_value1;
   231     sqlite3_stmt *sequence_value2;
   232 
   233     // revoked keys
   234     sqlite3_stmt *set_revoked;
   235     sqlite3_stmt *get_revoked;
   236     sqlite3_stmt *get_replacement_fpr;
   237 
   238     // mistrusted
   239     sqlite3_stmt* add_mistrusted_key;
   240     sqlite3_stmt* is_mistrusted_key;    
   241     sqlite3_stmt* delete_mistrusted_key;
   242     
   243     // aliases
   244     sqlite3_stmt *get_userid_alias_default;
   245     sqlite3_stmt *add_userid_alias;
   246 
   247     // callbacks
   248     examine_identity_t examine_identity;
   249     void *examine_management;
   250     notifyHandshake_t notifyHandshake;
   251     inject_sync_event_t inject_sync_event;
   252     retrieve_next_sync_event_t retrieve_next_sync_event;
   253     ensure_passphrase_t ensure_passphrase;
   254 
   255     // pEp Sync
   256     void *sync_management;
   257     void *sync_obj;
   258     struct Sync_state_s sync_state;
   259 
   260 //     void* sync_state_payload;
   261 //     char sync_uuid[37];
   262 //     time_t LastCannotDecrypt;
   263 //     time_t LastUpdateRequest;
   264 
   265     // runtime config
   266 
   267     bool passive_mode;
   268     bool unencrypted_subject;
   269     bool service_log;
   270     
   271 #ifndef NDEBUG
   272     int debug_color;
   273 #endif
   274 };
   275 
   276 
   277 PEP_STATUS init_transport_system(PEP_SESSION session, bool in_first);
   278 void release_transport_system(PEP_SESSION session, bool out_last);
   279 
   280 /* NOT to be exposed to the outside!!! */
   281 PEP_STATUS encrypt_only(
   282         PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
   283         size_t psize, char **ctext, size_t *csize
   284 );
   285 
   286 void decorate_message(
   287     PEP_SESSION session,
   288     message *msg,
   289     PEP_rating rating,
   290     stringlist_t *keylist,
   291     bool add_version,
   292     bool clobber);
   293 
   294 #if defined(NDEBUG) || defined(NOLOG)
   295 #define DEBUG_LOG(TITLE, ENTITY, DESC)
   296 #else
   297 #ifdef ANDROID
   298 #include <android/log.h>
   299 #define  LOG_MORE(...)  __android_log_print(ANDROID_LOG_DEBUG, "pEpEngine", " %s :: %s :: %s :: %s ", __VA_ARGS__);
   300 #else
   301 #include <stdio.h>
   302 #define  LOG_MORE(...)  fprintf(stderr, "pEpEngine DEBUG_LOG('%s','%s','%s','%s')\n", __VA_ARGS__);
   303 #endif
   304 #define DEBUG_LOG(TITLE, ENTITY, DESC) {\
   305     log_event(session, (TITLE), (ENTITY), (DESC), "debug " __FILE__ ":" S_LINE);\
   306     LOG_MORE((TITLE), (ENTITY), (DESC), __FILE__ ":" S_LINE)\
   307 }
   308 #endif
   309 
   310 typedef enum _normalize_hex_rest_t {
   311     accept_hex,
   312     ignore_hex,
   313     reject_hex
   314 } normalize_hex_res_t;
   315 
   316 static inline normalize_hex_res_t _normalize_hex(char *hex) 
   317 {
   318     if (*hex >= '0' && *hex <= '9')
   319         return accept_hex;
   320 
   321     if (*hex >= 'A' && *hex <= 'F') {
   322         *hex += 'a' - 'A';
   323         return accept_hex;
   324     }
   325 
   326     if (*hex >= 'a' && *hex <= 'f') 
   327         return accept_hex;
   328 
   329     if (*hex == ' ') 
   330         return ignore_hex;
   331 
   332     return reject_hex;
   333 }
   334 
   335 // Space tolerant and case insensitive fingerprint string compare
   336 static inline PEP_STATUS _compare_fprs(
   337         const char* fpra,
   338         size_t fpras,
   339         const char* fprb,
   340         size_t fprbs,
   341         int* comparison)
   342 {
   343 
   344     size_t ai = 0;
   345     size_t bi = 0;
   346     size_t significant = 0;
   347     int _comparison = 0;
   348     const int _FULL_FINGERPRINT_LENGTH = 40;
   349    
   350     // First compare every non-ignored chars until an end is reached
   351     while(ai < fpras && bi < fprbs)
   352     {
   353         char fprac = fpra[ai];
   354         char fprbc = fprb[bi];
   355         normalize_hex_res_t fprah = _normalize_hex(&fprac);
   356         normalize_hex_res_t fprbh = _normalize_hex(&fprbc);
   357 
   358         if(fprah == reject_hex || fprbh == reject_hex)
   359             return PEP_ILLEGAL_VALUE;
   360 
   361         if ( fprah == ignore_hex )
   362         {
   363             ai++;
   364         }
   365         else if ( fprbh == ignore_hex )
   366         {
   367             bi++;
   368         }
   369         else
   370         {
   371             if(fprac != fprbc && _comparison == 0 )
   372             {
   373                 _comparison = fprac > fprbc ? 1 : -1;
   374             }
   375 
   376             significant++;
   377             ai++;
   378             bi++;
   379 
   380         } 
   381     }
   382 
   383     // Bail out if we didn't got enough significnt chars
   384     if (significant != _FULL_FINGERPRINT_LENGTH )
   385         return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   386 
   387     // Then purge remaining chars, all must be ignored chars
   388     while ( ai < fpras )
   389     {
   390         char fprac = fpra[ai];
   391         normalize_hex_res_t fprah = _normalize_hex(&fprac);
   392         if( fprah == reject_hex )
   393             return PEP_ILLEGAL_VALUE;
   394         if ( fprah != ignore_hex )
   395             return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   396         ai++;
   397     }
   398     while ( bi < fprbs )
   399     {
   400         char fprbc = fprb[bi];
   401         normalize_hex_res_t fprbh = _normalize_hex(&fprbc);
   402         if( fprbh == reject_hex )
   403             return PEP_ILLEGAL_VALUE;
   404         if ( fprbh != ignore_hex )
   405             return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   406         bi++;
   407     }
   408 
   409     *comparison = _comparison;
   410     return PEP_STATUS_OK;
   411 }
   412 
   413 static inline int _same_fpr(
   414         const char* fpra,
   415         size_t fpras,
   416         const char* fprb,
   417         size_t fprbs
   418     )
   419 {
   420     // illegal values are ignored, and considered not same.
   421     int comparison = 1;
   422 
   423     _compare_fprs(fpra, fpras, fprb, fprbs, &comparison);
   424 
   425     return comparison == 0;
   426 }
   427 
   428 // size is the length of the bytestr that's coming in. This is really only intended
   429 // for comparing two full strings. If charstr's length is different from bytestr_size,
   430 // we'll return a non-zero value.
   431 static inline int _unsigned_signed_strcmp(const unsigned char* bytestr, const char* charstr, int bytestr_size) {
   432     int charstr_len = strlen(charstr);
   433     if (charstr_len != bytestr_size)
   434         return -1; // we don't actually care except that it's non-zero
   435     return memcmp(bytestr, charstr, bytestr_size);
   436 }
   437 
   438 // This is just a horrible example of C type madness. UTF-8 made me do it.
   439 static inline char* _pEp_subj_copy() {
   440 #ifndef WIN32
   441     unsigned char pEpstr[] = PEP_SUBJ_STRING;
   442     void* retval = calloc(1, sizeof(unsigned char)*PEP_SUBJ_BYTELEN + 1);
   443     memcpy(retval, pEpstr, PEP_SUBJ_BYTELEN);
   444     return (char*)retval;
   445 #else
   446     return strdup("pEp");
   447 #endif
   448 }
   449 
   450 static inline bool is_me(PEP_SESSION session, const pEp_identity* test_ident) {
   451     bool retval = false;
   452     if (test_ident && test_ident->user_id) {
   453         char* def_id = NULL;
   454         get_default_own_userid(session, &def_id);
   455         if (test_ident->me || 
   456             (def_id && strcmp(def_id, test_ident->user_id) == 0)) {
   457             retval = true;
   458         }
   459         free(def_id);
   460     }
   461     return retval;
   462 }
   463 
   464 static inline float pEp_version_numeric(const char* version_str) {
   465     float retval = 0;    
   466         
   467     if (!version_str || sscanf(version_str, "%f", &retval) != 1)
   468         return 0;
   469         
   470     return retval;    
   471 }
   472 
   473 static inline void pEp_version_major_minor(const char* version_str, unsigned int* major, unsigned int* minor) {
   474     if (!major || !minor)
   475         return;
   476                 
   477     if (!version_str || sscanf(version_str, "%u.%u", major, minor) != 2) {
   478         *major = 0;
   479         *minor = 0;
   480     }
   481         
   482     return;    
   483 }
   484 
   485 static inline int compare_versions(unsigned int first_maj, unsigned int first_min,
   486                                    unsigned int second_maj, unsigned int second_min) {
   487     if (first_maj > second_maj)
   488         return 1;
   489     if (first_maj < second_maj)
   490         return -1;
   491     if (first_min > second_min)
   492         return 1;
   493     if (first_min < second_min)
   494         return -1;
   495     return 0;    
   496 }
   497 
   498 static inline void set_min_version(unsigned int first_maj, unsigned int first_minor,
   499                                    unsigned int second_maj, unsigned int second_minor,
   500                                    unsigned int* result_maj, unsigned int* result_minor) {
   501     int result = compare_versions(first_maj, first_minor, second_maj, second_minor);
   502     if (result < 0) {
   503         *result_maj = first_maj;
   504         *result_minor = first_minor;
   505     }
   506     else {
   507         *result_maj = second_maj;
   508         *result_minor = second_minor;
   509     }    
   510 }
   511 
   512 static inline void set_max_version(unsigned int first_maj, unsigned int first_minor,
   513                                    unsigned int second_maj, unsigned int second_minor,
   514                                    unsigned int* result_maj, unsigned int* result_minor) {
   515     int result = compare_versions(first_maj, first_minor, second_maj, second_minor);
   516     if (result > 0) {
   517         *result_maj = first_maj;
   518         *result_minor = first_minor;
   519     }
   520     else {
   521         *result_maj = second_maj;
   522         *result_minor = second_minor;
   523     }    
   524 }
   525 
   526 #ifndef EMPTYSTR
   527 #define EMPTYSTR(STR) ((STR) == NULL || (STR)[0] == '\0')
   528 #endif
   529 
   530 #ifndef PASS_ERROR
   531 #define PASS_ERROR(ST) (ST == PEP_PASSPHRASE_REQUIRED || ST == PEP_WRONG_PASSPHRASE || ST == PEP_PASSPHRASE_FOR_NEW_KEYS_REQUIRED)
   532 #endif
   533 
   534 #ifndef IS_PGP_CT
   535 #define IS_PGP_CT(CT) (((CT) | PEP_ct_confirmed) == PEP_ct_OpenPGP)
   536 #endif
   537 
   538 #ifndef _MIN
   539 #define _MIN(A, B) ((B) > (A) ? (A) : (B))
   540 #endif
   541 #ifndef _MAX
   542 #define _MAX(A, B) ((B) > (A) ? (B) : (A))
   543 #endif
   544 
   545 // These are globals used in generating message IDs and should only be
   546 // computed once, as they're either really constants or OS-dependent
   547 
   548 extern int _pEp_rand_max_bits;
   549 extern double _pEp_log2_36;
   550 
   551 static inline void _init_globals() {
   552     _pEp_rand_max_bits = (int) ceil(log2((double) RAND_MAX));
   553     _pEp_log2_36 = log2(36);
   554 }
   555 
   556 // spinlock implementation
   557 
   558 static inline int Sqlite3_step(sqlite3_stmt* stmt)
   559 {
   560     int rc;
   561     do {
   562         rc = sqlite3_step(stmt);
   563     } while (rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
   564     return rc;
   565 }