src/pEp_internal.h
author Krista Bennett <krista@pep-project.org>
Tue, 06 Feb 2018 18:48:45 +0100
branchENGINE-250
changeset 2478 0460dfb7f3dc
parent 2473 6ca62f99148e
child 2480 8799c08f67af
permissions -rw-r--r--
ENGINE-250: fixed some things, am screaming at others. Have overcome the 'insert or update' issue at least, probably.
     1 // This file is under GNU General Public License 3.0
     2 // see LICENSE.txt
     3 
     4 #define PEP_ENGINE_VERSION "0.9.0"
     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 // 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 // maximum line length for reading gpg.conf
    21 #define MAX_LINELENGTH 1024
    22 
    23 // default keyserver
    24 #ifndef DEFAULT_KEYSERVER
    25 #define DEFAULT_KEYSERVER "hkp://keys.gnupg.net"
    26 #endif
    27 
    28 // crashdump constants
    29 #ifndef CRASHDUMP_DEFAULT_LINES
    30 #define CRASHDUMP_DEFAULT_LINES 100
    31 #endif
    32 #define CRASHDUMP_MAX_LINES 32767
    33 
    34 // p≡p full string, NUL-terminated
    35 #ifndef PEP_SUBJ_STRING
    36 #define PEP_SUBJ_STRING {0x70,0xE2,0x89,0xA1,0x70,0x00}
    37 #define PEP_SUBJ_BYTELEN 5
    38 #endif
    39 
    40 #ifndef PEP_SUBJ_KEY
    41 #define PEP_SUBJ_KEY "Subject: "
    42 #define PEP_SUBJ_KEY_LC "subject: "
    43 #define PEP_SUBJ_KEY_LEN 9
    44 #endif
    45 
    46 #ifndef PEP_MSG_WRAP_KEY
    47 #define PEP_MSG_WRAP_KEY "pEp-Wrapped-Message-Info: "
    48 #define PEP_MSG_WRAP_KEY_LC "pep-wrapped-message-info: "
    49 #define PEP_MSG_WRAP_KEY_LEN 26
    50 #endif
    51 
    52 
    53 #include "platform.h"
    54 
    55 #ifdef WIN32
    56 #define LOCAL_DB windoze_local_db()
    57 #define SYSTEM_DB windoze_system_db()
    58 #define LIBGPGME "libgpgme-11.dll"
    59 #else // UNIX
    60 #define _POSIX_C_SOURCE 200809L
    61 #include <dlfcn.h>
    62 #define LOCAL_DB unix_local_db()
    63 #ifndef SYSTEM_DB
    64 #define SYSTEM_DB "/usr/share/pEp/system.db"
    65 #endif
    66 #ifndef LIBGPGME
    67 #define LIBGPGME "libgpgme-pthread.so"
    68 #endif
    69 #endif
    70 
    71 #include <locale.h>
    72 #include <stdlib.h>
    73 #include <string.h>
    74 #include <assert.h>
    75 #include <stdio.h>
    76 #include <ctype.h>
    77 #include <math.h>
    78 
    79 #ifdef SQLITE3_FROM_OS
    80 #include <sqlite3.h>
    81 #else
    82 #include "sqlite3.h"
    83 #endif
    84 
    85 #include "pEpEngine.h"
    86 
    87 // If not specified, build for GPG
    88 #ifndef USE_NETPGP
    89 #ifndef USE_GPG
    90 #define USE_GPG
    91 #endif
    92 #endif
    93 
    94 #ifdef USE_GPG
    95 #include "pgp_gpg_internal.h"
    96 #elif defined(USE_NETPGP)
    97 #include "pgp_netpgp_internal.h"
    98 #endif
    99 
   100 #include "keymanagement.h"
   101 #include "cryptotech.h"
   102 #include "transport.h"
   103 #include "sync.h"
   104 
   105 #define NOT_IMPLEMENTED assert(0); return PEP_UNKNOWN_ERROR;
   106 
   107 struct _pEpSession;
   108 typedef struct _pEpSession pEpSession;
   109 struct _pEpSession {
   110     const char *version;
   111 #ifdef USE_GPG
   112     gpgme_ctx_t ctx;
   113 #elif defined(USE_NETPGP)
   114     pEpNetPGPSession ctx;
   115 #endif
   116 
   117     PEP_cryptotech_t *cryptotech;
   118     PEP_transport_t *transports;
   119 
   120     sqlite3 *db;
   121     sqlite3 *system_db;
   122 
   123     sqlite3_stmt *log;
   124     sqlite3_stmt *trustword;
   125     sqlite3_stmt *get_identity;
   126     sqlite3_stmt *get_identity_without_trust_check;
   127     sqlite3_stmt *get_identities_by_address;
   128     sqlite3_stmt *replace_identities_fpr;
   129     sqlite3_stmt *replace_main_user_fpr;
   130     sqlite3_stmt *get_main_user_fpr;
   131     sqlite3_stmt *refresh_userid_default_key;
   132     sqlite3_stmt *remove_fpr_as_default;
   133     sqlite3_stmt *set_person;
   134     sqlite3_stmt *update_person;    
   135     sqlite3_stmt *set_as_pep_user;
   136     sqlite3_stmt *is_pep_user;
   137     sqlite3_stmt *exists_person;
   138     sqlite3_stmt *set_device_group;
   139     sqlite3_stmt *get_device_group;
   140     sqlite3_stmt *set_pgp_keypair;
   141     sqlite3_stmt *set_identity_entry;
   142     sqlite3_stmt *update_identity_entry;    
   143     sqlite3_stmt *set_identity_flags;
   144     sqlite3_stmt *unset_identity_flags;
   145     sqlite3_stmt *set_trust;
   146     sqlite3_stmt *update_trust;    
   147     sqlite3_stmt *update_trust_for_fpr;
   148     sqlite3_stmt *get_trust;
   149     sqlite3_stmt *least_trust;
   150     sqlite3_stmt *mark_compromized;
   151     sqlite3_stmt *reset_trust;
   152     sqlite3_stmt *crashdump;
   153     sqlite3_stmt *languagelist;
   154     sqlite3_stmt *i18n_token;
   155     sqlite3_stmt *replace_userid;
   156 
   157     // blacklist
   158     sqlite3_stmt *blacklist_add;
   159     sqlite3_stmt *blacklist_delete;
   160     sqlite3_stmt *blacklist_is_listed;
   161     sqlite3_stmt *blacklist_retrieve;
   162     
   163     // Own keys
   164     sqlite3_stmt *own_key_is_listed;
   165     sqlite3_stmt *own_identities_retrieve;
   166     sqlite3_stmt *own_keys_retrieve;
   167     sqlite3_stmt *get_user_default_key;
   168         
   169     sqlite3_stmt *get_default_own_userid;
   170 
   171 //    sqlite3_stmt *set_own_key;
   172 
   173     // sequence value
   174     sqlite3_stmt *sequence_value1;
   175     sqlite3_stmt *sequence_value2;
   176     sqlite3_stmt *sequence_value3;
   177 
   178     // revoked keys
   179     sqlite3_stmt *set_revoked;
   180     sqlite3_stmt *get_revoked;
   181 
   182     // mistrusted
   183     sqlite3_stmt* add_mistrusted_key;
   184     sqlite3_stmt* is_mistrusted_key;    
   185     sqlite3_stmt* delete_mistrusted_key;
   186     
   187     // aliases
   188     sqlite3_stmt *get_userid_alias_default;
   189     sqlite3_stmt *add_userid_alias;
   190 
   191     // callbacks
   192     examine_identity_t examine_identity;
   193     void *examine_management;
   194     void *sync_management;
   195     void *sync_obj;
   196     messageToSend_t messageToSend;
   197     notifyHandshake_t notifyHandshake;
   198     inject_sync_msg_t inject_sync_msg;
   199     retrieve_next_sync_msg_t retrieve_next_sync_msg;
   200 
   201     // key sync
   202     pEpSession* sync_session;
   203     DeviceState_state sync_state;
   204     void* sync_state_payload;
   205     char sync_uuid[37];
   206     time_t LastCannotDecrypt;
   207     time_t LastUpdateRequest;
   208 
   209     // runtime config
   210 
   211     bool passive_mode;
   212     bool unencrypted_subject;
   213     bool keep_sync_msg;
   214     bool service_log;
   215 
   216     // mistrust undo cache
   217     pEp_identity* cached_mistrusted;
   218     
   219 #ifdef DEBUG_ERRORSTACK
   220     stringlist_t* errorstack;
   221 #endif
   222 };
   223 
   224 
   225 PEP_STATUS init_transport_system(PEP_SESSION session, bool in_first);
   226 void release_transport_system(PEP_SESSION session, bool out_last);
   227 
   228 /* NOT to be exposed to the outside!!! */
   229 PEP_STATUS encrypt_only(
   230         PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
   231         size_t psize, char **ctext, size_t *csize
   232 );
   233 
   234 #if defined(NDEBUG) || defined(NOLOG)
   235 #define DEBUG_LOG(TITLE, ENTITY, DESC)
   236 #else
   237 #ifdef ANDROID
   238 #include <android/log.h>
   239 #define  LOG_MORE(...)  __android_log_print(ANDROID_LOG_DEBUG, "pEpEngine", " %s :: %s :: %s :: %s ", __VA_ARGS__);
   240 #else
   241 #include <stdio.h>
   242 #define  LOG_MORE(...)  fprintf(stderr, "pEpEngine DEBUG_LOG('%s','%s','%s','%s')\n", __VA_ARGS__);
   243 #endif
   244 #define DEBUG_LOG(TITLE, ENTITY, DESC) {\
   245     log_event(session, (TITLE), (ENTITY), (DESC), "debug " __FILE__ ":" S_LINE);\
   246     LOG_MORE((TITLE), (ENTITY), (DESC), __FILE__ ":" S_LINE)\
   247 }
   248 #endif
   249 
   250 typedef enum _normalize_hex_rest_t {
   251     accept_hex,
   252     ignore_hex,
   253     reject_hex
   254 } normalize_hex_res_t;
   255 
   256 static inline normalize_hex_res_t _normalize_hex(char *hex) 
   257 {
   258     if (*hex >= '0' && *hex <= '9')
   259         return accept_hex;
   260 
   261     if (*hex >= 'A' && *hex <= 'F') {
   262         *hex += 'a' - 'A';
   263         return accept_hex;
   264     }
   265 
   266     if (*hex >= 'a' && *hex <= 'f') 
   267         return accept_hex;
   268 
   269     if (*hex == ' ') 
   270         return ignore_hex;
   271 
   272     return reject_hex;
   273 }
   274 
   275 // Space tolerant and case insensitive fingerprint string compare
   276 static inline PEP_STATUS _compare_fprs(
   277         const char* fpra,
   278         size_t fpras,
   279         const char* fprb,
   280         size_t fprbs,
   281         int* comparison)
   282 {
   283 
   284     size_t ai = 0;
   285     size_t bi = 0;
   286     size_t significant = 0;
   287     int _comparison = 0;
   288     const int _FULL_FINGERPRINT_LENGTH = 40;
   289    
   290     // First compare every non-ignored chars until an end is reached
   291     while(ai < fpras && bi < fprbs)
   292     {
   293         char fprac = fpra[ai];
   294         char fprbc = fprb[bi];
   295         normalize_hex_res_t fprah = _normalize_hex(&fprac);
   296         normalize_hex_res_t fprbh = _normalize_hex(&fprbc);
   297 
   298         if(fprah == reject_hex || fprbh == reject_hex)
   299             return PEP_ILLEGAL_VALUE;
   300 
   301         if ( fprah == ignore_hex )
   302         {
   303             ai++;
   304         }
   305         else if ( fprbh == ignore_hex )
   306         {
   307             bi++;
   308         }
   309         else
   310         {
   311             if(fprac != fprbc && _comparison == 0 )
   312             {
   313                 _comparison = fprac > fprbc ? 1 : -1;
   314             }
   315 
   316             significant++;
   317             ai++;
   318             bi++;
   319 
   320         } 
   321     }
   322 
   323     // Bail out if we didn't got enough significnt chars
   324     if (significant != _FULL_FINGERPRINT_LENGTH )
   325         return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   326 
   327     // Then purge remaining chars, all must be ignored chars
   328     while ( ai < fpras )
   329     {
   330         char fprac = fpra[ai];
   331         normalize_hex_res_t fprah = _normalize_hex(&fprac);
   332         if( fprah == reject_hex )
   333             return PEP_ILLEGAL_VALUE;
   334         if ( fprah != ignore_hex )
   335             return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   336         ai++;
   337     }
   338     while ( bi < fprbs )
   339     {
   340         char fprbc = fprb[bi];
   341         normalize_hex_res_t fprbh = _normalize_hex(&fprbc);
   342         if( fprbh == reject_hex )
   343             return PEP_ILLEGAL_VALUE;
   344         if ( fprbh != ignore_hex )
   345             return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   346         bi++;
   347     }
   348 
   349     *comparison = _comparison;
   350     return PEP_STATUS_OK;
   351 }
   352 
   353 static inline int _same_fpr(
   354         const char* fpra,
   355         size_t fpras,
   356         const char* fprb,
   357         size_t fprbs
   358     )
   359 {
   360     // illegal values are ignored, and considered not same.
   361     int comparison = 1;
   362 
   363     _compare_fprs(fpra, fpras, fprb, fprbs, &comparison);
   364 
   365     return comparison == 0;
   366 }
   367 
   368 // size is the length of the bytestr that's coming in. This is really only intended
   369 // for comparing two full strings. If charstr's length is different from bytestr_size,
   370 // we'll return a non-zero value.
   371 static inline int _unsigned_signed_strcmp(const unsigned char* bytestr, const char* charstr, int bytestr_size) {
   372     int charstr_len = strlen(charstr);
   373     if (charstr_len != bytestr_size)
   374         return -1; // we don't actually care except that it's non-zero
   375     return memcmp(bytestr, charstr, bytestr_size);
   376 }
   377 
   378 // This is just a horrible example of C type madness. UTF-8 made me do it.
   379 static inline char* _pep_subj_copy() {
   380 #ifndef WIN32
   381     unsigned char pepstr[] = PEP_SUBJ_STRING;
   382     void* retval = calloc(1, sizeof(unsigned char)*PEP_SUBJ_BYTELEN + 1);
   383     memcpy(retval, pepstr, PEP_SUBJ_BYTELEN);
   384     return (char*)retval;
   385 #else
   386     return strdup("pEp");
   387 #endif
   388 }
   389 
   390 static inline bool is_me(PEP_SESSION session, pEp_identity* test_ident) {
   391     bool retval = false;
   392     if (test_ident && test_ident->user_id) {
   393         char* def_id = NULL;
   394         get_default_own_userid(session, &def_id);
   395         if (test_ident->me || 
   396             (def_id && strcmp(def_id, test_ident->user_id) == 0)) {
   397             retval = true;
   398         }
   399         free(def_id);
   400     }
   401     return retval;
   402 }
   403 
   404 #ifndef EMPTYSTR
   405 #define EMPTYSTR(STR) ((STR) == NULL || (STR)[0] == '\0')
   406 #endif
   407 
   408 #ifndef _MIN
   409 #define _MIN(A, B) ((B) > (A) ? (A) : (B))
   410 #endif
   411 #ifndef _MAX
   412 #define _MAX(A, B) ((B) > (A) ? (B) : (A))
   413 #endif
   414 
   415 
   416 // These are globals used in generating message IDs and should only be
   417 // computed once, as they're either really constants or OS-dependent
   418 
   419 extern int _pEp_rand_max_bits;
   420 extern double _pEp_log2_36;
   421 
   422 static inline void _init_globals() {
   423     _pEp_rand_max_bits = ceil(log2(RAND_MAX));
   424     _pEp_log2_36 = log2(36);
   425 }
   426 
   427 #ifdef DEBUG_ERRORSTACK
   428     PEP_STATUS session_add_error(PEP_SESSION session, const char* file, unsigned line, PEP_STATUS status);
   429     #define ADD_TO_LOG(status)   session_add_error(session, __FILE__, __LINE__, (status))
   430     #define GOTO(label)          do{ (void)session_add_error(session, __FILE__, __LINE__, status); goto label; }while(0)
   431 #else
   432     #define ADD_TO_LOG(status)   (status)
   433     #define GOTO(label)          goto label
   434 #endif