GateKeeper.cpp
author Markus Schaber <markus@pep-security.net>
Tue, 04 Oct 2016 23:07:42 +0200
branchkeysync
changeset 178 9f30e2a5f72c
parent 144 18208f2ec0bf
child 198 f317fa016c94
permissions -rw-r--r--
COM-30 COM-24: Refactorings
Drop unused enum.
     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         LONG lResult = RegOpenCurrentUser(KEY_READ, &cu);
   126         assert(lResult == ERROR_SUCCESS);
   127         if (lResult == ERROR_SUCCESS)
   128             cu_open = true;
   129         else
   130             cu_open = false;
   131 
   132         if (cu_open) {
   133             LONG lResult = RegOpenKeyEx(cu, updater_reg_path, 0, KEY_READ, &hkUpdater);
   134             assert(lResult == ERROR_SUCCESS);
   135             if (lResult != ERROR_SUCCESS)
   136                 return;
   137 
   138             lResult = RegOpenKeyEx(cu, plugin_reg_path, 0, KEY_WRITE, &hkPluginStart);
   139             assert(lResult == ERROR_SUCCESS);
   140             if (lResult != ERROR_SUCCESS)
   141                 return;
   142             RegCloseKey(hkPluginStart);
   143         }
   144     }
   145     
   146     GateKeeper::~GateKeeper()
   147     {
   148         if (cu_open) {
   149             if (hkUpdater)
   150                 RegCloseKey(hkUpdater);
   151             RegCloseKey(cu);
   152         }
   153     }
   154 
   155     time_t GateKeeper::time_diff()
   156     {
   157         try {
   158             static random_device rd;
   159             static mt19937 gen(rd());
   160 
   161             uniform_int_distribution<time_t> dist(0, cycle/fraction);
   162 
   163             return dist(gen);
   164         }
   165         catch (exception&) {
   166             assert(0);
   167             return 0;
   168         }
   169     }
   170 
   171     void GateKeeper::keep()
   172     {
   173         if (!cu_open)
   174             return;
   175 
   176         while (1) {
   177             keep_plugin();
   178 
   179             now = time(NULL);
   180             assert(now != -1);
   181 
   182             if (now > next) {
   183                 next = now + GateKeeper::cycle;
   184                 keep_updated();
   185             }
   186 
   187             Sleep(waiting);
   188         }
   189     }
   190 
   191     void GateKeeper::keep_plugin()
   192     {
   193         if (!hkPluginStart)
   194             return;
   195 
   196         LONG lResult = RegOpenKeyEx(cu, plugin_reg_path, 0, KEY_WRITE, &hkPluginStart);
   197         assert(lResult == ERROR_SUCCESS);
   198         if (lResult != ERROR_SUCCESS)
   199             return;
   200 
   201         DWORD v = 3;
   202         lResult = RegSetValueEx(hkPluginStart, plugin_reg_value_name, 0, REG_DWORD, (const BYTE *) &v, sizeof(DWORD));
   203         assert(lResult == ERROR_SUCCESS);
   204 
   205         RegCloseKey(hkPluginStart);
   206     }
   207 
   208     string GateKeeper::update_key()
   209     {
   210         static string key;
   211 
   212         if (key.length() == 0) {
   213             HRSRC res = FindResource(_self->hModule(), MAKEINTRESOURCE(IRD_UPDATEKEY), RT_RCDATA);
   214             assert(res);
   215             if (!res)
   216                 throw runtime_error("FindResource: IRD_UPDATEKEY");
   217 
   218             HGLOBAL hRes = LoadResource(_self->hModule(), res);
   219             assert(hRes);
   220             if (!hRes)
   221                 throw runtime_error("LoadResource: IRD_UPDATEKEY");
   222 
   223             key = string((char *)LockResource(hRes), SizeofResource(_self->hModule(), res));
   224             UnlockResource(hRes);
   225         }
   226 
   227         return key;
   228     }
   229 
   230     BCRYPT_KEY_HANDLE GateKeeper::delivery_key()
   231     {
   232         aeskey_t key;
   233 
   234         static random_device rd;
   235         static mt19937 gen(rd());
   236 
   237         uniform_int_distribution<int64_t> dist(0, UINT32_MAX);
   238 
   239         for (int i = 0; i < 8; i++)
   240             key.dw_key[i] = (uint32_t) dist(gen);
   241 
   242         BCRYPT_KEY_HANDLE hKey;
   243 
   244         NTSTATUS status = BCryptGenerateSymmetricKey(hAES, &hKey, NULL, 0, (PUCHAR) &key, (ULONG) sizeof(aeskey_t), 0);
   245         assert(status == 0);
   246         if (status)
   247             throw runtime_error("BCryptGenerateSymmetricKey");
   248 
   249 #ifndef NDEBUG
   250         DWORD keylength = 0;
   251         ULONG copied = 0;
   252         status = BCryptGetProperty(hKey, BCRYPT_KEY_LENGTH, (PUCHAR) &keylength, sizeof(DWORD), &copied, 0);
   253         assert(keylength == 256);
   254 #endif
   255 
   256         return hKey;
   257     }
   258 
   259     string GateKeeper::wrapped_delivery_key(BCRYPT_KEY_HANDLE hDeliveryKey)
   260     {
   261         string result;
   262 
   263         BCRYPT_KEY_HANDLE hUpdateKey;
   264         string _update_key = update_key();
   265 
   266         PCERT_PUBLIC_KEY_INFO uk;
   267         DWORD uk_size;
   268 
   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);
   271         if (!bResult)
   272             throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
   273 
   274         PUBLIC_KEY_VALUES *_uk;
   275         DWORD _uk_size;
   276 
   277         bResult = CryptDecodeObjectEx(X509_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB,
   278             uk->PublicKey.pbData, uk->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &_uk, &_uk_size);
   279         LocalFree(uk);
   280         if (!bResult)
   281             throw runtime_error("CryptDecodeObjectEx: X509_PUBLIC_KEY_INFO");
   282 
   283         HRESULT hResult = ImportRsaPublicKey(hRSA, _uk, &hUpdateKey);
   284         LocalFree(_uk);
   285         if (hResult)
   286             throw runtime_error("ImportRsaPublicKey");
   287 
   288         ULONG psize;
   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);
   293 
   294         ULONG export_size;
   295         status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, NULL, NULL,
   296             &export_size, 0);
   297         if (status)
   298             throw runtime_error("BCryptExportKey: measuring export size");
   299 
   300         PUCHAR _delivery_key = new UCHAR[export_size];
   301         ULONG copied;
   302         status = BCryptExportKey(hDeliveryKey, NULL, BCRYPT_KEY_DATA_BLOB, _delivery_key, export_size,
   303                 &copied, 0);
   304         if (status) {
   305             delete[] _delivery_key;
   306             throw runtime_error("BCryptExportKey: delivery_key");
   307         }
   308 
   309         BCRYPT_OAEP_PADDING_INFO pi;
   310         memset(&pi, 0, sizeof(BCRYPT_OAEP_PADDING_INFO));
   311         pi.pszAlgId = BCRYPT_SHA256_ALGORITHM;
   312 
   313         ULONG result_size;
   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);
   318         if (status) {
   319             delete[] _delivery_key;
   320             BCryptDestroyKey(hUpdateKey);
   321             throw runtime_error("BCryptEncrypt: calculating result size");
   322         }
   323 
   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;
   327         if (status) {
   328             BCryptDestroyKey(hUpdateKey);
   329             delete[] _result;
   330             throw runtime_error("BCryptEncrypt: encrypting using update_key");
   331         }
   332 
   333         BCryptDestroyKey(hUpdateKey);
   334 
   335         stringstream s;
   336         for (ULONG i = 0; i < copied; i++) {
   337             s << hex << setw(2) << setfill('0');
   338             s << (int) _result[i];
   339         }
   340         delete[] _result;
   341         s >> result;
   342 
   343         return result;
   344     }
   345 
   346     GateKeeper::product_list& GateKeeper::registered_products()
   347     {
   348         static product_list products;
   349 
   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];
   354         DWORD value_size;
   355 
   356         products.empty();
   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         ShellExecute(NULL, _T("open"), filename.c_str(), NULL, NULL, SW_SHOW);
   374     }
   375 
   376     void GateKeeper::update_product(product p, DWORD context)
   377     {
   378         BCRYPT_KEY_HANDLE dk = delivery_key();
   379 #ifdef UNICODE
   380         tstring delivery = utility::utf16_string(wrapped_delivery_key(dk));
   381 #else
   382         tstring delivery = wrapped_delivery_key(delivery_key());
   383 #endif
   384         tstring url = p.second;
   385         url += _T("&challenge=");
   386         url += delivery;
   387         tstring headers;
   388         HINTERNET hUrl = InternetOpenUrl(internet, url.c_str(), headers.c_str(), headers.length(),
   389                 INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE, context);
   390         if (hUrl == NULL)
   391             return;
   392 
   393         string crypted;
   394         string unencrypted;
   395         UCHAR iv[12];
   396         UCHAR nonce[sizeof(iv)];
   397         UCHAR tag[16];
   398         tstring filename;
   399         HANDLE hFile = NULL;
   400         char *unencrypted_buffer = NULL;
   401 
   402         try {
   403             DWORD reading;
   404             InternetReadFile(hUrl, iv, sizeof(iv), &reading);
   405 
   406             if (reading) do {
   407                 static char buffer[1024*1024];
   408                 BOOL bResult = InternetReadFile(hUrl, buffer, 1024*1024, &reading);
   409                 if (!bResult || !reading)
   410                     break;
   411                 crypted += string(buffer, reading);
   412             } while (1);
   413         }
   414         catch (exception&) {
   415             goto closing;
   416         }
   417 
   418         InternetCloseHandle(hUrl);
   419         hUrl = NULL;
   420 
   421         memcpy(nonce, iv, sizeof(iv));
   422 
   423         BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo;
   424         BCRYPT_INIT_AUTH_MODE_INFO(authInfo);
   425         authInfo.pbNonce = nonce;
   426         authInfo.cbNonce = sizeof(nonce);
   427         authInfo.pbTag = tag;
   428         authInfo.cbTag = sizeof(tag);
   429 
   430         ULONG unencrypted_size;
   431         NTSTATUS status = BCryptDecrypt(dk, (PUCHAR) crypted.data(), crypted.size(),
   432                 &authInfo, iv, sizeof(iv), NULL, 0, &unencrypted_size, 0);
   433         if (status)
   434             goto closing;
   435         
   436         unencrypted_buffer = new char[unencrypted_size];
   437         PUCHAR crypted_data = (PUCHAR) crypted.data();
   438         ULONG crypted_size = (ULONG) crypted.size() - sizeof(tag);
   439         memcpy(tag, crypted_data + crypted_size, sizeof(tag));
   440 
   441         status = BCryptDecrypt(dk, crypted_data, crypted_size,
   442             &authInfo, iv, sizeof(iv), (PUCHAR) unencrypted_buffer, unencrypted_size, &unencrypted_size, 0);
   443         if (status)
   444             goto closing;
   445 
   446         BCryptDestroyKey(dk);
   447 
   448         TCHAR temp_path[MAX_PATH + 1];
   449         GetTempPath(MAX_PATH, temp_path);
   450         filename = temp_path;
   451         filename += _T("\\pEp_");
   452         filename += delivery.substr(0, 32);
   453         filename += _T(".msi");
   454 
   455         hFile = CreateFile(filename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
   456         if (!hFile)
   457             goto closing;
   458         DWORD writing;
   459         WriteFile(hFile, unencrypted_buffer, unencrypted_size, &writing, NULL);
   460         CloseHandle(hFile);
   461 
   462         install_msi(filename);
   463 
   464         return;
   465 
   466     closing:
   467         if (unencrypted_buffer)
   468             delete[] unencrypted_buffer;
   469         if (hFile)
   470             CloseHandle(hFile);
   471         if (hUrl)
   472             InternetCloseHandle(hUrl);
   473         BCryptDestroyKey(dk);
   474     }
   475 
   476     void GateKeeper::keep_updated()
   477     {
   478         NTSTATUS status = BCryptOpenAlgorithmProvider(&hAES, BCRYPT_AES_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
   479         assert(status == 0);
   480         if (status)
   481             goto closing;
   482         status = BCryptSetProperty(hAES, BCRYPT_CHAINING_MODE, (PUCHAR) BCRYPT_CHAIN_MODE_GCM, sizeof(BCRYPT_CHAIN_MODE_GCM), 0);
   483         if (status)
   484             goto closing;
   485 
   486         status = BCryptOpenAlgorithmProvider(&hRSA, BCRYPT_RSA_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0);
   487         assert(status == 0);
   488         if (status)
   489             goto closing;
   490 
   491         internet = InternetOpen(_T("pEp"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
   492         if (!internet)
   493             goto closing;
   494 
   495         product_list& products = registered_products();
   496         DWORD context = 0;
   497 
   498         for (auto i = products.begin(); i != products.end(); i++) {
   499             try {
   500                 update_product(*i, context++);
   501             }
   502             catch (exception&) {
   503             
   504             }
   505         }
   506 
   507     closing:
   508         if (internet)
   509             InternetCloseHandle(internet);
   510         if (hAES)
   511             BCryptCloseAlgorithmProvider(hAES, 0);
   512         if (hRSA)
   513             BCryptCloseAlgorithmProvider(hRSA, 0);
   514         internet = NULL;
   515         hAES = NULL;
   516         hRSA = NULL;
   517     }
   518 
   519 } // namespace pEp