GateKeeper.cpp
author Thomas
Fri, 11 Oct 2019 18:02:20 +0200
branchsync
changeset 361 7cf83867e018
parent 360 57c7ace37425
child 362 088a701f8a8f
permissions -rw-r--r--
Execute all file types when updating
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 {
markus@284
   112
    std::mutex GateKeeper::update_wait_mtx;
markus@284
   113
    std::condition_variable GateKeeper::update_wait_var;
markus@284
   114
    bool GateKeeper::update_wait_forced = false;
vb@96
   115
vb@96
   116
    const LPCTSTR GateKeeper::plugin_reg_path = _T("Software\\Microsoft\\Office\\Outlook\\Addins\\pEp");
vb@96
   117
    const LPCTSTR GateKeeper::plugin_reg_value_name = _T("LoadBehavior");
vb@135
   118
    const LPCTSTR GateKeeper::updater_reg_path = _T("Software\\pEp\\Updater");
vb@96
   119
vb@96
   120
    const time_t GateKeeper::cycle = 7200;   // 7200 sec is 2 h
vb@137
   121
    const time_t GateKeeper::fraction = 10;  // first update is at 10% of cycle
markus@284
   122
    const chrono::seconds GateKeeper::waiting = 10s; //  10 sec
vb@88
   123
vb@117
   124
    GateKeeper::GateKeeper(CpEpCOMServerAdapterModule * self)
vb@228
   125
        : _self(self), now(time(NULL)), next(now /*+ time_diff()*/), hkUpdater(NULL),
markus@269
   126
        internet(NULL), hAES(NULL), hRSA(NULL)
vb@96
   127
    {
markus@269
   128
        DeleteFile(get_lockFile().c_str());
vb@208
   129
vb@96
   130
        LONG lResult = RegOpenCurrentUser(KEY_READ, &cu);
vb@96
   131
        assert(lResult == ERROR_SUCCESS);
vb@96
   132
        if (lResult == ERROR_SUCCESS)
vb@96
   133
            cu_open = true;
vb@96
   134
        else
vb@96
   135
            cu_open = false;
vb@88
   136
vb@96
   137
        if (cu_open) {
vb@96
   138
            LONG lResult = RegOpenKeyEx(cu, updater_reg_path, 0, KEY_READ, &hkUpdater);
markus@269
   139
            if (lResult != ERROR_SUCCESS)
markus@269
   140
                RegCreateKeyEx(cu, updater_reg_path, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ, NULL, &hkUpdater, NULL);
markus@269
   141
        }
vb@96
   142
    }
markus@269
   143
vb@96
   144
    GateKeeper::~GateKeeper()
vb@96
   145
    {
vb@96
   146
        if (cu_open) {
vb@96
   147
            if (hkUpdater)
vb@96
   148
                RegCloseKey(hkUpdater);
vb@96
   149
            RegCloseKey(cu);
vb@96
   150
        }
vb@96
   151
    }
vb@88
   152
vb@96
   153
    time_t GateKeeper::time_diff()
vb@96
   154
    {
vb@96
   155
        try {
vb@96
   156
            static random_device rd;
vb@96
   157
            static mt19937 gen(rd());
vb@88
   158
markus@269
   159
            uniform_int_distribution<time_t> dist(0, cycle / fraction);
vb@96
   160
vb@96
   161
            return dist(gen);
vb@96
   162
        }
vb@96
   163
        catch (exception&) {
vb@96
   164
            assert(0);
vb@96
   165
            return 0;
vb@96
   166
        }
vb@88
   167
    }
vb@96
   168
vb@96
   169
    void GateKeeper::keep()
vb@96
   170
    {
vb@96
   171
        if (!cu_open)
vb@96
   172
            return;
vb@96
   173
vb@96
   174
        while (1) {
vb@96
   175
            keep_plugin();
vb@96
   176
vb@96
   177
            now = time(NULL);
vb@96
   178
            assert(now != -1);
vb@96
   179
markus@284
   180
            bool force_check;
markus@284
   181
            // We need to sleep, but we should be interruptible by the update_now() method.
markus@284
   182
            {
markus@284
   183
                std::unique_lock<std::mutex> guard(GateKeeper::update_wait_mtx);
markus@284
   184
                GateKeeper::update_wait_var.wait_for(guard, waiting);
markus@284
   185
                force_check = GateKeeper::update_wait_forced;
markus@284
   186
                GateKeeper::update_wait_forced = false;
markus@284
   187
            }
markus@284
   188
markus@284
   189
            if (force_check || now > next) {
vb@96
   190
                next = now + GateKeeper::cycle;
vb@96
   191
                keep_updated();
vb@134
   192
            }
markus@284
   193
        }
markus@284
   194
    }
vb@96
   195
markus@284
   196
    void GateKeeper::update_now() 
markus@284
   197
    {
markus@284
   198
        // Signal the GateKeeper thread that we need to check for updates now.
markus@284
   199
        std::unique_lock<std::mutex> guard(GateKeeper::update_wait_mtx);
markus@284
   200
        GateKeeper::update_wait_forced = true;
markus@284
   201
        GateKeeper::update_wait_var.notify_all();
vb@88
   202
    }
vb@96
   203
vb@96
   204
    void GateKeeper::keep_plugin()
vb@96
   205
    {
markus@269
   206
        HKEY hkPluginStart = NULL;
vb@141
   207
vb@141
   208
        LONG lResult = RegOpenKeyEx(cu, plugin_reg_path, 0, KEY_WRITE, &hkPluginStart);
vb@96
   209
        if (lResult != ERROR_SUCCESS)
vb@96
   210
            return;
vb@96
   211
vb@141
   212
        DWORD v = 3;
markus@269
   213
        lResult = RegSetValueEx(hkPluginStart, plugin_reg_value_name, 0, REG_DWORD, (const BYTE *)&v, sizeof(DWORD));
vb@141
   214
        assert(lResult == ERROR_SUCCESS);
vb@141
   215
vb@141
   216
        RegCloseKey(hkPluginStart);
vb@96
   217
    }
vb@96
   218
vb@111
   219
    string GateKeeper::update_key()
vb@110
   220
    {
vb@110
   221
        static string key;
vb@110
   222
vb@110
   223
        if (key.length() == 0) {
vb@110
   224
            HRSRC res = FindResource(_self->hModule(), MAKEINTRESOURCE(IRD_UPDATEKEY), RT_RCDATA);
vb@110
   225
            assert(res);
vb@110
   226
            if (!res)
vb@110
   227
                throw runtime_error("FindResource: IRD_UPDATEKEY");
vb@110
   228
vb@110
   229
            HGLOBAL hRes = LoadResource(_self->hModule(), res);
vb@110
   230
            assert(hRes);
vb@110
   231
            if (!hRes)
vb@110
   232
                throw runtime_error("LoadResource: IRD_UPDATEKEY");
vb@110
   233
vb@110
   234
            key = string((char *)LockResource(hRes), SizeofResource(_self->hModule(), res));
vb@110
   235
            UnlockResource(hRes);
vb@110
   236
        }
vb@110
   237
vb@110
   238
        return key;
vb@110
   239
    }
vb@110
   240
vb@116
   241
    BCRYPT_KEY_HANDLE GateKeeper::delivery_key()
vb@112
   242
    {
vb@112
   243
        aeskey_t key;
vb@112
   244
vb@112
   245
        static random_device rd;
vb@112
   246
        static mt19937 gen(rd());
vb@112
   247
vb@123
   248
        uniform_int_distribution<int64_t> dist(0, UINT32_MAX);
vb@112
   249
vb@123
   250
        for (int i = 0; i < 8; i++)
markus@269
   251
            key.dw_key[i] = (uint32_t)dist(gen);
vb@113
   252
vb@116
   253
        BCRYPT_KEY_HANDLE hKey;
vb@142
   254
markus@269
   255
        NTSTATUS status = BCryptGenerateSymmetricKey(hAES, &hKey, NULL, 0, (PUCHAR)&key, (ULONG) sizeof(aeskey_t), 0);
vb@116
   256
        assert(status == 0);
vb@116
   257
        if (status)
vb@116
   258
            throw runtime_error("BCryptGenerateSymmetricKey");
vb@116
   259
vb@142
   260
#ifndef NDEBUG
vb@131
   261
        DWORD keylength = 0;
vb@131
   262
        ULONG copied = 0;
markus@269
   263
        status = BCryptGetProperty(hKey, BCRYPT_KEY_LENGTH, (PUCHAR)&keylength, sizeof(DWORD), &copied, 0);
vb@131
   264
        assert(keylength == 256);
vb@142
   265
#endif
vb@131
   266
vb@116
   267
        return hKey;
vb@113
   268
    }
vb@113
   269
vb@121
   270
    string GateKeeper::wrapped_delivery_key(BCRYPT_KEY_HANDLE hDeliveryKey)
vb@113
   271
    {
vb@113
   272
        string result;
vb@113
   273
vb@299
   274
        BCRYPT_KEY_HANDLE hUpdateKey = NULL;
vb@117
   275
        string _update_key = update_key();
vb@113
   276
vb@299
   277
        PCERT_PUBLIC_KEY_INFO uk = NULL;
vb@299
   278
        DWORD uk_size = 0;
vb@142
   279
vb@123
   280
        BOOL bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO,
markus@269
   281
            (const BYTE *)_update_key.data(), _update_key.size(), CRYPT_DECODE_ALLOC_FLAG, NULL, &uk, &uk_size);
vb@123
   282
        if (!bResult)
vb@123
   283
            throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
vb@123
   284
vb@299
   285
        PUBLIC_KEY_VALUES *_uk = NULL;
vb@299
   286
        DWORD _uk_size = 0;
vb@142
   287
vb@123
   288
        bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB,
vb@123
   289
            uk->PublicKey.pbData, uk->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &_uk, &_uk_size);
