GateKeeper.cpp
author Volker Birk <vb@pep.foundation>
Fri, 01 Nov 2019 15:06:30 +0100
branchsync
changeset 367 38698c75fbbf
parent 366 f369f8053681
parent 364 2259aa4c6a64
child 370 8be91c5f6570
permissions -rw-r--r--
merging
vb@88
     1
#include "stdafx.h"
vb@88
     2
vb@88
     3
#include "GateKeeper.h"
vb@110
     4
#include "pEpCOMServerAdapter.h"
vb@123
     5
#include "utf8_helper.h"
vb@88
     6
vb@88
     7
using namespace std;
vb@88
     8
vb@130
     9
// from https://msdn.microsoft.com/en-us/library/windows/desktop/dd388945(v=vs.85).aspx
vb@123
    10
vb@123
    11
struct PUBLIC_KEY_VALUES {
vb@123
    12
    BLOBHEADER blobheader;
vb@123
    13
    RSAPUBKEY rsapubkey;
vb@123
    14
    BYTE modulus[4096];
vb@123
    15
};
vb@123
    16
vb@123
    17
static void ReverseMemCopy(
vb@123
    18
    _Out_ BYTE       *pbDest,
vb@123
    19
    _In_  BYTE const *pbSource,
vb@123
    20
    _In_  DWORD       cb
markus@269
    21
)
vb@123
    22
{
vb@123
    23
    for (DWORD i = 0; i < cb; i++) {
vb@123
    24
        pbDest[cb - 1 - i] = pbSource[i];
vb@123
    25
    }
vb@123
    26
}
vb@123
    27
vb@123
    28
static NTSTATUS ImportRsaPublicKey(
vb@123
    29
    _In_ BCRYPT_ALG_HANDLE  hAlg,    // CNG provider
vb@123
    30
    _In_ PUBLIC_KEY_VALUES *pKey,    // Pointer to the RSAPUBKEY blob.
vb@123
    31
    _In_ BCRYPT_KEY_HANDLE *phKey    // Receives a handle the imported public key.
markus@269
    32
)
vb@123
    33
{
vb@123
    34
    NTSTATUS hr = 0;
vb@123
    35
vb@123
    36
    BYTE *pbPublicKey = NULL;
vb@123
    37
    DWORD cbKey = 0;
vb@123
    38
vb@123
    39
    // Layout of the RSA public key blob:
vb@123
    40
vb@123
    41
    //  +----------------------------------------------------------------+
vb@123
    42
    //  |     BCRYPT_RSAKEY_BLOB    | BE( dwExp ) |   BE( Modulus )      |
vb@123
    43
    //  +----------------------------------------------------------------+
vb@123
    44
    //
vb@123
    45
    //  sizeof(BCRYPT_RSAKEY_BLOB)       cbExp           cbModulus 
vb@123
    46
    //  <--------------------------><------------><---------------------->
vb@123
    47
    //
vb@123
    48
    //   BE = Big Endian Format                                                     
vb@123
    49
vb@123
    50
    DWORD cbModulus = (pKey->rsapubkey.bitlen + 7) / 8;
vb@123
    51
    DWORD dwExp = pKey->rsapubkey.pubexp;
vb@123
    52
    DWORD cbExp = (dwExp & 0xFF000000) ? 4 :
vb@123
    53
        (dwExp & 0x00FF0000) ? 3 :
vb@123
    54
        (dwExp & 0x0000FF00) ? 2 : 1;
vb@123
    55
vb@123
    56
    BCRYPT_RSAKEY_BLOB *pRsaBlob;
vb@123
    57
    PBYTE pbCurrent;
vb@123
    58
vb@123
    59
    if (!SUCCEEDED(hr = DWordAdd(cbModulus, sizeof(BCRYPT_RSAKEY_BLOB), &cbKey))) {
vb@123
    60
        goto cleanup;
vb@123
    61
    }
vb@123
    62
vb@123
    63
    cbKey += cbExp;
vb@123
    64
markus@269
    65
    pbPublicKey = (PBYTE)CoTaskMemAlloc(cbKey);
vb@123
    66
    if (pbPublicKey == NULL) {
vb@123
    67
        hr = E_OUTOFMEMORY;
vb@123
    68
        goto cleanup;
vb@123
    69
    }
vb@123
    70
vb@123
    71
    ZeroMemory(pbPublicKey, cbKey);
markus@269
    72
    pRsaBlob = (BCRYPT_RSAKEY_BLOB *)(pbPublicKey);
vb@123
    73
vb@123
    74
    //
vb@123
    75
    // Make the Public Key Blob Header
vb@123
    76
    //
vb@123
    77
vb@123
    78
    pRsaBlob->Magic = BCRYPT_RSAPUBLIC_MAGIC;
vb@123
    79
    pRsaBlob->BitLength = pKey->rsapubkey.bitlen;
vb@123
    80
    pRsaBlob->cbPublicExp = cbExp;
vb@123
    81
    pRsaBlob->cbModulus = cbModulus;
vb@123
    82
    pRsaBlob->cbPrime1 = 0;
vb@123
    83
    pRsaBlob->cbPrime2 = 0;
vb@123
    84
markus@269
    85
    pbCurrent = (PBYTE)(pRsaBlob + 1);
vb@123
    86
vb@123
    87
    //
vb@123
    88
    // Copy pubExp Big Endian 
vb@123
    89
    //
vb@123
    90
markus@269
    91
    ReverseMemCopy(pbCurrent, (PBYTE)&dwExp, cbExp);
vb@123
    92
    pbCurrent += cbExp;
vb@123
    93
vb@123
    94
    //
vb@123
    95
    // Copy Modulus Big Endian 
vb@123
    96
    //
vb@123
    97
vb@123
    98
    ReverseMemCopy(pbCurrent, pKey->modulus, cbModulus);
vb@123
    99
vb@123
   100
    //
vb@123
   101
    // Import the public key
vb@123
   102
    //
vb@123
   103
markus@269
   104
    hr = BCryptImportKeyPair(hAlg, NULL, BCRYPT_RSAPUBLIC_BLOB, phKey, (PUCHAR)pbPublicKey, cbKey, 0);
vb@123
   105
vb@123
   106
cleanup:
vb@123
   107
    CoTaskMemFree(pbPublicKey);
vb@123
   108
    return hr;
vb@123
   109
}
vb@123
   110
