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