3 #include "GateKeeper.h"
4 #include "pEpCOMServerAdapter.h"
5 #include "utf8_helper.h"
9 // from https://msdn.microsoft.com/en-us/library/windows/desktop/dd388945(v=vs.85).aspx
11 struct PUBLIC_KEY_VALUES {
12 BLOBHEADER blobheader;
17 static void ReverseMemCopy(
19 _In_ BYTE const *pbSource,
23 for (DWORD i = 0; i < cb; i++) {
24 pbDest[cb - 1 - i] = pbSource[i];
28 static NTSTATUS ImportRsaPublicKey(
29 _In_ BCRYPT_ALG_HANDLE hAlg, // CNG provider
30 _In_ PUBLIC_KEY_VALUES *pKey, // Pointer to the RSAPUBKEY blob.
31 _In_ BCRYPT_KEY_HANDLE *phKey // Receives a handle the imported public key.
36 BYTE *pbPublicKey = NULL;
39 // Layout of the RSA public key blob:
41 // +----------------------------------------------------------------+
42 // | BCRYPT_RSAKEY_BLOB | BE( dwExp ) | BE( Modulus ) |
43 // +----------------------------------------------------------------+
45 // sizeof(BCRYPT_RSAKEY_BLOB) cbExp cbModulus
46 // <--------------------------><------------><---------------------->
48 // BE = Big Endian Format
50 DWORD cbModulus = (pKey->rsapubkey.bitlen + 7) / 8;
51 DWORD dwExp = pKey->rsapubkey.pubexp;
52 DWORD cbExp = (dwExp & 0xFF000000) ? 4 :
53 (dwExp & 0x00FF0000) ? 3 :
54 (dwExp & 0x0000FF00) ? 2 : 1;
56 BCRYPT_RSAKEY_BLOB *pRsaBlob;
59 if (!SUCCEEDED(hr = DWordAdd(cbModulus, sizeof(BCRYPT_RSAKEY_BLOB), &cbKey))) {
65 pbPublicKey = (PBYTE) CoTaskMemAlloc(cbKey);
66 if (pbPublicKey == NULL) {
71 ZeroMemory(pbPublicKey, cbKey);
72 pRsaBlob = (BCRYPT_RSAKEY_BLOB *) (pbPublicKey);
75 // Make the Public Key Blob Header
78 pRsaBlob->Magic = BCRYPT_RSAPUBLIC_MAGIC;
79 pRsaBlob->BitLength = pKey->rsapubkey.bitlen;
80 pRsaBlob->cbPublicExp = cbExp;
81 pRsaBlob->cbModulus = cbModulus;
82 pRsaBlob->cbPrime1 = 0;
83 pRsaBlob->cbPrime2 = 0;
85 pbCurrent = (PBYTE) (pRsaBlob + 1);
88 // Copy pubExp Big Endian
91 ReverseMemCopy(pbCurrent, (PBYTE) &dwExp, cbExp);
95 // Copy Modulus Big Endian
98 ReverseMemCopy(pbCurrent, pKey->modulus, cbModulus);
101 // Import the public key
104 hr = BCryptImportKeyPair(hAlg, NULL, BCRYPT_RSAPUBLIC_BLOB, phKey, (PUCHAR) pbPublicKey, cbKey, 0);
107 CoTaskMemFree(pbPublicKey);
113 const LPCTSTR GateKeeper::plugin_reg_path = _T("Software\\Microsoft\\Office\\Outlook\\Addins\\pEp");
114 const LPCTSTR GateKeeper::plugin_reg_value_name = _T("LoadBehavior");
115 const LPCTSTR GateKeeper::updater_reg_path = _T("Software\\pEp\\Updater");
117 const time_t GateKeeper::cycle = 7200; // 7200 sec is 2 h
118 const time_t GateKeeper::fraction = 10; // first update is at 10% of cycle
119 const DWORD GateKeeper::waiting = 10000; // 10000 ms is 10 sec
121 GateKeeper::GateKeeper(CpEpCOMServerAdapterModule * self)
122 : _self(self), now(time(NULL)), next(now + time_diff()), hkUpdater(NULL), hkPluginStart(NULL),
123 internet(NULL), hAES(NULL), hRSA(NULL)
125 LONG lResult = RegOpenCurrentUser(KEY_READ, &cu);
126 assert(lResult == ERROR_SUCCESS);
127 if (lResult == ERROR_SUCCESS)
133 LONG lResult = RegOpenKeyEx(cu, updater_reg_path, 0, KEY_READ, &hkUpdater);
134 assert(lResult == ERROR_SUCCESS);
135 if (lResult != ERROR_SUCCESS)
138 lResult = RegOpenKeyEx(cu, plugin_reg_path, 0, KEY_WRITE, &hkPluginStart);
139 assert(lResult == ERROR_SUCCESS);
140 if (lResult != ERROR_SUCCESS)
142 RegCloseKey(hkPluginStart);
146 GateKeeper::~GateKeeper()
150 RegCloseKey(hkUpdater);
155 time_t GateKeeper::time_diff()
158 static random_device rd;
159 static mt19937 gen(rd());
161 uniform_int_distribution<time_t> dist(0, cycle/fraction);
171 void GateKeeper::keep()
183 next = now + GateKeeper::cycle;
191 void GateKeeper::keep_plugin()
196 LONG lResult = RegOpenKeyEx(cu, plugin_reg_path, 0, KEY_WRITE, &hkPluginStart);
197 assert(lResult == ERROR_SUCCESS);
198 if (lResult != ERROR_SUCCESS)
202 lResult = RegSetValueEx(hkPluginStart, plugin_reg_value_name, 0, REG_DWORD, (const BYTE *) &v, sizeof(DWORD));
203 assert(lResult == ERROR_SUCCESS);
205 RegCloseKey(hkPluginStart);
208 string GateKeeper::update_key()
212 if (key.length() == 0) {
213 HRSRC res = FindResource(_self->hModule(), MAKEINTRESOURCE(IRD_UPDATEKEY), RT_RCDATA);
216 throw runtime_error("FindResource: IRD_UPDATEKEY");
218 HGLOBAL hRes = LoadResource(_self->hModule(), res);
221 throw runtime_error("LoadResource: IRD_UPDATEKEY");
223 key = string((char *)LockResource(hRes), SizeofResource(_self->hModule(), res));
224 UnlockResource(hRes);
230 BCRYPT_KEY_HANDLE GateKeeper::delivery_key()
234 static random_device rd;
235 static mt19937 gen(rd());
237 uniform_int_distribution<int64_t> dist(0, UINT32_MAX);
239 for (int i = 0; i < 8; i++)
240 key.dw_key[i] = (uint32_t) dist(gen);
242 BCRYPT_KEY_HANDLE hKey;
244 NTSTATUS status = BCryptGenerateSymmetricKey(hAES, &hKey, NULL, 0, (PUCHAR) &key, (ULONG) sizeof(aeskey_t), 0);
247 throw runtime_error("BCryptGenerateSymmetricKey");
252 status = BCryptGetProperty(hKey, BCRYPT_KEY_LENGTH, (PUCHAR) &keylength, sizeof(DWORD), &copied, 0);
253 assert(keylength == 256);
259 string GateKeeper::wrapped_delivery_key(BCRYPT_KEY_HANDLE hDeliveryKey)
263 BCRYPT_KEY_HANDLE hUpdateKey;
264 string _update_key = update_key();
266 PCERT_PUBLIC_KEY_INFO uk;
269 BOOL bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO,
270 (const BYTE *) _update_key.data(), _update_key.size(), CRYPT_DECODE_ALLOC_FLAG, NULL, &uk, &uk_size);
272 throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
274 PUBLIC_KEY_VALUES *_uk;
277 bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB,
278 uk->PublicKey.pbData, uk->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &_uk, &_uk_size);
281 throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
283 HRESULT hResult = ImportRsaPublicKey(hRSA, _uk, &hUpdateKey);
286 throw runtime_error("ImportRsaPublicKey");
289 NTSTATUS status = BCryptGetProperty(hUpdateKey, BCRYPT_ALGORITHM_NAME, NULL, 0, &psize, 0);
290 char *prop = new char[psize];
291 TCHAR *_prop = (TCHAR *) prop;
292 BCryptGetProperty(hUpdateKey, BCRYPT_ALGORITHM_NAME, (PUCHAR) prop, psize, &psize, 0);
295 status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, NULL, NULL,
298 throw runtime_error("BCryptExportKey: measuring export size");
300 PUCHAR _delivery_key = new UCHAR[export_size];
302 status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, _delivery_key, export_size,
305 delete[] _delivery_key;
306 throw runtime_error("BCryptExportKey: delivery_key");
309 BCRYPT_OAEP_PADDING_INFO pi;
310 memset(&pi, 0, sizeof(BCRYPT_OAEP_PADDING_INFO));
311 pi.pszAlgId = BCRYPT_SHA256_ALGORITHM;
314 PUCHAR _result = NULL;
315 ULONG blob_size = export_size - sizeof(BCRYPT_KEY_DATA_BLOB_HEADER);
316 PUCHAR blob = _delivery_key + sizeof(BCRYPT_KEY_DATA_BLOB_HEADER);
317 status = BCryptEncrypt(hUpdateKey, blob, blob_size, &pi, NULL, 0, NULL, 0, &result_size, BCRYPT_PAD_OAEP);
319 delete[] _delivery_key;
320 BCryptDestroyKey(hUpdateKey);
321 throw runtime_error("BCryptEncrypt: calculating result size");
324 _result = new UCHAR[result_size];
325 status = BCryptEncrypt(hUpdateKey, blob, blob_size, &pi, NULL, 0, _result, result_size, &copied, BCRYPT_PAD_OAEP);
326 delete[] _delivery_key;
328 BCryptDestroyKey(hUpdateKey);
330 throw runtime_error("BCryptEncrypt: encrypting using update_key");
333 BCryptDestroyKey(hUpdateKey);
336 for (ULONG i = 0; i < copied; i++) {
337 s << hex << setw(2) << setfill('0');
338 s << (int) _result[i];
346 GateKeeper::product_list& GateKeeper::registered_products()
348 static product_list products;
350 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724872(v=vs.85).aspx
351 TCHAR value_name[16384];
352 DWORD value_name_size;
353 TCHAR value[L_MAX_URL_LENGTH + 1];
358 LONG lResult = ERROR_SUCCESS;
359 for (DWORD i = 0; lResult == ERROR_SUCCESS; i++) {
360 value_name_size = 16383;
361 value_size = L_MAX_URL_LENGTH + 1;
362 lResult = RegEnumValue(hkUpdater, i, value_name, &value_name_size, NULL, NULL, (LPBYTE) value, &value_size);
363 if (lResult == ERROR_SUCCESS) {
364 products.push_back({ value_name, value });
371 void GateKeeper::install_msi(tstring filename)
373 HANDLE hMutex = CreateMutex(NULL, TRUE, _T("PEPINSTALLERMUTEX"));
376 ShellExecute(NULL, _T("open"), filename.c_str(), NULL, NULL, SW_SHOW);
380 void GateKeeper::update_product(product p, DWORD context)
383 HANDLE hMutex = CreateMutex(NULL, TRUE, _T("PEPINSTALLERMUTEX"));
390 BCRYPT_KEY_HANDLE dk = delivery_key();
392 tstring delivery = utility::utf16_string(wrapped_delivery_key(dk));
394 tstring delivery = wrapped_delivery_key(delivery_key());
396 tstring url = p.second;
397 url += _T("&challenge=");
400 HINTERNET hUrl = InternetOpenUrl(internet, url.c_str(), headers.c_str(), headers.length(),
401 INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE, context);
408 UCHAR nonce[sizeof(iv)];
412 char *unencrypted_buffer = NULL;
416 InternetReadFile(hUrl, iv, sizeof(iv), &reading);
419 static char buffer[1024*1024];
420 BOOL bResult = InternetReadFile(hUrl, buffer, 1024*1024, &reading);
421 if (!bResult || !reading)
423 crypted += string(buffer, reading);
430 InternetCloseHandle(hUrl);
433 memcpy(nonce, iv, sizeof(iv));
435 BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo;
436 BCRYPT_INIT_AUTH_MODE_INFO(authInfo);
437 authInfo.pbNonce = nonce;
438 authInfo.cbNonce = sizeof(nonce);
439 authInfo.pbTag = tag;
440 authInfo.cbTag = sizeof(tag);
442 ULONG unencrypted_size;
443 NTSTATUS status = BCryptDecrypt(dk, (PUCHAR) crypted.data(), crypted.size(),
444 &authInfo, iv, sizeof(iv), NULL, 0, &unencrypted_size, 0);
448 unencrypted_buffer = new char[unencrypted_size];
449 PUCHAR crypted_data = (PUCHAR) crypted.data();
450 ULONG crypted_size = (ULONG) crypted.size() - sizeof(tag);
451 memcpy(tag, crypted_data + crypted_size, sizeof(tag));
453 status = BCryptDecrypt(dk, crypted_data, crypted_size,
454 &authInfo, iv, sizeof(iv), (PUCHAR) unencrypted_buffer, unencrypted_size, &unencrypted_size, 0);
458 BCryptDestroyKey(dk);
460 TCHAR temp_path[MAX_PATH + 1];
461 GetTempPath(MAX_PATH, temp_path);
462 filename = temp_path;
463 filename += _T("\\pEp_");
464 filename += delivery.substr(0, 32);
465 filename += _T(".msi");
467 hFile = CreateFile(filename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
471 WriteFile(hFile, unencrypted_buffer, unencrypted_size, &writing, NULL);
474 install_msi(filename);
479 if (unencrypted_buffer)
480 delete[] unencrypted_buffer;
484 InternetCloseHandle(hUrl);
485 BCryptDestroyKey(dk);
488 void GateKeeper::keep_updated()
490 NTSTATUS status = BCryptOpenAlgorithmProvider(&hAES, BCRYPT_AES_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
494 status = BCryptSetProperty(hAES, BCRYPT_CHAINING_MODE, (PUCHAR) BCRYPT_CHAIN_MODE_GCM, sizeof(BCRYPT_CHAIN_MODE_GCM), 0);
498 status = BCryptOpenAlgorithmProvider(&hRSA, BCRYPT_RSA_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
503 internet = InternetOpen(_T("pEp"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
507 product_list& products = registered_products();
510 for (auto i = products.begin(); i != products.end(); i++) {
512 update_product(*i, context++);
521 InternetCloseHandle(internet);
523 BCryptCloseAlgorithmProvider(hAES, 0);
525 BCryptCloseAlgorithmProvider(hRSA, 0);