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