vb@123
   290
        LocalFree(uk);
vb@123
   291
        if (!bResult)
vb@123
   292
            throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
vb@123
   293
vb@123
   294
        HRESULT hResult = ImportRsaPublicKey(hRSA, _uk, &hUpdateKey);
vb@123
   295
        LocalFree(_uk);
vb@302
   296
        if (!hUpdateKey)
vb@123
   297
            throw runtime_error("ImportRsaPublicKey");
vb@117
   298
vb@129
   299
        ULONG psize;
vb@129
   300
        NTSTATUS status = BCryptGetProperty(hUpdateKey, BCRYPT_ALGORITHM_NAME, NULL, 0, &psize, 0);
vb@129
   301
        char *prop = new char[psize];
markus@269
   302
        TCHAR *_prop = (TCHAR *)prop;
vb@299
   303
        status = BCryptGetProperty(hUpdateKey, BCRYPT_ALGORITHM_NAME, (PUCHAR)prop, psize, &psize, 0);
vb@302
   304
        if (status)
vb@302
   305
            throw runtime_error("BCryptGetProperty: BCRYPT_ALGORITHM_NAME");
vb@129
   306
vb@129
   307
        ULONG export_size;
vb@129
   308
        status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, NULL, NULL,
vb@129
   309
            &export_size, 0);
