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