vb@96
   111
namespace pEp {
vb@96
   112
    const LPCTSTR GateKeeper::plugin_reg_path = _T("Software\\Microsoft\\Office\\Outlook\\Addins\\pEp");
vb@96
   113
    const LPCTSTR GateKeeper::plugin_reg_value_name = _T("LoadBehavior");
vb@135
   114
    const LPCTSTR GateKeeper::updater_reg_path = _T("Software\\pEp\\Updater");
vb@96
   115
vb@96
   116
    const time_t GateKeeper::cycle = 7200;   // 7200 sec is 2 h
vb@137
   117
    const time_t GateKeeper::fraction = 10;  // first update is at 10% of cycle
markus@284
   118
    const chrono::seconds GateKeeper::waiting = 10s; //  10 sec
vb@88
   119
vb@117
   120
    GateKeeper::GateKeeper(CpEpCOMServerAdapterModule * self)
vb@228
   121
        : _self(self), now(time(NULL)), next(now /*+ time_diff()*/), hkUpdater(NULL),
markus@269
   122
        internet(NULL), hAES(NULL), hRSA(NULL)
vb@96
   123
    {
vb@366
   124
		if (the_gatekeeper)
vb@366
   125
			throw runtime_error("second instance of GateKeeper was initialized");
vb@366
   126
markus@269
   127
        DeleteFile(get_lockFile().c_str());
vb@208
   128
vb@96
   129
        LONG lResult = RegOpenCurrentUser(KEY_READ, &cu);
vb@96
   130
        assert(lResult == ERROR_SUCCESS);
vb@96
   131
        if (lResult == ERROR_SUCCESS)
vb@96
   132
            cu_open = true;
vb@96
   133
        else
vb@96
   134
            cu_open = false;
vb@88
   135
vb@96
   136
        if (cu_open) {
vb@96
   137
            LONG lResult = RegOpenKeyEx(cu, updater_reg_path, 0, KEY_READ, &hkUpdater);
markus@269
   138
            if (lResult != ERROR_SUCCESS)
markus@269
   139
                RegCreateKeyEx(cu, updater_reg_path, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ, NULL, &hkUpdater, NULL);
markus@269
   140
        }
vb@366
   141
vb@366
   142
		the_gatekeeper = this;
vb@96
   143
    }
markus@269
   144
vb@96
   145
    GateKeeper::~GateKeeper()
vb@96
   146
    {
vb@366
   147
		the_gatekeeper = nullptr;
vb@366
   148
vb@96
   149
        if (cu_open) {
vb@96
   150
            if (hkUpdater)
vb@96
   151
                RegCloseKey(hkUpdater);
vb@96
   152
            RegCloseKey(cu);
vb@96
   153
        }
vb@96
   154
    }
vb@88
   155
vb@96
   156
    time_t GateKeeper::time_diff()
vb@96
   157
    {
vb@96
   158
        try {
vb@96
   159
            static random_device rd;
vb@96
   160
            static mt19937 gen(rd());
vb@88
   161
markus@269
   162
            uniform_int_distribution<time_t> dist(0, cycle / fraction);
vb@96
   163
vb@96
   164
            return dist(gen);
vb@96
   165
        }
vb@96
   166
        catch (exception&) {
vb@96
   167
            assert(0);
vb@96
   168
            return 0;
vb@96
   169
        }
vb@88
   170
    }
vb@96
   171
vb@96
   172
    void GateKeeper::keep()
vb@96
   173
    {
vb@96
   174
        if (!cu_open)
vb@96
   175
            return;
vb@96
   176
vb@96
   177
        while (1) {
vb@96
   178
            keep_plugin();
vb@96
   179
vb@96
   180
            now = time(NULL);
vb@96
   181
            assert(now != -1);
vb@96
   182
vb@366
   183
            if (now > next) {
vb@96
   184
                next = now + GateKeeper::cycle;
vb@96
   185
                keep_updated();
vb@134
   186
            }
markus@284
   187
        }
markus@284
   188
    }
vb@96
   189
vb@96
   190
    void GateKeeper::keep_plugin()
vb@96
   191
    {
markus@269
   192
        HKEY hkPluginStart = NULL;
vb@141
   193
vb@141
   194
        LONG lResult = RegOpenKeyEx(cu, plugin_reg_path, 0, KEY_WRITE, &hkPluginStart);
vb@96
   195
        if (lResult != ERROR_SUCCESS)
vb@96
   196
            return;
vb@96
   197
vb@141
   198
        DWORD v = 3;
markus@269
   199
        lResult = RegSetValueEx(hkPluginStart, plugin_reg_value_name, 0, REG_DWORD, (const BYTE *)&v, sizeof(DWORD));
vb@141
   200
        assert(lResult == ERROR_SUCCESS);
vb@141
   201
vb@141
   202
        RegCloseKey(hkPluginStart);
vb@96
   203
    }
vb@96
   204
vb@111
   205
    string GateKeeper::update_key()
vb@110
   206
    {
vb@110
   207
        static string key;
vb@110
   208
vb@110
   209
        if (key.length() == 0) {
vb@110
   210
            HRSRC res = FindResource(_self->hModule(), MAKEINTRESOURCE(IRD_UPDATEKEY), RT_RCDATA);
vb@110
   211
            assert(res);
vb@110
   212
            if (!res)
vb@110
   213
                throw runtime_error("FindResource: IRD_UPDATEKEY");
vb@110
   214
vb@110
   215
            HGLOBAL hRes = LoadResource(_self->hModule(), res);
vb@110
   216
            assert(hRes);
vb@110
   217
            if (!hRes)
vb@110
   218
                throw runtime_error("LoadResource: IRD_UPDATEKEY");
vb@110
   219
vb@110
   220
            key = string((char *)LockResource(hRes), SizeofResource(_self->hModule(), res));
vb@110
   221
            UnlockResource(hRes);
vb@110
   222
        }
vb@110
   223
vb@110
   224
        return key;
vb@110
   225
    }
vb@110
   226
vb@116
   227
    BCRYPT_KEY_HANDLE GateKeeper::delivery_key()
vb@112
   228
    {
vb@112
   229
        aeskey_t key;
vb@112
   230
vb@112
   231
        static random_device rd;
vb@112
   232
        static mt19937 gen(rd());
vb@112
   233
vb@123
   234
        uniform_int_distribution<int64_t> dist(0, UINT32_MAX);
vb@112
   235
vb@123
   236
        for (int i = 0; i < 8; i++)
markus@269
   237
            key.dw_key[i] = (uint32_t)dist(gen);
vb@113
   238
vb@116
   239
        BCRYPT_KEY_HANDLE hKey;
vb@142
   240
markus@269
   241
        NTSTATUS status = BCryptGenerateSymmetricKey(hAES, &hKey, NULL, 0, (PUCHAR)&key, (ULONG) sizeof(aeskey_t), 0);
vb@116
   242
        assert(status == 0);
vb@116
   243
        if (status)
vb@116
   244
            throw runtime_error("BCryptGenerateSymmetricKey");
vb@116
   245
vb@142
   246
#ifndef NDEBUG
vb@131
   247
        DWORD keylength = 0;
vb@131
   248
        ULONG copied = 0;
markus@269
   249
        status = BCryptGetProperty(hKey, BCRYPT_KEY_LENGTH, (PUCHAR)&keylength, sizeof(DWORD), &copied, 0);
vb@131
   250
        assert(keylength == 256);
vb@142
   251
#endif
vb@131
   252
vb@116
   253
        return hKey;
vb@113
   254
    }
vb@113
   255
vb@121
   256
    string GateKeeper::wrapped_delivery_key(BCRYPT_KEY_HANDLE hDeliveryKey)
vb@113
   257
    {
vb@113
   258
        string result;
vb@113
   259
vb@299
   260
        BCRYPT_KEY_HANDLE hUpdateKey = NULL;
vb@117
   261
        string _update_key = update_key();
vb@113
   262
vb@299
   263
        PCERT_PUBLIC_KEY_INFO uk = NULL;
vb@299
   264
        DWORD uk_size = 0;
vb@142
   265
vb@123
   266
        BOOL bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO,
markus@269
   267
            (const BYTE *)_update_key.data(), _update_key.size(), CRYPT_DECODE_ALLOC_FLAG, NULL, &uk, &uk_size);
vb@123
   268
        if (!bResult)
vb@123
   269
            throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
vb@123
   270
vb@299
   271
        PUBLIC_KEY_VALUES *_uk = NULL;
vb@299
   272
        DWORD _uk_size = 0;
vb@142
   273
vb@123
   274
        bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB,
vb@123
   275
            uk->PublicKey.pbData, uk->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &_uk, &_uk_size);