vb@129
   310
        if (status)
vb@129
   311
            throw runtime_error("BCryptExportKey: measuring export size");
vb@129
   312
vb@129
   313
        PUCHAR _delivery_key = new UCHAR[export_size];
vb@120
   314
        ULONG copied;
vb@129
   315
        status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, _delivery_key, export_size,
markus@269
   316
            &copied, 0);
vb@129
   317
        if (status) {
vb@129
   318
            delete[] _delivery_key;
vb@120
   319
            throw runtime_error("BCryptExportKey: delivery_key");
vb@129
   320
        }
vb@120
   321
vb@117
   322
        BCRYPT_OAEP_PADDING_INFO pi;
vb@119
   323
        memset(&pi, 0, sizeof(BCRYPT_OAEP_PADDING_INFO));
vb@117
   324
        pi.pszAlgId = BCRYPT_SHA256_ALGORITHM;
vb@117
   325
vb@301
   326
        ULONG result_size = 0;
vb@118
   327
        PUCHAR _result = NULL;
vb@129
   328
        ULONG blob_size = export_size - sizeof(BCRYPT_KEY_DATA_BLOB_HEADER);
vb@129
   329
        PUCHAR blob = _delivery_key + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER);
vb@129
   330
        status = BCryptEncrypt(hUpdateKey, blob, blob_size, &pi, NULL, 0, NULL, 0, &result_size, BCRYPT_PAD_OAEP);
