GateKeeper.cpp
author Volker Birk <vb@pep-project.org>
Sun, 13 Nov 2016 08:45:29 +0100
changeset 208 35eb7b0492ac
parent 207 d5d291166c76
child 209 dbc6c02c9755
permissions -rw-r--r--
delete lock file on startup
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
vb@123
    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.
vb@123
    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
vb@123
    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);
vb@123
    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
vb@123
    85
    pbCurrent = (PBYTE) (pRsaBlob + 1);
vb@123
    86
vb@123
    87
    //
vb@123
    88
    // Copy pubExp Big Endian 
vb@123
    89
    //
vb@123
    90
vb@123
    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
vb@123
   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
vb@96
   113
    const LPCTSTR GateKeeper::plugin_reg_path = _T("Software\\Microsoft\\Office\\Outlook\\Addins\\pEp");
vb@96
   114
    const LPCTSTR GateKeeper::plugin_reg_value_name = _T("LoadBehavior");
vb@135
   115
    const LPCTSTR GateKeeper::updater_reg_path = _T("Software\\pEp\\Updater");
vb@96
   116
vb@96
   117
    const time_t GateKeeper::cycle = 7200;   // 7200 sec is 2 h
vb@137
   118
    const time_t GateKeeper::fraction = 10;  // first update is at 10% of cycle
vb@96
   119
    const DWORD GateKeeper::waiting = 10000; // 10000 ms is 10 sec
vb@88
   120
vb@117
   121
    GateKeeper::GateKeeper(CpEpCOMServerAdapterModule * self)
vb@141
   122
        : _self(self), now(time(NULL)), next(now + time_diff()), hkUpdater(NULL), hkPluginStart(NULL),
vb@141
   123
            internet(NULL), hAES(NULL), hRSA(NULL)
vb@96
   124
    {
vb@208
   125
		DeleteFile(get_lockFile().c_str());
vb@208
   126
vb@96
   127
        LONG lResult = RegOpenCurrentUser(KEY_READ, &cu);
vb@96
   128
        assert(lResult == ERROR_SUCCESS);
vb@96
   129
        if (lResult == ERROR_SUCCESS)
vb@96
   130
            cu_open = true;
vb@96
   131
        else
vb@96
   132
            cu_open = false;
vb@88
   133
vb@96
   134
        if (cu_open) {
vb@96
   135
            LONG lResult = RegOpenKeyEx(cu, updater_reg_path, 0, KEY_READ, &hkUpdater);
vb@96
   136
            assert(lResult == ERROR_SUCCESS);
vb@96
   137
            if (lResult != ERROR_SUCCESS)
vb@96
   138
                return;
vb@141
   139
vb@141
   140
            lResult = RegOpenKeyEx(cu, plugin_reg_path, 0, KEY_WRITE, &hkPluginStart);
vb@141
   141
            assert(lResult == ERROR_SUCCESS);
vb@141
   142
            if (lResult != ERROR_SUCCESS)
vb@141
   143
                return;
vb@141
   144
            RegCloseKey(hkPluginStart);
vb@96
   145
        }
vb@96
   146
    }
vb@96
   147
    
vb@96
   148
    GateKeeper::~GateKeeper()
vb@96
   149
    {
vb@96
   150
        if (cu_open) {
vb@96
   151
            if (hkUpdater)
vb@96
   152
                RegCloseKey(hkUpdater);
vb@96
   153
            RegCloseKey(cu);
vb@96
   154
        }
vb@96
   155
    }
vb@88
   156
vb@96
   157
    time_t GateKeeper::time_diff()
vb@96
   158
    {
vb@96
   159
        try {
vb@96
   160
            static random_device rd;
vb@96
   161
            static mt19937 gen(rd());
vb@88
   162
vb@137
   163
            uniform_int_distribution<time_t> dist(0, cycle/fraction);
vb@96
   164
vb@96
   165
            return dist(gen);
vb@96
   166
        }
vb@96
   167
        catch (exception&) {
vb@96
   168
            assert(0);
vb@96
   169
            return 0;
vb@96
   170
        }
vb@88
   171
    }