vb@123
   276
        LocalFree(uk);
vb@123
   277
        if (!bResult)
vb@123
   278
            throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
vb@123
   279
vb@123
   280
        HRESULT hResult = ImportRsaPublicKey(hRSA, _uk, &hUpdateKey);
vb@123
   281
        LocalFree(_uk);
vb@302
   282
        if (!hUpdateKey)
vb@123
   283
            throw runtime_error("ImportRsaPublicKey");
vb@117
   284
vb@129
   285
        ULONG psize;
vb@129
   286
        NTSTATUS status = BCryptGetProperty(hUpdateKey, BCRYPT_ALGORITHM_NAME, NULL, 0, &psize, 0);
vb@129
   287
        char *prop = new char[psize];
markus@269
   288
        TCHAR *_prop = (TCHAR *)prop;
vb@299
   289
        status = BCryptGetProperty(hUpdateKey, BCRYPT_ALGORITHM_NAME, (PUCHAR)prop, psize, &psize, 0);
vb@302
   290
        if (status)
vb@302
   291
            throw runtime_error("BCryptGetProperty: BCRYPT_ALGORITHM_NAME");
vb@129
   292
vb@129
   293
        ULONG export_size;
vb@129
   294
        status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, NULL, NULL,
vb@129
   295
            &export_size, 0);