vb@119
   331
        if (status) {
vb@129
   332
            delete[] _delivery_key;
vb@119
   333
            BCryptDestroyKey(hUpdateKey);
vb@117
   334
            throw runtime_error("BCryptEncrypt: calculating result size");
vb@119
   335
        }
vb@117
   336
vb@301
   337
        _result = new UCHAR[result_size + 1];
vb@129
   338
        status = BCryptEncrypt(hUpdateKey, blob, blob_size, &pi, NULL, 0, _result, result_size, &copied, BCRYPT_PAD_OAEP);
vb@129
   339
        delete[] _delivery_key;
vb@119
   340
        if (status) {
vb@119
   341
            BCryptDestroyKey(hUpdateKey);
vb@119
   342
            delete[] _result;
vb@118
   343
            throw runtime_error("BCryptEncrypt: encrypting using update_key");
vb@119
   344
        }
vb@117
   345
vb@120
   346
        BCryptDestroyKey(hUpdateKey);
vb@120
   347
vb@117
   348
        stringstream s;
vb@129
   349
        for (ULONG i = 0; i < copied; i++) {
vb@129
   350
            s << hex << setw(2) << setfill('0');
markus@269
   351
            s << (int)_result[i];
vb@129
   352
        }
vb@117
   353
        delete[] _result;
vb@117
   354
        s >> result;
vb@117
   355
vb@113
   356
        return result;
vb@112
   357
    }
vb@112
   358
vb@214
   359
    GateKeeper::product_list GateKeeper::registered_products()
vb@96
   360
    {
vb@214
   361
        product_list products;
vb@88
   362
vb@96
   363
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724872(v=vs.85).aspx
vb@300
   364
        static TCHAR value_name[16384];
vb@96
   365
        DWORD value_name_size;
vb@300
   366
        static TCHAR value[L_MAX_URL_LENGTH + 1];
vb@96
   367
        DWORD value_size;
vb@88
   368
vb@96
   369
        LONG lResult = ERROR_SUCCESS;
vb@96
   370
        for (DWORD i = 0; lResult == ERROR_SUCCESS; i++) {
vb@138
   371
            value_name_size = 16383;
vb@96
   372
            value_size = L_MAX_URL_LENGTH + 1;
markus@269
   373
            lResult = RegEnumValue(hkUpdater, i, value_name, &value_name_size, NULL, NULL, (LPBYTE)value, &value_size);
vb@139
   374
            if (lResult == ERROR_SUCCESS) {
vb@96
   375
                products.push_back({ value_name, value });
vb@139
   376
            }
vb@88
   377
        }
vb@88
   378
vb@96
   379
        return products;
vb@88
   380
    }
vb@88
   381
Thomas@360
   382
    void GateKeeper::execute_file(tstring filename)
vb@126
   383
    {
markus@269
   384
        HANDLE hMutex = CreateMutex(NULL, TRUE, _T("PEPINSTALLERMUTEX"));
markus@269
   385
        if (hMutex) {
markus@269
   386
            CloseHandle(hMutex);
markus@269
   387
            ShellExecute(NULL, _T("open"), filename.c_str(), NULL, NULL, SW_SHOW);
markus@269
   388
        }
vb@126
   389
    }
vb@126
   390
markus@269
   391
    tstring GateKeeper::get_lockFile()