vb@96
   172
vb@96
   173
    void GateKeeper::keep()
vb@96
   174
    {
vb@96
   175
        if (!cu_open)
vb@96
   176
            return;
vb@96
   177
vb@96
   178
        while (1) {
vb@96
   179
            keep_plugin();
vb@96
   180
vb@96
   181
            now = time(NULL);
vb@96
   182
            assert(now != -1);
vb@96
   183
vb@134
   184
            if (now > next) {
vb@96
   185
                next = now + GateKeeper::cycle;
vb@96
   186
                keep_updated();
vb@134
   187
            }
vb@96
   188
vb@96
   189
            Sleep(waiting);
vb@96
   190
        }
vb@88
   191
    }
vb@96
   192
vb@96
   193
    void GateKeeper::keep_plugin()
vb@96
   194
    {
vb@141
   195
        if (!hkPluginStart)
vb@141
   196
            return;
vb@141
   197
vb@141
   198
        LONG lResult = RegOpenKeyEx(cu, plugin_reg_path, 0, KEY_WRITE, &hkPluginStart);
vb@141
   199
        assert(lResult == ERROR_SUCCESS);
vb@96
   200
        if (lResult != ERROR_SUCCESS)
vb@96
   201
            return;
vb@96
   202
vb@141
   203
        DWORD v = 3;
vb@141
   204
        lResult = RegSetValueEx(hkPluginStart, plugin_reg_value_name, 0, REG_DWORD, (const BYTE *) &v, sizeof(DWORD));
vb@141
   205
        assert(lResult == ERROR_SUCCESS);
vb@141
   206
vb@141
   207
        RegCloseKey(hkPluginStart);
vb@96
   208
    }
vb@96
   209
vb@111
   210
    string GateKeeper::update_key()
vb@110
   211
    {
vb@110
   212
        static string key;
vb@110
   213
vb@110
   214
        if (key.length() == 0) {
vb@110
   215
            HRSRC res = FindResource(_self->hModule(), MAKEINTRESOURCE(IRD_UPDATEKEY), RT_RCDATA);
vb@110
   216
            assert(res);
vb@110
   217
            if (!res)
vb@110
   218
                throw runtime_error("FindResource: IRD_UPDATEKEY");
vb@110
   219
vb@110
   220
            HGLOBAL hRes = LoadResource(_self->hModule(), res);
vb@110
   221
            assert(hRes);
vb@110
   222
            if (!hRes)
vb@110
   223
                throw runtime_error("LoadResource: IRD_UPDATEKEY");
vb@110
   224
vb@110
   225
            key = string((char *)LockResource(hRes), SizeofResource(_self->hModule(), res));
vb@110
   226
            UnlockResource(hRes);
vb@110
   227
        }
vb@110
   228
vb@110
   229
        return key;
vb@110
   230
    }
vb@110
   231
vb@116
   232
    BCRYPT_KEY_HANDLE GateKeeper::delivery_key()
vb@112
   233
    {
vb@112
   234
        aeskey_t key;
vb@112
   235
vb@112
   236
        static random_device rd;
vb@112
   237
        static mt19937 gen(rd());
vb@112
   238
vb@123
   239
        uniform_int_distribution<int64_t> dist(0, UINT32_MAX);
vb@112
   240
vb@123
   241
        for (int i = 0; i < 8; i++)
vb@123
   242
            key.dw_key[i] = (uint32_t) dist(gen);
vb@113
   243
vb@116
   244
        BCRYPT_KEY_HANDLE hKey;
vb@142
   245
vb@116
   246
        NTSTATUS status = BCryptGenerateSymmetricKey(hAES, &hKey, NULL, 0, (PUCHAR) &key, (ULONG) sizeof(aeskey_t), 0);
vb@116
   247
        assert(status == 0);
vb@116
   248
        if (status)
vb@116
   249
            throw runtime_error("BCryptGenerateSymmetricKey");
vb@116
   250
vb@142
   251
#ifndef NDEBUG
vb@131
   252
        DWORD keylength = 0;
vb@131
   253
        ULONG copied = 0;
vb@131
   254
        status = BCryptGetProperty(hKey, BCRYPT_KEY_LENGTH, (PUCHAR) &keylength, sizeof(DWORD), &copied, 0);
vb@131
   255
        assert(keylength == 256);
vb@142
   256
#endif
vb@131
   257
vb@116
   258
        return hKey;
vb@113
   259
    }