vb@129
   296
        if (status)
vb@129
   297
            throw runtime_error("BCryptExportKey: measuring export size");
vb@129
   298
vb@129
   299
        PUCHAR _delivery_key = new UCHAR[export_size];
vb@120
   300
        ULONG copied;
vb@129
   301
        status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, _delivery_key, export_size,
markus@269
   302
            &copied, 0);
vb@129
   303
        if (status) {
vb@129
   304
            delete[] _delivery_key;
vb@120
   305
            throw runtime_error("BCryptExportKey: delivery_key");
vb@129
   306
        }
vb@120
   307
vb@117
   308
        BCRYPT_OAEP_PADDING_INFO pi;
vb@119
   309
        memset(&pi, 0, sizeof(BCRYPT_OAEP_PADDING_INFO));
vb@117
   310
        pi.pszAlgId = BCRYPT_SHA256_ALGORITHM;
vb@117
   311
vb@301
   312
        ULONG result_size = 0;
vb@118
   313
        PUCHAR _result = NULL;
vb@129
   314
        ULONG blob_size = export_size - sizeof(BCRYPT_KEY_DATA_BLOB_HEADER);
vb@129
   315
        PUCHAR blob = _delivery_key + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER);
vb@129
   316
        status = BCryptEncrypt(hUpdateKey, blob, blob_size, &pi, NULL, 0, NULL, 0, &result_size, BCRYPT_PAD_OAEP);