markus@269
   392
    {
markus@269
   393
        static const tstring _fileName = _T("\\pEpSetup.lck");
markus@269
   394
        static tstring fileName;
vb@207
   395
markus@269
   396
        if (fileName.length() == 0) {
markus@269
   397
            unique_ptr < TCHAR[] > _pathName(new TCHAR[MAX_PATH + 1]);
markus@269
   398
            DWORD size = GetTempPath(MAX_PATH, _pathName.get());
markus@269
   399
            if (size > MAX_PATH - _fileName.size())
markus@269
   400
                throw runtime_error("TEMP path too long");
vb@207
   401
markus@269
   402
            fileName = _pathName.get();
markus@269
   403
            fileName += _fileName;
markus@269
   404
        }
vb@207
   405
markus@269
   406
        return fileName;
markus@269
   407
    }
vb@208
   408
Thomas@361
   409
	// Retrieving Headers Using HTTP_QUERY_CUSTOM
Thomas@361
   410
	static tstring httpQueryCustom(HINTERNET hHttp, tstring header)
Thomas@361
   411
	{
Thomas@361
   412
		DWORD dwResult = 0;
Thomas@361
   413
		LPTSTR lpOutBuffer = StrDup(header.c_str());
Thomas@361
   414
Thomas@361
   415
	retry:
Thomas@361
   416
Thomas@361
   417
		if (!HttpQueryInfo(hHttp, HTTP_QUERY_CUSTOM, (LPVOID)lpOutBuffer, &dwResult, NULL))
Thomas@361
   418
		{
Thomas@361
   419
			if (GetLastError() == ERROR_HTTP_HEADER_NOT_FOUND)
Thomas@361
   420
			{
Thomas@361
   421
				// Code to handle the case where the header isn't available.
Thomas@361
   422
				LocalFree(lpOutBuffer);
Thomas@361
   423
				throw(runtime_error("ERROR_HTTP_HEADER_NOT_FOUND"));
Thomas@361
   424
			}
Thomas@361
   425
			else
Thomas@361
   426
			{
Thomas@361
   427
				// Check for an insufficient buffer.
Thomas@361
   428
				if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
Thomas@361
   429
				{
Thomas@361
   430
					// Allocate the necessary buffer.
Thomas@361
   431
					LocalFree(lpOutBuffer);
Thomas@361
   432
					lpOutBuffer = (LPTSTR)LocalAlloc(LMEM_FIXED, dwResult + 1);
Thomas@361
   433
Thomas@361
   434
					// Rewrite the header name in the buffer.
Thomas@361
   435
					StringCchPrintf(lpOutBuffer, dwResult, header.c_str());
Thomas@361
   436
Thomas@361
   437
					// Retry the call.
Thomas@361
   438
					goto retry;
Thomas@361
   439
				}
Thomas@361
   440
				else
Thomas@361
   441
				{
Thomas@361
   442
					// Error handling code.
Thomas@361
   443
					LocalFree(lpOutBuffer);
Thomas@361
   444
					// FIXME: Add GetLastError()
Thomas@361
   445
					throw(runtime_error("Unknown"));
Thomas@361
   446
				}
Thomas@361
   447
			}
Thomas@361
   448
		}
Thomas@361
   449
Thomas@361
   450
		tstring result(lpOutBuffer);
Thomas@361
   451
		LocalFree(lpOutBuffer);
Thomas@361
   452
Thomas@361
   453
		return result;
Thomas@361
   454
	}
Thomas@361
   455
vb@208
   456
    void GateKeeper::update_product(product p, DWORD context)