vb@113
   260
vb@121
   261
    string GateKeeper::wrapped_delivery_key(BCRYPT_KEY_HANDLE hDeliveryKey)
vb@113
   262
    {
vb@113
   263
        string result;
vb@113
   264
vb@116
   265
        BCRYPT_KEY_HANDLE hUpdateKey;
vb@117
   266
        string _update_key = update_key();
vb@113
   267
vb@123
   268
        PCERT_PUBLIC_KEY_INFO uk;
vb@123
   269
        DWORD uk_size;
vb@142
   270
vb@123
   271
        BOOL bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO,
vb@123
   272
                (const BYTE *) _update_key.data(), _update_key.size(), CRYPT_DECODE_ALLOC_FLAG, NULL, &uk, &uk_size);
vb@123
   273
        if (!bResult)
vb@123
   274
            throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
vb@123
   275
vb@123
   276
        PUBLIC_KEY_VALUES *_uk;
vb@123
   277
        DWORD _uk_size;
vb@142
   278
vb@123
   279
        bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB,
vb@123
   280
            uk->PublicKey.pbData, uk->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &_uk, &_uk_size);
vb@123
   281
        LocalFree(uk);
vb@123
   282
        if (!bResult)
vb@123
   283
            throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
vb@123
   284
vb@123
   285
        HRESULT hResult = ImportRsaPublicKey(hRSA, _uk, &hUpdateKey);
vb@123
   286
        LocalFree(_uk);
vb@123
   287
        if (hResult)
vb@123
   288
            throw runtime_error("ImportRsaPublicKey");
vb@117
   289
vb@129
   290
        ULONG psize;
vb@129
   291
        NTSTATUS status = BCryptGetProperty(hUpdateKey, BCRYPT_ALGORITHM_NAME, NULL, 0, &psize, 0);
vb@129
   292
        char *prop = new char[psize];
vb@129
   293
        TCHAR *_prop = (TCHAR *) prop;
vb@129
   294
        BCryptGetProperty(hUpdateKey, BCRYPT_ALGORITHM_NAME, (PUCHAR) prop, psize, &psize, 0);
vb@129
   295
vb@129
   296
        ULONG export_size;
vb@129
   297
        status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, NULL, NULL,
vb@129
   298
            &export_size, 0);
vb@129
   299
        if (status)
vb@129
   300
            throw runtime_error("BCryptExportKey: measuring export size");
vb@129
   301
vb@129
   302
        PUCHAR _delivery_key = new UCHAR[export_size];
vb@120
   303
        ULONG copied;
vb@129
   304
        status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, _delivery_key, export_size,
vb@123
   305
                &copied, 0);
vb@129
   306
        if (status) {
vb@129
   307
            delete[] _delivery_key;
vb@120
   308
            throw runtime_error("BCryptExportKey: delivery_key");
vb@129
   309
        }
vb@120
   310
vb@117
   311
        BCRYPT_OAEP_PADDING_INFO pi;
vb@119
   312
        memset(&pi, 0, sizeof(BCRYPT_OAEP_PADDING_INFO));
vb@117
   313
        pi.pszAlgId = BCRYPT_SHA256_ALGORITHM;
vb@117
   314
vb@117
   315
        ULONG result_size;
vb@118
   316
        PUCHAR _result = NULL;
vb@129
   317
        ULONG blob_size = export_size - sizeof(BCRYPT_KEY_DATA_BLOB_HEADER);
vb@129
   318
        PUCHAR blob = _delivery_key + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER);
vb@129
   319
        status = BCryptEncrypt(hUpdateKey, blob, blob_size, &pi, NULL, 0, NULL, 0, &result_size, BCRYPT_PAD_OAEP);
