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