vb@208
   457
    {
markus@269
   458
        {
markus@269
   459
            HANDLE file = CreateFile(get_lockFile().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
markus@269
   460
            if (file == INVALID_HANDLE_VALUE) {
markus@269
   461
                return;
markus@269
   462
            }
markus@269
   463
            else {
markus@269
   464
                CloseHandle(file);
markus@269
   465
                DeleteFile(get_lockFile().c_str());
markus@269
   466
            }
markus@269
   467
        }
vb@199
   468
vb@127
   469
        BCRYPT_KEY_HANDLE dk = delivery_key();
vb@126
   470
#ifdef UNICODE
vb@127
   471
        tstring delivery = utility::utf16_string(wrapped_delivery_key(dk));
vb@126
   472
#else
vb@126
   473
        tstring delivery = wrapped_delivery_key(delivery_key());
vb@126
   474
#endif
vb@124
   475
        tstring url = p.second;
vb@124
   476
        url += _T("&challenge=");
vb@124
   477
        url += delivery;
vb@124
   478
        tstring headers;
vb@124
   479
        HINTERNET hUrl = InternetOpenUrl(internet, url.c_str(), headers.c_str(), headers.length(),
markus@269
   480
            INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE, context);
vb@97
   481
        if (hUrl == NULL)
vb@97
   482
            return;
vb@94
   483
vb@127
   484
        string crypted;
vb@127
   485
        string unencrypted;
vb@133
   486
        UCHAR iv[12];
vb@133
   487
        UCHAR nonce[sizeof(iv)];
vb@133
   488
        UCHAR tag[16];
vb@138
   489
        tstring filename;
vb@138
   490
        HANDLE hFile = NULL;
vb@138
   491
        char *unencrypted_buffer = NULL;
vb@107
   492
vb@130
   493
        try {
Thomas@361
   494
vb@133
   495
            DWORD reading;
vb@133
   496
            InternetReadFile(hUrl, iv, sizeof(iv), &reading);
vb@133
   497
vb@133
   498
            if (reading) do {
markus@269
   499
                static char buffer[1024 * 1024];
markus@269
   500
                BOOL bResult = InternetReadFile(hUrl, buffer, 1024 * 1024, &reading);
vb@130
   501
                if (!bResult || !reading)
vb@130
   502
                    break;
vb@130
   503
                crypted += string(buffer, reading);
vb@130
   504
            } while (1);
vb@279
   505
Thomas@361
   506
			tstring contentDisposition = httpQueryCustom(hUrl, _T("Content-Disposition"));
Thomas@361
   507
Thomas@361
   508
			wregex filenameRegex(_T("filename=.([^\"]*)"), regex::extended); //FIXME: case insensitive
Thomas@361
   509
			wsmatch match;
Thomas@361
   510
Thomas@361
   511
			if (regex_search(contentDisposition, match, filenameRegex)) {
Thomas@361
   512
				filename = match[1];
Thomas@361
   513
			}
Thomas@361
   514
vb@279
   515
            InternetCloseHandle(hUrl);
vb@279
   516
            hUrl = NULL;
vb@279
   517
vb@279
   518
            memcpy(nonce, iv, sizeof(iv));
vb@279
   519
vb@279
   520
            BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo;
vb@279
   521
            BCRYPT_INIT_AUTH_MODE_INFO(authInfo);
vb@279
   522
            authInfo.pbNonce = nonce;
vb@279
   523
            authInfo.cbNonce = sizeof(nonce);
vb@279
   524
            authInfo.pbTag = tag;
vb@279
   525
            authInfo.cbTag = sizeof(tag);
vb@279
   526
vb@279
   527
            ULONG unencrypted_size;
vb@279
   528
            NTSTATUS status = BCryptDecrypt(dk, (PUCHAR)crypted.data(), crypted.size(),
vb@279
   529
                &authInfo, iv, sizeof(iv), NULL, 0, &unencrypted_size, 0);
vb@279
   530
            if (status)
vb@279
   531
                goto closing;
vb@279
   532
vb@279
   533
            unencrypted_buffer = new char[unencrypted_size];
vb@279
   534
vb@279
   535
            PUCHAR crypted_data = (PUCHAR)crypted.data();
vb@279
   536
            ULONG crypted_size = (ULONG)crypted.size() - sizeof(tag);
vb@279
   537
            memcpy(tag, crypted_data + crypted_size, sizeof(tag));
vb@279
   538
vb@279
   539
            status = BCryptDecrypt(dk, crypted_data, crypted_size,
vb@279
   540
                &authInfo, iv, sizeof(iv), (PUCHAR)unencrypted_buffer, unencrypted_size, &unencrypted_size, 0);
vb@279
   541
            if (status)
vb@279
   542
                goto closing;
vb@279
   543
vb@279
   544
            BCryptDestroyKey(dk);
vb@279
   545
vb@279
   546
            TCHAR temp_path[MAX_PATH + 1];
vb@279
   547
            GetTempPath(MAX_PATH, temp_path);
Thomas@361
   548
Thomas@361
   549
			if (filename == _T("")) {
Thomas@361
   550
				filename = temp_path;
Thomas@361
   551
				filename += _T("\\pEp_");
Thomas@361
   552
				filename += delivery.substr(0, 32);
Thomas@361
   553
				filename += _T(".msi");
Thomas@361
   554
			}
Thomas@361
   555
			else {
Thomas@361
   556
				filename = tstring(temp_path) + _T("\\") + filename;
Thomas@361
   557
			}
vb@279
   558
vb@279
   559
            hFile = CreateFile(filename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
vb@279
   560
            if (!hFile)
vb@279
   561
                goto closing;
vb@279
   562
            DWORD writing;
vb@279
   563
            WriteFile(hFile, unencrypted_buffer, unencrypted_size, &writing, NULL);
vb@279
   564
            CloseHandle(hFile);
Thomas@361
   565
			hFile = NULL;
vb@279
   566
            delete[] unencrypted_buffer;
vb@279
   567
            unencrypted_buffer = nullptr;
vb@130
   568
        }
vb@138
   569
        catch (exception&) {
vb@138
   570
            goto closing;
vb@130
   571
        }
vb@133
   572
Thomas@360
   573
        execute_file(filename);
vb@127
   574
vb@126
   575
    closing:
vb@127
   576
        if (unencrypted_buffer)
vb@127
   577
            delete[] unencrypted_buffer;
vb@126
   578
        if (hFile)
vb@126
   579
            CloseHandle(hFile);
vb@126
   580
        if (hUrl)
vb@126
   581
            InternetCloseHandle(hUrl);
vb@127
   582
        BCryptDestroyKey(dk);
vb@96
   583
    }
vb@88
   584
vb@96
   585
    void GateKeeper::keep_updated()
vb@96
   586
    {
vb@116
   587
        NTSTATUS status = BCryptOpenAlgorithmProvider(&hAES, BCRYPT_AES_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
vb@116
   588
        assert(status == 0);
vb@116
   589
        if (status)
vb@116
   590
            goto closing;
markus@269
   591
        status = BCryptSetProperty(hAES, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_GCM, sizeof(BCRYPT_CHAIN_MODE_GCM), 0);
vb@128
   592
        if (status)
vb@128
   593
            goto closing;
vb@116
   594
vb@116
   595
        status = BCryptOpenAlgorithmProvider(&hRSA, BCRYPT_RSA_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
vb@116
   596
        assert(status == 0);
vb@116
   597
        if (status)
vb@116
   598
            goto closing;
vb@116
   599
vb@124
   600
        internet = InternetOpen(_T("pEp"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
vb@124
   601
        if (!internet)
vb@124
   602
            goto closing;
vb@97
   603
markus@269
   604
        {
markus@269
   605
            product_list products = registered_products();
markus@269
   606
            DWORD context = 0;
vb@138
   607
markus@269
   608
            for (auto i = products.begin(); i != products.end(); i++) {
markus@269
   609
                try {
markus@269
   610
                    update_product(*i, context++);
markus@269
   611
                }
markus@269
   612
                catch (exception&) {
vb@214
   613
markus@269
   614
                }
markus@269
   615
            }
markus@269
   616
        }
vb@97
   617
vb@116
   618
    closing:
vb@116
   619
        if (internet)
vb@116
   620
            InternetCloseHandle(internet);
vb@116
   621
        if (hAES)
vb@116
   622
            BCryptCloseAlgorithmProvider(hAES, 0);
vb@116
   623
        if (hRSA)
vb@116
   624
            BCryptCloseAlgorithmProvider(hRSA, 0);
vb@97
   625
        internet = NULL;
vb@116
   626
        hAES = NULL;
vb@116
   627
        hRSA = NULL;
vb@96
   628
    }
vb@88
   629
vb@96
   630
} // namespace pEp