vb@119
   320
        if (status) {
vb@129
   321
            delete[] _delivery_key;
vb@119
   322
            BCryptDestroyKey(hUpdateKey);
vb@117
   323
            throw runtime_error("BCryptEncrypt: calculating result size");
vb@119
   324
        }
vb@117
   325
vb@117
   326
        _result = new UCHAR[result_size];
vb@129
   327
        status = BCryptEncrypt(hUpdateKey, blob, blob_size, &pi, NULL, 0, _result, result_size, &copied, BCRYPT_PAD_OAEP);
vb@129
   328
        delete[] _delivery_key;
vb@119
   329
        if (status) {
vb@119
   330
            BCryptDestroyKey(hUpdateKey);
vb@119
   331
            delete[] _result;
vb@118
   332
            throw runtime_error("BCryptEncrypt: encrypting using update_key");
vb@119
   333
        }
vb@117
   334
vb@120
   335
        BCryptDestroyKey(hUpdateKey);
vb@120
   336
vb@117
   337
        stringstream s;
vb@129
   338
        for (ULONG i = 0; i < copied; i++) {
vb@129
   339
            s << hex << setw(2) << setfill('0');
vb@118
   340
            s << (int) _result[i];
vb@129
   341
        }
vb@117
   342
        delete[] _result;
vb@117
   343
        s >> result;
vb@117
   344
vb@113
   345
        return result;
vb@112
   346
    }
vb@112
   347
vb@96
   348
    GateKeeper::product_list& GateKeeper::registered_products()
vb@96
   349
    {
vb@96
   350
        static product_list products;
vb@88
   351
vb@96
   352
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724872(v=vs.85).aspx
vb@138
   353
        TCHAR value_name[16384];
vb@96
   354
        DWORD value_name_size;
vb@138
   355
        TCHAR value[L_MAX_URL_LENGTH + 1];
vb@96
   356
        DWORD value_size;
vb@88
   357
vb@96
   358
        products.empty();
vb@96
   359
vb@96
   360
        LONG lResult = ERROR_SUCCESS;
vb@96
   361
        for (DWORD i = 0; lResult == ERROR_SUCCESS; i++) {
vb@138
   362
            value_name_size = 16383;
vb@96
   363
            value_size = L_MAX_URL_LENGTH + 1;
vb@139
   364
            lResult = RegEnumValue(hkUpdater, i, value_name, &value_name_size, NULL, NULL, (LPBYTE) value, &value_size);
vb@139
   365
            if (lResult == ERROR_SUCCESS) {
vb@96
   366
                products.push_back({ value_name, value });
vb@139
   367
            }
vb@88
   368
        }
vb@88
   369
vb@96
   370
        return products;
vb@88
   371
    }
vb@88
   372
vb@126
   373
    void GateKeeper::install_msi(tstring filename)
vb@126
   374
    {
vb@198
   375
		HANDLE hMutex = CreateMutex(NULL, TRUE, _T("PEPINSTALLERMUTEX"));
vb@198
   376
		if (hMutex) {
vb@198
   377
			CloseHandle(hMutex);
vb@198
   378
			ShellExecute(NULL, _T("open"), filename.c_str(), NULL, NULL, SW_SHOW);
vb@198
   379
		}
vb@126
   380
    }
vb@126
   381
vb@208
   382
	tstring GateKeeper::get_lockFile()
vb@208
   383
	{
vb@208
   384
		static const tstring _fileName = _T("\\pEpSetup.lck");
vb@208
   385
		static tstring fileName;
vb@207
   386
vb@208
   387
		if (fileName.length() == 0) {
vb@207
   388
			unique_ptr < TCHAR[] > _pathName(new TCHAR[MAX_PATH + 1]);
vb@207
   389
			DWORD size = GetTempPath(MAX_PATH, _pathName.get());
vb@207
   390
			if (size > MAX_PATH - _fileName.size())
vb@207
   391
				throw runtime_error("TEMP path too long");
vb@207
   392
vb@207
   393
			tstring fileName(_pathName.get());
vb@207
   394
			fileName += _fileName;
vb@208
   395
		}
vb@207
   396
vb@208
   397
		return fileName;
vb@208
   398
	}
