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