vb@119
   317
        if (status) {
vb@129
   318
            delete[] _delivery_key;
vb@119
   319
            BCryptDestroyKey(hUpdateKey);
vb@117
   320
            throw runtime_error("BCryptEncrypt: calculating result size");
vb@119
   321
        }
vb@117
   322
vb@301
   323
        _result = new UCHAR[result_size + 1];
vb@129
   324
        status = BCryptEncrypt(hUpdateKey, blob, blob_size, &pi, NULL, 0, _result, result_size, &copied, BCRYPT_PAD_OAEP);
vb@129
   325
        delete[] _delivery_key;
vb@119
   326
        if (status) {
vb@119
   327
            BCryptDestroyKey(hUpdateKey);
vb@119
   328
            delete[] _result;
vb@118
   329
            throw runtime_error("BCryptEncrypt: encrypting using update_key");
vb@119
   330
        }
vb@117
   331
vb@120
   332
        BCryptDestroyKey(hUpdateKey);
vb@120
   333
vb@117
   334
        stringstream s;
vb@129
   335
        for (ULONG i = 0; i < copied; i++) {
vb@129
   336
            s << hex << setw(2) << setfill('0');
markus@269
   337
            s << (int)_result[i];
vb@129
   338
        }
vb@117
   339
        delete[] _result;
vb@117
   340
        s >> result;
vb@117
   341
vb@113
   342
        return result;
vb@112
   343
    }
vb@112
   344
vb@214
   345
    GateKeeper::product_list GateKeeper::registered_products()
vb@96
   346
    {
vb@214
   347
        product_list products;
vb@88
   348
vb@96
   349
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724872(v=vs.85).aspx
vb@300
   350
        static TCHAR value_name[16384];
vb@96
   351
        DWORD value_name_size;
vb@300
   352
        static TCHAR value[L_MAX_URL_LENGTH + 1];
vb@96
   353
        DWORD value_size;
vb@88
   354
vb@96
   355
        LONG lResult = ERROR_SUCCESS;
vb@96
   356
        for (DWORD i = 0; lResult == ERROR_SUCCESS; i++) {
vb@138
   357
            value_name_size = 16383;
vb@96
   358
            value_size = L_MAX_URL_LENGTH + 1;
markus@269
   359
            lResult = RegEnumValue(hkUpdater, i, value_name, &value_name_size, NULL, NULL, (LPBYTE)value, &value_size);
vb@139
   360
            if (lResult == ERROR_SUCCESS) {
vb@96
   361
                products.push_back({ value_name, value });
vb@139
   362
            }
vb@88
   363
        }
vb@88
   364
vb@96
   365
        return products;
vb@88
   366
    }
vb@88
   367
Thomas@360
   368
    void GateKeeper::execute_file(tstring filename)
vb@126
   369
    {
markus@269
   370
        HANDLE hMutex = CreateMutex(NULL, TRUE, _T("PEPINSTALLERMUTEX"));
markus@269
   371
        if (hMutex) {
markus@269
   372
            CloseHandle(hMutex);
markus@269
   373
            ShellExecute(NULL, _T("open"), filename.c_str(), NULL, NULL, SW_SHOW);
markus@269
   374
        }
vb@126
   375
    }
vb@126
   376
markus@269
   377
    tstring GateKeeper::get_lockFile()