vb@208
   399
vb@208
   400
    void GateKeeper::update_product(product p, DWORD context)
vb@208
   401
    {
vb@208
   402
		{
vb@208
   403
			HANDLE file = CreateFile(get_lockFile().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
vb@207
   404
			if (file == INVALID_HANDLE_VALUE) {
vb@207
   405
				return;
vb@206
   406
			}
vb@206
   407
			else {
vb@207
   408
				CloseHandle(file);
vb@208
   409
				DeleteFile(get_lockFile().c_str());
vb@206
   410
			}
vb@199
   411
		}
vb@199
   412
vb@127
   413
        BCRYPT_KEY_HANDLE dk = delivery_key();
vb@126
   414
#ifdef UNICODE
vb@127
   415
        tstring delivery = utility::utf16_string(wrapped_delivery_key(dk));
vb@126
   416
#else
vb@126
   417
        tstring delivery = wrapped_delivery_key(delivery_key());
vb@126
   418
#endif
vb@124
   419
        tstring url = p.second;
vb@124
   420
        url += _T("&challenge=");
vb@124
   421
        url += delivery;
vb@124
   422
        tstring headers;
vb@124
   423
        HINTERNET hUrl = InternetOpenUrl(internet, url.c_str(), headers.c_str(), headers.length(),
vb@97
   424
                INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE, context);
vb@97
   425
        if (hUrl == NULL)
vb@97
   426
            return;
vb@94
   427
vb@127
   428
        string crypted;
vb@127
   429
        string unencrypted;
vb@133
   430
        UCHAR iv[12];
vb@133
   431
        UCHAR nonce[sizeof(iv)];
vb@133
   432
        UCHAR tag[16];
vb@138
   433
        tstring filename;
vb@138
   434
        HANDLE hFile = NULL;
vb@138
   435
        char *unencrypted_buffer = NULL;
vb@107
   436
vb@130
   437
        try {
vb@133
   438
            DWORD reading;
vb@133
   439
            InternetReadFile(hUrl, iv, sizeof(iv), &reading);
vb@133
   440
vb@133
   441
            if (reading) do {
vb@130
   442
                static char buffer[1024*1024];
vb@130
   443
                BOOL bResult = InternetReadFile(hUrl, buffer, 1024*1024, &reading);
vb@130
   444
                if (!bResult || !reading)
vb@130
   445
                    break;
vb@130
   446
                crypted += string(buffer, reading);
vb@130
   447
            } while (1);
vb@130
   448
        }
vb@138
   449
        catch (exception&) {
vb@138
   450
            goto closing;
vb@130
   451
        }
vb@133
   452
vb@97
   453
        InternetCloseHandle(hUrl);
vb@126
   454
        hUrl = NULL;
vb@126
   455
vb@133
   456
        memcpy(nonce, iv, sizeof(iv));
vb@133
   457
vb@130
   458
        BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo;
vb@130
   459
        BCRYPT_INIT_AUTH_MODE_INFO(authInfo);
vb@130
   460
        authInfo.pbNonce = nonce;
vb@130
   461
        authInfo.cbNonce = sizeof(nonce);
vb@133
   462
        authInfo.pbTag = tag;
vb@133
   463
        authInfo.cbTag = sizeof(tag);
vb@128
   464
vb@127
   465
        ULONG unencrypted_size;
vb@127
   466
        NTSTATUS status = BCryptDecrypt(dk, (PUCHAR) crypted.data(), crypted.size(),
vb@131
   467
                &authInfo, iv, sizeof(iv), NULL, 0, &unencrypted_size, 0);
vb@127
   468
        if (status)
vb@127
   469
            goto closing;
vb@127
   470
        
vb@127
   471
        unencrypted_buffer = new char[unencrypted_size];
vb@131
   472
        PUCHAR crypted_data = (PUCHAR) crypted.data();
vb@133
   473
        ULONG crypted_size = (ULONG) crypted.size() - sizeof(tag);
vb@133
   474
        memcpy(tag, crypted_data + crypted_size, sizeof(tag));
vb@133
   475
vb@131
   476
        status = BCryptDecrypt(dk, crypted_data, crypted_size,
vb@133
   477
            &authInfo, iv, sizeof(iv), (PUCHAR) unencrypted_buffer, unencrypted_size, &unencrypted_size, 0);
vb@129
   478
        if (status)
vb@127
   479
            goto closing;
vb@127
   480
vb@134
   481
        BCryptDestroyKey(dk);
vb@134
   482
vb@127
   483
        TCHAR temp_path[MAX_PATH + 1];
vb@127
   484
        GetTempPath(MAX_PATH, temp_path);
vb@127
   485
        filename = temp_path;
vb@127
   486
        filename += _T("\\pEp_");
vb@127
   487
        filename += delivery.substr(0, 32);
vb@127
   488
        filename += _T(".msi");
vb@127
   489
vb@127
   490
        hFile = CreateFile(filename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
vb@127
   491
        if (!hFile)
vb@127
   492
            goto closing;
vb@127
   493
        DWORD writing;
vb@127
   494
        WriteFile(hFile, unencrypted_buffer, unencrypted_size, &writing, NULL);
vb@127
   495
        CloseHandle(hFile);
vb@127
   496
vb@126
   497
        install_msi(filename);
vb@127
   498
vb@126
   499
        return;
vb@126
   500
vb@126
   501
    closing:
vb@127
   502
        if (unencrypted_buffer)
vb@127
   503
            delete[] unencrypted_buffer;
vb@126
   504
        if (hFile)
vb@126
   505
            CloseHandle(hFile);
vb@126
   506
        if (hUrl)
vb@126
   507
            InternetCloseHandle(hUrl);
vb@127
   508
        BCryptDestroyKey(dk);
vb@96
   509
    }
vb@88
   510
vb@96
   511
    void GateKeeper::keep_updated()
vb@96
   512
    {
vb@116
   513
        NTSTATUS status = BCryptOpenAlgorithmProvider(&hAES, BCRYPT_AES_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
vb@116
   514
        assert(status == 0);
vb@116
   515
        if (status)
vb@116
   516
            goto closing;
vb@130
   517
        status = BCryptSetProperty(hAES, BCRYPT_CHAINING_MODE, (PUCHAR) BCRYPT_CHAIN_MODE_GCM, sizeof(BCRYPT_CHAIN_MODE_GCM), 0);
vb@128
   518
        if (status)
vb@128
   519
            goto closing;
vb@116
   520
vb@116
   521
        status = BCryptOpenAlgorithmProvider(&hRSA, BCRYPT_RSA_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
vb@116
   522
        assert(status == 0);
vb@116
   523
        if (status)
vb@116
   524
            goto closing;
vb@116
   525
vb@124
   526
        internet = InternetOpen(_T("pEp"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
vb@124
   527
        if (!internet)
vb@124
   528
            goto closing;
vb@97
   529
vb@96
   530
        product_list& products = registered_products();
vb@97
   531
        DWORD context = 0;
vb@138
   532
vb@96
   533
        for (auto i = products.begin(); i != products.end(); i++) {
vb@126
   534
            try {
vb@126
   535
                update_product(*i, context++);
vb@126
   536
            }
vb@126
   537
            catch (exception&) {
vb@126
   538
            
vb@126
   539
            }
vb@96
   540
        }
vb@97
   541
vb@116
   542
    closing:
vb@116
   543
        if (internet)
vb@116
   544
            InternetCloseHandle(internet);
vb@116
   545
        if (hAES)
vb@116
   546
            BCryptCloseAlgorithmProvider(hAES, 0);
vb@116
   547
        if (hRSA)
vb@116
   548
            BCryptCloseAlgorithmProvider(hRSA, 0);
vb@97
   549
        internet = NULL;
vb@116
   550
        hAES = NULL;
vb@116
   551
        hRSA = NULL;
vb@96
   552
    }
vb@88
   553
vb@96
   554
} // namespace pEp