src/pEp_internal.h
author Krista Bennett <krista@pep-project.org>
Mon, 22 Jan 2018 11:11:38 +0100
branchENGINE-332
changeset 2433 5ecf504e88eb
parent 2398 2365cdba8783
child 2435 66750e44dc49
permissions -rw-r--r--
ENGINE-332: rewrite complete, but needs checking and testing.
     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 *remove_fpr_as_default;
   132     sqlite3_stmt *set_person;
   133     sqlite3_stmt *set_device_group;
   134     sqlite3_stmt *get_device_group;
   135     sqlite3_stmt *set_pgp_keypair;
   136     sqlite3_stmt *set_identity;
   137     sqlite3_stmt *set_identity_flags;
   138     sqlite3_stmt *unset_identity_flags;
   139     sqlite3_stmt *set_trust;
   140     sqlite3_stmt *update_trust_for_fpr;
   141     sqlite3_stmt *get_trust;
   142     sqlite3_stmt *least_trust;
   143     sqlite3_stmt *mark_compromized;
   144     sqlite3_stmt *reset_trust;
   145     sqlite3_stmt *crashdump;
   146     sqlite3_stmt *languagelist;
   147     sqlite3_stmt *i18n_token;
   148     sqlite3_stmt *replace_userid;
   149 
   150     // blacklist
   151     sqlite3_stmt *blacklist_add;
   152     sqlite3_stmt *blacklist_delete;
   153     sqlite3_stmt *blacklist_is_listed;
   154     sqlite3_stmt *blacklist_retrieve;
   155     
   156     // Own keys
   157     sqlite3_stmt *own_key_is_listed;
   158     sqlite3_stmt *own_identities_retrieve;
   159     sqlite3_stmt *own_keys_retrieve;
   160     sqlite3_stmt *get_user_default_key;
   161         
   162     sqlite3_stmt *get_default_own_userid;
   163 
   164 //    sqlite3_stmt *set_own_key;
   165 
   166     // sequence value
   167     sqlite3_stmt *sequence_value1;
   168     sqlite3_stmt *sequence_value2;
   169     sqlite3_stmt *sequence_value3;
   170 
   171     // revoked keys
   172     sqlite3_stmt *set_revoked;
   173     sqlite3_stmt *get_revoked;
   174 
   175     // aliases
   176     sqlite3_stmt *get_userid_alias_default;
   177     sqlite3_stmt *add_userid_alias;
   178 
   179     // callbacks
   180     examine_identity_t examine_identity;
   181     void *examine_management;
   182     void *sync_management;
   183     void *sync_obj;
   184     messageToSend_t messageToSend;
   185     notifyHandshake_t notifyHandshake;
   186     inject_sync_msg_t inject_sync_msg;
   187     retrieve_next_sync_msg_t retrieve_next_sync_msg;
   188 
   189     // key sync
   190     pEpSession* sync_session;
   191     DeviceState_state sync_state;
   192     void* sync_state_payload;
   193     char sync_uuid[37];
   194     time_t LastCannotDecrypt;
   195     time_t LastUpdateRequest;
   196 
   197     // runtime config
   198 
   199     bool passive_mode;
   200     bool unencrypted_subject;
   201     bool keep_sync_msg;
   202     bool service_log;
   203 
   204     // mistrust undo cache
   205     pEp_identity* cached_mistrusted;
   206     
   207 #ifdef DEBUG_ERRORSTACK
   208     stringlist_t* errorstack;
   209 #endif
   210 };
   211 
   212 
   213 PEP_STATUS init_transport_system(PEP_SESSION session, bool in_first);
   214 void release_transport_system(PEP_SESSION session, bool out_last);
   215 
   216 /* NOT to be exposed to the outside!!! */
   217 PEP_STATUS encrypt_only(
   218         PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
   219         size_t psize, char **ctext, size_t *csize
   220 );
   221 
   222 #if defined(NDEBUG) || defined(NOLOG)
   223 #define DEBUG_LOG(TITLE, ENTITY, DESC)
   224 #else
   225 #ifdef ANDROID
   226 #include <android/log.h>
   227 #define  LOG_MORE(...)  __android_log_print(ANDROID_LOG_DEBUG, "pEpEngine", " %s :: %s :: %s :: %s ", __VA_ARGS__);
   228 #else
   229 #include <stdio.h>
   230 #define  LOG_MORE(...)  fprintf(stderr, "pEpEngine DEBUG_LOG('%s','%s','%s','%s')\n", __VA_ARGS__);
   231 #endif
   232 #define DEBUG_LOG(TITLE, ENTITY, DESC) {\
   233     log_event(session, (TITLE), (ENTITY), (DESC), "debug " __FILE__ ":" S_LINE);\
   234     LOG_MORE((TITLE), (ENTITY), (DESC), __FILE__ ":" S_LINE)\
   235 }
   236 #endif
   237 
   238 typedef enum _normalize_hex_rest_t {
   239     accept_hex,
   240     ignore_hex,
   241     reject_hex
   242 } normalize_hex_res_t;
   243 
   244 static inline normalize_hex_res_t _normalize_hex(char *hex) 
   245 {
   246     if (*hex >= '0' && *hex <= '9')
   247         return accept_hex;
   248 
   249     if (*hex >= 'A' && *hex <= 'F') {
   250         *hex += 'a' - 'A';
   251         return accept_hex;
   252     }
   253 
   254     if (*hex >= 'a' && *hex <= 'f') 
   255         return accept_hex;
   256 
   257     if (*hex == ' ') 
   258         return ignore_hex;
   259 
   260     return reject_hex;
   261 }
   262 
   263 // Space tolerant and case insensitive fingerprint string compare
   264 static inline PEP_STATUS _compare_fprs(
   265         const char* fpra,
   266         size_t fpras,
   267         const char* fprb,
   268         size_t fprbs,
   269         int* comparison)
   270 {
   271 
   272     size_t ai = 0;
   273     size_t bi = 0;
   274     size_t significant = 0;
   275     int _comparison = 0;
   276     const int _FULL_FINGERPRINT_LENGTH = 40;
   277    
   278     // First compare every non-ignored chars until an end is reached
   279     while(ai < fpras && bi < fprbs)
   280     {
   281         char fprac = fpra[ai];
   282         char fprbc = fprb[bi];
   283         normalize_hex_res_t fprah = _normalize_hex(&fprac);
   284         normalize_hex_res_t fprbh = _normalize_hex(&fprbc);
   285 
   286         if(fprah == reject_hex || fprbh == reject_hex)
   287             return PEP_ILLEGAL_VALUE;
   288 
   289         if ( fprah == ignore_hex )
   290         {
   291             ai++;
   292         }
   293         else if ( fprbh == ignore_hex )
   294         {
   295             bi++;
   296         }
   297         else
   298         {
   299             if(fprac != fprbc && _comparison == 0 )
   300             {
   301                 _comparison = fprac > fprbc ? 1 : -1;
   302             }
   303 
   304             significant++;
   305             ai++;
   306             bi++;
   307 
   308         } 
   309     }
   310 
   311     // Bail out if we didn't got enough significnt chars
   312     if (significant != _FULL_FINGERPRINT_LENGTH )
   313         return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   314 
   315     // Then purge remaining chars, all must be ignored chars
   316     while ( ai < fpras )
   317     {
   318         char fprac = fpra[ai];
   319         normalize_hex_res_t fprah = _normalize_hex(&fprac);
   320         if( fprah == reject_hex )
   321             return PEP_ILLEGAL_VALUE;
   322         if ( fprah != ignore_hex )
   323             return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   324         ai++;
   325     }
   326     while ( bi < fprbs )
   327     {
   328         char fprbc = fprb[bi];
   329         normalize_hex_res_t fprbh = _normalize_hex(&fprbc);
   330         if( fprbh == reject_hex )
   331             return PEP_ILLEGAL_VALUE;
   332         if ( fprbh != ignore_hex )
   333             return PEP_TRUSTWORDS_FPR_WRONG_LENGTH;
   334         bi++;
   335     }
   336 
   337     *comparison = _comparison;
   338     return PEP_STATUS_OK;
   339 }
   340 
   341 static inline int _same_fpr(
   342         const char* fpra,
   343         size_t fpras,
   344         const char* fprb,
   345         size_t fprbs
   346     )
   347 {
   348     // illegal values are ignored, and considered not same.
   349     int comparison = 1;
   350 
   351     _compare_fprs(fpra, fpras, fprb, fprbs, &comparison);
   352 
   353     return comparison == 0;
   354 }
   355 
   356 // size is the length of the bytestr that's coming in. This is really only intended
   357 // for comparing two full strings. If charstr's length is different from bytestr_size,
   358 // we'll return a non-zero value.
   359 static inline int _unsigned_signed_strcmp(const unsigned char* bytestr, const char* charstr, int bytestr_size) {
   360     int charstr_len = strlen(charstr);
   361     if (charstr_len != bytestr_size)
   362         return -1; // we don't actually care except that it's non-zero
   363     return memcmp(bytestr, charstr, bytestr_size);
   364 }
   365 
   366 // This is just a horrible example of C type madness. UTF-8 made me do it.
   367 static inline char* _pep_subj_copy() {
   368 #ifndef WIN32
   369     unsigned char pepstr[] = PEP_SUBJ_STRING;
   370     void* retval = calloc(1, sizeof(unsigned char)*PEP_SUBJ_BYTELEN + 1);
   371     memcpy(retval, pepstr, PEP_SUBJ_BYTELEN);
   372     return (char*)retval;
   373 #else
   374     return strdup("pEp");
   375 #endif
   376 }
   377 
   378 static inline bool is_me(PEP_SESSION session, pEp_identity* test_ident) {
   379     bool retval = false;
   380     if (test_ident && test_ident->user_id) {
   381         char* def_id = NULL;
   382         get_default_own_userid(session, &def_id);
   383         if (test_ident->me || 
   384             (def_id && strcmp(def_id, test_ident->user_id) == 0)) {
   385             retval = true;
   386         }
   387         free(def_id);
   388     }
   389     return retval;
   390 }
   391 
   392 // These are globals used in generating message IDs and should only be
   393 // computed once, as they're either really constants or OS-dependent
   394 
   395 int _pEp_rand_max_bits;
   396 double _pEp_log2_36;
   397 
   398 static inline void _init_globals() {
   399     _pEp_rand_max_bits = ceil(log2(RAND_MAX));
   400     _pEp_log2_36 = log2(36);
   401 }
   402 
   403 #ifdef DEBUG_ERRORSTACK
   404     PEP_STATUS session_add_error(PEP_SESSION session, const char* file, unsigned line, PEP_STATUS status);
   405     #define ADD_TO_LOG(status)   session_add_error(session, __FILE__, __LINE__, (status))
   406     #define GOTO(label)          do{ (void)session_add_error(session, __FILE__, __LINE__, status); goto label; }while(0)
   407 #else
   408     #define ADD_TO_LOG(status)   (status)
   409     #define GOTO(label)          goto label
   410 #endif