markus@269
   378
    {
markus@269
   379
        static const tstring _fileName = _T("\\pEpSetup.lck");
markus@269
   380
        static tstring fileName;
vb@207
   381
markus@269
   382
        if (fileName.length() == 0) {
markus@269
   383
            unique_ptr < TCHAR[] > _pathName(new TCHAR[MAX_PATH + 1]);
markus@269
   384
            DWORD size = GetTempPath(MAX_PATH, _pathName.get());
markus@269
   385
            if (size > MAX_PATH - _fileName.size())
markus@269
   386
                throw runtime_error("TEMP path too long");
vb@207
   387
markus@269
   388
            fileName = _pathName.get();
markus@269
   389
            fileName += _fileName;
markus@269
   390
        }
vb@207
   391
markus@269
   392
        return fileName;
markus@269
   393
    }
vb@208
   394
Thomas@364
   395
    // Retrieving Headers Using HTTP_QUERY_CUSTOM
Thomas@364
   396
    static tstring httpQueryCustom(HINTERNET hHttp, tstring header)
Thomas@364
   397
    {
Thomas@364
   398
        DWORD dwResult = 0;
Thomas@364
   399
        LPTSTR lpOutBuffer = StrDup(header.c_str());
Thomas@361
   400
Thomas@364
   401
    retry:
Thomas@361
   402
Thomas@364
   403
        if (!HttpQueryInfo(hHttp, HTTP_QUERY_CUSTOM, (LPVOID)lpOutBuffer, &dwResult, NULL))
Thomas@364
   404
        {
Thomas@364
   405
            if (GetLastError() == ERROR_HTTP_HEADER_NOT_FOUND)
Thomas@364
   406
            {
Thomas@364
   407
                // Code to handle the case where the header isn't available.
Thomas@364
   408
                LocalFree(lpOutBuffer);
Thomas@364
   409
                throw(runtime_error("ERROR_HTTP_HEADER_NOT_FOUND"));
Thomas@364
   410
            }
Thomas@364
   411
            else
Thomas@364
   412
            {
Thomas@364
   413
                // Check for an insufficient buffer.
Thomas@364
   414
                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
Thomas@364
   415
                {
Thomas@364
   416
                    // Allocate the necessary buffer.
Thomas@364
   417
                    LocalFree(lpOutBuffer);
Thomas@364
   418
                    lpOutBuffer = (LPTSTR)LocalAlloc(LMEM_FIXED, dwResult + 1);
Thomas@361
   419
Thomas@364
   420
                    // Rewrite the header name in the buffer.
Thomas@364
   421
                    StringCchPrintf(lpOutBuffer, dwResult, header.c_str());
Thomas@361
   422
Thomas@364
   423
                    // Retry the call.
Thomas@364
   424
                    goto retry;
Thomas@364
   425
                }
Thomas@364
   426
                else
Thomas@364
   427
                {
Thomas@364
   428
                    // Error handling code.
Thomas@364
   429
                    LocalFree(lpOutBuffer);
Thomas@364
   430
                    // FIXME: Add GetLastError()
Thomas@364
   431
                    throw(runtime_error("Unknown"));
Thomas@364
   432
                }
Thomas@364
   433
            }
Thomas@364
   434
        }
Thomas@361
   435
Thomas@364
   436
        tstring result(lpOutBuffer);
Thomas@364
   437
        LocalFree(lpOutBuffer);
Thomas@361
   438
Thomas@364
   439
        return result;
Thomas@364
   440
    }
Thomas@361
   441
vb@363
   442
    bool GateKeeper::update_product(product p, DWORD context)
