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