vb@208
   443
    {
markus@269
   444
        {
markus@269
   445
            HANDLE file = CreateFile(get_lockFile().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
markus@269
   446
            if (file == INVALID_HANDLE_VALUE) {
vb@363
   447
                return false;
markus@269
   448
            }
markus@269
   449
            else {
markus@269
   450
                CloseHandle(file);
markus@269
   451
                DeleteFile(get_lockFile().c_str());
markus@269
   452
            }
markus@269
   453
        }
vb@199
   454
vb@127
   455
        BCRYPT_KEY_HANDLE dk = delivery_key();
vb@126
   456
#ifdef UNICODE
vb@127
   457
        tstring delivery = utility::utf16_string(wrapped_delivery_key(dk));
vb@126
   458
#else
vb@126
   459
        tstring delivery = wrapped_delivery_key(delivery_key());
vb@126
   460
#endif
vb@124
   461
        tstring url = p.second;
vb@124
   462
        url += _T("&challenge=");
vb@124
   463
        url += delivery;
vb@124
   464
        tstring headers;
vb@124
   465
        HINTERNET hUrl = InternetOpenUrl(internet, url.c_str(), headers.c_str(), headers.length(),
markus@269
   466
            INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE, context);
vb@97
   467
        if (hUrl == NULL)
vb@363
   468
            return false;
vb@94
   469
vb@127
   470
        string crypted;
vb@127
   471
        string unencrypted;
vb@133
   472
        UCHAR iv[12];
vb@133
   473
        UCHAR nonce[sizeof(iv)];
vb@133
   474
        UCHAR tag[16];
vb@138
   475
        tstring filename;
vb@138
   476
        HANDLE hFile = NULL;
vb@138
   477
        char *unencrypted_buffer = NULL;
Thomas@364
   478
        bool result = false;
vb@107
   479
vb@130
   480
        try {
Thomas@361
   481
vb@133
   482
            DWORD reading;
vb@133
   483
            InternetReadFile(hUrl, iv, sizeof(iv), &reading);
vb@133
   484
vb@133
   485
            if (reading) do {
markus@269
   486
                static char buffer[1024 * 1024];
markus@269
   487
                BOOL bResult = InternetReadFile(hUrl, buffer, 1024 * 1024, &reading);
vb@130
   488
                if (!bResult || !reading)
vb@130
   489
                    break;
vb@130
   490
                crypted += string(buffer, reading);
vb@130
   491
            } while (1);
vb@279
   492
Thomas@364
   493
            tstring contentDisposition = httpQueryCustom(hUrl, _T("Content-Disposition"));
Thomas@361
   494
Thomas@364
   495
            tregex filenameRegex(_T("filename=.([^\"]*)"), regex::extended); //FIXME: case insensitive
Thomas@364
   496
            tsmatch match;
Thomas@361
   497
Thomas@364
   498
            if (regex_search(contentDisposition, match, filenameRegex)) {
Thomas@364
   499
                filename = match[1];
Thomas@364
   500
            }
Thomas@361
   501
vb@279
   502
            InternetCloseHandle(hUrl);
vb@279
   503
            hUrl = NULL;
vb@279
   504
vb@279
   505
            memcpy(nonce, iv, sizeof(iv));
vb@279
   506
vb@279
   507
            BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo;
vb@279
   508
            BCRYPT_INIT_AUTH_MODE_INFO(authInfo);
vb@279
   509
            authInfo.pbNonce = nonce;
vb@279
   510
            authInfo.cbNonce = sizeof(nonce);
vb@279
   511
            authInfo.pbTag = tag;
vb@279
   512
            authInfo.cbTag = sizeof(tag);
vb@279
   513
vb@279
   514
            ULONG unencrypted_size;
vb@279
   515
            NTSTATUS status = BCryptDecrypt(dk, (PUCHAR)crypted.data(), crypted.size(),
vb@279
   516
                &authInfo, iv, sizeof(iv), NULL, 0, &unencrypted_size, 0);
vb@279
   517
            if (status)
vb@279
   518
                goto closing;
vb@279
   519
vb@279
   520
            unencrypted_buffer = new char[unencrypted_size];
vb@279
   521
vb@279
   522
            PUCHAR crypted_data = (PUCHAR)crypted.data();
vb@279
   523
            ULONG crypted_size = (ULONG)crypted.size() - sizeof(tag);
vb@279
   524
            memcpy(tag, crypted_data + crypted_size, sizeof(tag));
vb@279
   525
vb@279
   526
            status = BCryptDecrypt(dk, crypted_data, crypted_size,
vb@279
   527
                &authInfo, iv, sizeof(iv), (PUCHAR)unencrypted_buffer, unencrypted_size, &unencrypted_size, 0);
vb@279
   528
            if (status)
vb@279
   529
                goto closing;
vb@279
   530
vb@279
   531
            BCryptDestroyKey(dk);
vb@279
   532
vb@279
   533
            TCHAR temp_path[MAX_PATH + 1];
vb@279
   534
            GetTempPath(MAX_PATH, temp_path);
Thomas@361
   535
Thomas@364
   536
            if (filename == _T("")) {
Thomas@364
   537
                filename = temp_path;
Thomas@364
   538
                filename += _T("\\pEp_");
Thomas@364
   539
                filename += delivery.substr(0, 32);
Thomas@364
   540
                filename += _T(".msi");
Thomas@364
   541
            }
Thomas@364
   542
            else {
Thomas@364
   543
                filename = tstring(temp_path) + _T("\\") + filename;
Thomas@364
   544
            }
vb@279
   545
vb@279
   546
            hFile = CreateFile(filename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
vb@279
   547
            if (!hFile)
vb@279
   548
                goto closing;
vb@279
   549
            DWORD writing;
vb@279
   550
            WriteFile(hFile, unencrypted_buffer, unencrypted_size, &writing, NULL);
vb@279
   551
            CloseHandle(hFile);
Thomas@364
   552
            hFile = NULL;
vb@279
   553
            delete[] unencrypted_buffer;
vb@279
   554
            unencrypted_buffer = nullptr;
vb@130
   555
        }
vb@138
   556
        catch (exception&) {
vb@138
   557
            goto closing;
vb@130
   558
        }
vb@133
   559
Thomas@360
   560
        execute_file(filename);
Thomas@364
   561
        result = true;
vb@127
   562
vb@126
   563
    closing:
vb@127
   564
        if (unencrypted_buffer)
vb@127
   565
            delete[] unencrypted_buffer;
vb@126
   566
        if (hFile)
vb@126
   567
            CloseHandle(hFile);
vb@126
   568
        if (hUrl)
vb@126
   569
            InternetCloseHandle(hUrl);
vb@127
   570
        BCryptDestroyKey(dk);
vb@363
   571
Thomas@364
   572
        return result;
vb@96
   573
    }
vb@88
   574
vb@96
   575
    void GateKeeper::keep_updated()
vb@96
   576
    {
vb@116
   577
        NTSTATUS status = BCryptOpenAlgorithmProvider(&hAES, BCRYPT_AES_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
vb@116
   578
        assert(status == 0);
vb@116
   579
        if (status)
vb@116
   580
            goto closing;
markus@269
   581
        status = BCryptSetProperty(hAES, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_GCM, sizeof(BCRYPT_CHAIN_MODE_GCM), 0);
vb@128
   582
        if (status)
vb@128
   583
            goto closing;
vb@116
   584
vb@116
   585
        status = BCryptOpenAlgorithmProvider(&hRSA, BCRYPT_RSA_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
vb@116
   586
        assert(status == 0);
vb@116
   587
        if (status)
vb@116
   588
            goto closing;
vb@116
   589
vb@124
   590
        internet = InternetOpen(_T("pEp"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
vb@124
   591
        if (!internet)
vb@124
   592
            goto closing;
vb@97
   593
markus@269
   594
        {
markus@269
   595
            product_list products = registered_products();
markus@269
   596
            DWORD context = 0;
vb@138
   597
markus@269
   598
            for (auto i = products.begin(); i != products.end(); i++) {
markus@269
   599
                try {
markus@269
   600
                    update_product(*i, context++);
markus@269
   601
                }
markus@269
   602
                catch (exception&) {
vb@214
   603
markus@269
   604
                }
markus@269
   605
            }
markus@269
   606
        }
vb@97
   607
vb@116
   608
    closing:
vb@116
   609
        if (internet)
vb@116
   610
            InternetCloseHandle(internet);
vb@116
   611
        if (hAES)
vb@116
   612
            BCryptCloseAlgorithmProvider(hAES, 0);
vb@116
   613
        if (hRSA)
vb@116
   614
            BCryptCloseAlgorithmProvider(hRSA, 0);
vb@97
   615
        internet = NULL;
vb@116
   616
        hAES = NULL;
vb@116
   617
        hRSA = NULL;
vb@96
   618
    }
vb@88
   619
vb@366
   620
	GateKeeper *GateKeeper::the_gatekeeper = nullptr;
vb@366
   621
vb@96
   622
} // namespace pEp