zip_crypto_win.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. zip_crypto_win.c -- Windows Crypto API wrapper.
  3. Copyright (C) 2018-2021 Dieter Baron and Thomas Klausner
  4. This file is part of libzip, a library to manipulate ZIP archives.
  5. The authors can be contacted at <libzip@nih.at>
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions
  8. are met:
  9. 1. Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. 2. Redistributions in binary form must reproduce the above copyright
  12. notice, this list of conditions and the following disclaimer in
  13. the documentation and/or other materials provided with the
  14. distribution.
  15. 3. The names of the authors may not be used to endorse or promote
  16. products derived from this software without specific prior
  17. written permission.
  18. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
  19. OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
  22. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  24. GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  25. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  26. IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  27. OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  28. IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include <stdlib.h>
  31. #include <limits.h>
  32. #include "zipint.h"
  33. #include "zip_crypto.h"
  34. #define WIN32_LEAN_AND_MEAN
  35. #define NOCRYPT
  36. #include <windows.h>
  37. #include <bcrypt.h>
  38. #pragma comment(lib, "bcrypt.lib")
  39. /*
  40. This code is using the Cryptography API: Next Generation (CNG)
  41. https://docs.microsoft.com/en-us/windows/desktop/seccng/cng-portal
  42. This API is supported on
  43. - Windows Vista or later (client OS)
  44. - Windows Server 2008 (server OS)
  45. - Windows Embedded Compact 2013 (don't know about Windows Embedded Compact 7)
  46. The code was developed for Windows Embedded Compact 2013 (WEC2013),
  47. but should be working for all of the above mentioned OSes.
  48. There are 2 restrictions for WEC2013, Windows Vista and Windows Server 2008:
  49. 1.) The function "BCryptDeriveKeyPBKDF2" is not available
  50. I found some code which is implementing this function using the deprecated Crypto API here:
  51. https://www.idrix.fr/Root/content/view/37/54/
  52. I took this code and converted it to the newer CNG API. The original code was more
  53. flexible, but this is not needed here so i refactored it a bit and just kept what is needed.
  54. The define "HAS_BCRYPTDERIVEKEYPBKDF2" controls whether "BCryptDeriveKeyPBKDF2"
  55. of the CNG API is used or not. This define must not be set if you are compiling for WEC2013 or Windows Vista.
  56. 2.) "BCryptCreateHash" can't manage the memory needed for the hash object internally
  57. On Windows 7 or later it is possible to pass NULL for the hash object buffer.
  58. This is not supported on WEC2013, so we have to handle the memory allocation/deallocation ourselves.
  59. There is no #ifdef to control that, because this is working for all supported OSes.
  60. */
  61. #if !defined(WINCE) && !defined(__MINGW32__)
  62. #define HAS_BCRYPTDERIVEKEYPBKDF2
  63. #endif
  64. #ifdef HAS_BCRYPTDERIVEKEYPBKDF2
  65. bool
  66. _zip_crypto_pbkdf2(const zip_uint8_t *key, zip_uint64_t key_length, const zip_uint8_t *salt, zip_uint16_t salt_length, zip_uint16_t iterations, zip_uint8_t *output, zip_uint16_t output_length) {
  67. BCRYPT_ALG_HANDLE hAlgorithm = NULL;
  68. bool result;
  69. if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&hAlgorithm, BCRYPT_SHA1_ALGORITHM, NULL, BCRYPT_ALG_HANDLE_HMAC_FLAG))) {
  70. return false;
  71. }
  72. result = BCRYPT_SUCCESS(BCryptDeriveKeyPBKDF2(hAlgorithm, (PUCHAR)key, (ULONG)key_length, (PUCHAR)salt, salt_length, iterations, output, output_length, 0));
  73. BCryptCloseAlgorithmProvider(hAlgorithm, 0);
  74. return result;
  75. }
  76. #else
  77. #include <math.h>
  78. #define DIGEST_SIZE 20
  79. #define BLOCK_SIZE 64
  80. typedef struct {
  81. BCRYPT_ALG_HANDLE hAlgorithm;
  82. BCRYPT_HASH_HANDLE hInnerHash;
  83. BCRYPT_HASH_HANDLE hOuterHash;
  84. ULONG cbHashObject;
  85. PUCHAR pbInnerHash;
  86. PUCHAR pbOuterHash;
  87. } PRF_CTX;
  88. static void
  89. hmacFree(PRF_CTX *pContext) {
  90. if (pContext->hOuterHash)
  91. BCryptDestroyHash(pContext->hOuterHash);
  92. if (pContext->hInnerHash)
  93. BCryptDestroyHash(pContext->hInnerHash);
  94. free(pContext->pbOuterHash);
  95. free(pContext->pbInnerHash);
  96. if (pContext->hAlgorithm)
  97. BCryptCloseAlgorithmProvider(pContext->hAlgorithm, 0);
  98. }
  99. static BOOL
  100. hmacPrecomputeDigest(BCRYPT_HASH_HANDLE hHash, PUCHAR pbPassword, DWORD cbPassword, BYTE mask) {
  101. BYTE buffer[BLOCK_SIZE];
  102. DWORD i;
  103. if (cbPassword > BLOCK_SIZE) {
  104. return FALSE;
  105. }
  106. memset(buffer, mask, sizeof(buffer));
  107. for (i = 0; i < cbPassword; ++i) {
  108. buffer[i] = (char)(pbPassword[i] ^ mask);
  109. }
  110. return BCRYPT_SUCCESS(BCryptHashData(hHash, buffer, sizeof(buffer), 0));
  111. }
  112. static BOOL
  113. hmacInit(PRF_CTX *pContext, PUCHAR pbPassword, DWORD cbPassword) {
  114. BOOL bStatus = FALSE;
  115. ULONG cbResult;
  116. BYTE key[DIGEST_SIZE];
  117. if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&pContext->hAlgorithm, BCRYPT_SHA1_ALGORITHM, NULL, 0)) || !BCRYPT_SUCCESS(BCryptGetProperty(pContext->hAlgorithm, BCRYPT_OBJECT_LENGTH, (PUCHAR)&pContext->cbHashObject, sizeof(pContext->cbHashObject), &cbResult, 0)) || ((pContext->pbInnerHash = malloc(pContext->cbHashObject)) == NULL) || ((pContext->pbOuterHash = malloc(pContext->cbHashObject)) == NULL) || !BCRYPT_SUCCESS(BCryptCreateHash(pContext->hAlgorithm, &pContext->hInnerHash, pContext->pbInnerHash, pContext->cbHashObject, NULL, 0, 0)) || !BCRYPT_SUCCESS(BCryptCreateHash(pContext->hAlgorithm, &pContext->hOuterHash, pContext->pbOuterHash, pContext->cbHashObject, NULL, 0, 0))) {
  118. goto hmacInit_end;
  119. }
  120. if (cbPassword > BLOCK_SIZE) {
  121. BCRYPT_HASH_HANDLE hHash = NULL;
  122. PUCHAR pbHashObject = malloc(pContext->cbHashObject);
  123. if (pbHashObject == NULL) {
  124. goto hmacInit_end;
  125. }
  126. bStatus = BCRYPT_SUCCESS(BCryptCreateHash(pContext->hAlgorithm, &hHash, pbHashObject, pContext->cbHashObject, NULL, 0, 0)) && BCRYPT_SUCCESS(BCryptHashData(hHash, pbPassword, cbPassword, 0)) && BCRYPT_SUCCESS(BCryptGetProperty(hHash, BCRYPT_HASH_LENGTH, (PUCHAR)&cbPassword, sizeof(cbPassword), &cbResult, 0)) && BCRYPT_SUCCESS(BCryptFinishHash(hHash, key, cbPassword, 0));
  127. if (hHash)
  128. BCryptDestroyHash(hHash);
  129. free(pbHashObject);
  130. if (!bStatus) {
  131. goto hmacInit_end;
  132. }
  133. pbPassword = key;
  134. }
  135. bStatus = hmacPrecomputeDigest(pContext->hInnerHash, pbPassword, cbPassword, 0x36) && hmacPrecomputeDigest(pContext->hOuterHash, pbPassword, cbPassword, 0x5C);
  136. hmacInit_end:
  137. if (bStatus == FALSE)
  138. hmacFree(pContext);
  139. return bStatus;
  140. }
  141. static BOOL
  142. hmacCalculateInternal(BCRYPT_HASH_HANDLE hHashTemplate, PUCHAR pbData, DWORD cbData, PUCHAR pbOutput, DWORD cbOutput, DWORD cbHashObject) {
  143. BOOL success = FALSE;
  144. BCRYPT_HASH_HANDLE hHash = NULL;
  145. PUCHAR pbHashObject = malloc(cbHashObject);
  146. if (pbHashObject == NULL) {
  147. return FALSE;
  148. }
  149. if (BCRYPT_SUCCESS(BCryptDuplicateHash(hHashTemplate, &hHash, pbHashObject, cbHashObject, 0))) {
  150. success = BCRYPT_SUCCESS(BCryptHashData(hHash, pbData, cbData, 0)) && BCRYPT_SUCCESS(BCryptFinishHash(hHash, pbOutput, cbOutput, 0));
  151. BCryptDestroyHash(hHash);
  152. }
  153. free(pbHashObject);
  154. return success;
  155. }
  156. static BOOL
  157. hmacCalculate(PRF_CTX *pContext, PUCHAR pbData, DWORD cbData, PUCHAR pbDigest) {
  158. DWORD cbResult;
  159. DWORD cbHashObject;
  160. return BCRYPT_SUCCESS(BCryptGetProperty(pContext->hAlgorithm, BCRYPT_OBJECT_LENGTH, (PUCHAR)&cbHashObject, sizeof(cbHashObject), &cbResult, 0)) && hmacCalculateInternal(pContext->hInnerHash, pbData, cbData, pbDigest, DIGEST_SIZE, cbHashObject) && hmacCalculateInternal(pContext->hOuterHash, pbDigest, DIGEST_SIZE, pbDigest, DIGEST_SIZE, cbHashObject);
  161. }
  162. static void
  163. myxor(LPBYTE ptr1, LPBYTE ptr2, DWORD dwLen) {
  164. while (dwLen--)
  165. *ptr1++ ^= *ptr2++;
  166. }
  167. BOOL
  168. pbkdf2(PUCHAR pbPassword, ULONG cbPassword, PUCHAR pbSalt, ULONG cbSalt, DWORD cIterations, PUCHAR pbDerivedKey, ULONG cbDerivedKey) {
  169. BOOL bStatus = FALSE;
  170. DWORD l, r, dwULen, i, j;
  171. BYTE Ti[DIGEST_SIZE];
  172. BYTE V[DIGEST_SIZE];
  173. LPBYTE U = malloc(max((cbSalt + 4), DIGEST_SIZE));
  174. PRF_CTX prfCtx = {0};
  175. if (U == NULL) {
  176. return FALSE;
  177. }
  178. if (pbPassword == NULL || cbPassword == 0 || pbSalt == NULL || cbSalt == 0 || cIterations == 0 || pbDerivedKey == NULL || cbDerivedKey == 0) {
  179. free(U);
  180. return FALSE;
  181. }
  182. if (!hmacInit(&prfCtx, pbPassword, cbPassword)) {
  183. goto PBKDF2_end;
  184. }
  185. l = (DWORD)ceil((double)cbDerivedKey / (double)DIGEST_SIZE);
  186. r = cbDerivedKey - (l - 1) * DIGEST_SIZE;
  187. for (i = 1; i <= l; i++) {
  188. ZeroMemory(Ti, DIGEST_SIZE);
  189. for (j = 0; j < cIterations; j++) {
  190. if (j == 0) {
  191. /* construct first input for PRF */
  192. memcpy(U, pbSalt, cbSalt);
  193. U[cbSalt] = (BYTE)((i & 0xFF000000) >> 24);
  194. U[cbSalt + 1] = (BYTE)((i & 0x00FF0000) >> 16);
  195. U[cbSalt + 2] = (BYTE)((i & 0x0000FF00) >> 8);
  196. U[cbSalt + 3] = (BYTE)((i & 0x000000FF));
  197. dwULen = cbSalt + 4;
  198. }
  199. else {
  200. memcpy(U, V, DIGEST_SIZE);
  201. dwULen = DIGEST_SIZE;
  202. }
  203. if (!hmacCalculate(&prfCtx, U, dwULen, V)) {
  204. goto PBKDF2_end;
  205. }
  206. myxor(Ti, V, DIGEST_SIZE);
  207. }
  208. if (i != l) {
  209. memcpy(&pbDerivedKey[(i - 1) * DIGEST_SIZE], Ti, DIGEST_SIZE);
  210. }
  211. else {
  212. /* Take only the first r bytes */
  213. memcpy(&pbDerivedKey[(i - 1) * DIGEST_SIZE], Ti, r);
  214. }
  215. }
  216. bStatus = TRUE;
  217. PBKDF2_end:
  218. hmacFree(&prfCtx);
  219. free(U);
  220. return bStatus;
  221. }
  222. bool
  223. _zip_crypto_pbkdf2(const zip_uint8_t *key, zip_uint64_t key_length, const zip_uint8_t *salt, zip_uint16_t salt_length, zip_uint16_t iterations, zip_uint8_t *output, zip_uint16_t output_length) {
  224. return (key_length <= ZIP_UINT32_MAX) && pbkdf2((PUCHAR)key, (ULONG)key_length, (PUCHAR)salt, salt_length, iterations, output, output_length);
  225. }
  226. #endif
  227. struct _zip_crypto_aes_s {
  228. BCRYPT_ALG_HANDLE hAlgorithm;
  229. BCRYPT_KEY_HANDLE hKey;
  230. ULONG cbKeyObject;
  231. PUCHAR pbKeyObject;
  232. };
  233. _zip_crypto_aes_t *
  234. _zip_crypto_aes_new(const zip_uint8_t *key, zip_uint16_t key_size, zip_error_t *error) {
  235. _zip_crypto_aes_t *aes = (_zip_crypto_aes_t *)calloc(1, sizeof(*aes));
  236. ULONG cbResult;
  237. ULONG key_length = key_size / 8;
  238. if (aes == NULL) {
  239. zip_error_set(error, ZIP_ER_MEMORY, 0);
  240. return NULL;
  241. }
  242. if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&aes->hAlgorithm, BCRYPT_AES_ALGORITHM, NULL, 0))) {
  243. _zip_crypto_aes_free(aes);
  244. return NULL;
  245. }
  246. if (!BCRYPT_SUCCESS(BCryptSetProperty(aes->hAlgorithm, BCRYPT_CHAINING_MODE, (PUCHAR)BCRYPT_CHAIN_MODE_ECB, sizeof(BCRYPT_CHAIN_MODE_ECB), 0))) {
  247. _zip_crypto_aes_free(aes);
  248. return NULL;
  249. }
  250. if (!BCRYPT_SUCCESS(BCryptGetProperty(aes->hAlgorithm, BCRYPT_OBJECT_LENGTH, (PUCHAR)&aes->cbKeyObject, sizeof(aes->cbKeyObject), &cbResult, 0))) {
  251. _zip_crypto_aes_free(aes);
  252. return NULL;
  253. }
  254. aes->pbKeyObject = malloc(aes->cbKeyObject);
  255. if (aes->pbKeyObject == NULL) {
  256. _zip_crypto_aes_free(aes);
  257. zip_error_set(error, ZIP_ER_MEMORY, 0);
  258. return NULL;
  259. }
  260. if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(aes->hAlgorithm, &aes->hKey, aes->pbKeyObject, aes->cbKeyObject, (PUCHAR)key, key_length, 0))) {
  261. _zip_crypto_aes_free(aes);
  262. return NULL;
  263. }
  264. return aes;
  265. }
  266. void
  267. _zip_crypto_aes_free(_zip_crypto_aes_t *aes) {
  268. if (aes == NULL) {
  269. return;
  270. }
  271. if (aes->hKey != NULL) {
  272. BCryptDestroyKey(aes->hKey);
  273. }
  274. if (aes->pbKeyObject != NULL) {
  275. free(aes->pbKeyObject);
  276. }
  277. if (aes->hAlgorithm != NULL) {
  278. BCryptCloseAlgorithmProvider(aes->hAlgorithm, 0);
  279. }
  280. free(aes);
  281. }
  282. bool
  283. _zip_crypto_aes_encrypt_block(_zip_crypto_aes_t *aes, const zip_uint8_t *in, zip_uint8_t *out) {
  284. ULONG cbResult;
  285. NTSTATUS status = BCryptEncrypt(aes->hKey, (PUCHAR)in, ZIP_CRYPTO_AES_BLOCK_LENGTH, NULL, NULL, 0, (PUCHAR)out, ZIP_CRYPTO_AES_BLOCK_LENGTH, &cbResult, 0);
  286. return BCRYPT_SUCCESS(status);
  287. }
  288. struct _zip_crypto_hmac_s {
  289. BCRYPT_ALG_HANDLE hAlgorithm;
  290. BCRYPT_HASH_HANDLE hHash;
  291. DWORD cbHashObject;
  292. PUCHAR pbHashObject;
  293. DWORD cbHash;
  294. PUCHAR pbHash;
  295. };
  296. /* https://code.msdn.microsoft.com/windowsdesktop/Hmac-Computation-Sample-11fe8ec1/sourcecode?fileId=42820&pathId=283874677 */
  297. _zip_crypto_hmac_t *
  298. _zip_crypto_hmac_new(const zip_uint8_t *secret, zip_uint64_t secret_length, zip_error_t *error) {
  299. NTSTATUS status;
  300. ULONG cbResult;
  301. _zip_crypto_hmac_t *hmac;
  302. if (secret_length > INT_MAX) {
  303. zip_error_set(error, ZIP_ER_INVAL, 0);
  304. return NULL;
  305. }
  306. hmac = (_zip_crypto_hmac_t *)calloc(1, sizeof(*hmac));
  307. if (hmac == NULL) {
  308. zip_error_set(error, ZIP_ER_MEMORY, 0);
  309. return NULL;
  310. }
  311. status = BCryptOpenAlgorithmProvider(&hmac->hAlgorithm, BCRYPT_SHA1_ALGORITHM, NULL, BCRYPT_ALG_HANDLE_HMAC_FLAG);
  312. if (!BCRYPT_SUCCESS(status)) {
  313. _zip_crypto_hmac_free(hmac);
  314. return NULL;
  315. }
  316. status = BCryptGetProperty(hmac->hAlgorithm, BCRYPT_OBJECT_LENGTH, (PUCHAR)&hmac->cbHashObject, sizeof(hmac->cbHashObject), &cbResult, 0);
  317. if (!BCRYPT_SUCCESS(status)) {
  318. _zip_crypto_hmac_free(hmac);
  319. return NULL;
  320. }
  321. hmac->pbHashObject = malloc(hmac->cbHashObject);
  322. if (hmac->pbHashObject == NULL) {
  323. _zip_crypto_hmac_free(hmac);
  324. zip_error_set(error, ZIP_ER_MEMORY, 0);
  325. return NULL;
  326. }
  327. status = BCryptGetProperty(hmac->hAlgorithm, BCRYPT_HASH_LENGTH, (PUCHAR)&hmac->cbHash, sizeof(hmac->cbHash), &cbResult, 0);
  328. if (!BCRYPT_SUCCESS(status)) {
  329. _zip_crypto_hmac_free(hmac);
  330. return NULL;
  331. }
  332. hmac->pbHash = malloc(hmac->cbHash);
  333. if (hmac->pbHash == NULL) {
  334. _zip_crypto_hmac_free(hmac);
  335. zip_error_set(error, ZIP_ER_MEMORY, 0);
  336. return NULL;
  337. }
  338. status = BCryptCreateHash(hmac->hAlgorithm, &hmac->hHash, hmac->pbHashObject, hmac->cbHashObject, (PUCHAR)secret, (ULONG)secret_length, 0);
  339. if (!BCRYPT_SUCCESS(status)) {
  340. _zip_crypto_hmac_free(hmac);
  341. return NULL;
  342. }
  343. return hmac;
  344. }
  345. void
  346. _zip_crypto_hmac_free(_zip_crypto_hmac_t *hmac) {
  347. if (hmac == NULL) {
  348. return;
  349. }
  350. if (hmac->hHash != NULL) {
  351. BCryptDestroyHash(hmac->hHash);
  352. }
  353. if (hmac->pbHash != NULL) {
  354. free(hmac->pbHash);
  355. }
  356. if (hmac->pbHashObject != NULL) {
  357. free(hmac->pbHashObject);
  358. }
  359. if (hmac->hAlgorithm) {
  360. BCryptCloseAlgorithmProvider(hmac->hAlgorithm, 0);
  361. }
  362. free(hmac);
  363. }
  364. bool
  365. _zip_crypto_hmac(_zip_crypto_hmac_t *hmac, zip_uint8_t *data, zip_uint64_t length) {
  366. if (hmac == NULL || length > ULONG_MAX) {
  367. return false;
  368. }
  369. return BCRYPT_SUCCESS(BCryptHashData(hmac->hHash, data, (ULONG)length, 0));
  370. }
  371. bool
  372. _zip_crypto_hmac_output(_zip_crypto_hmac_t *hmac, zip_uint8_t *data) {
  373. if (hmac == NULL) {
  374. return false;
  375. }
  376. return BCRYPT_SUCCESS(BCryptFinishHash(hmac->hHash, data, hmac->cbHash, 0));
  377. }
  378. ZIP_EXTERN bool
  379. zip_secure_random(zip_uint8_t *buffer, zip_uint16_t length) {
  380. return BCRYPT_SUCCESS(BCryptGenRandom(NULL, buffer, length, BCRYPT_USE_SYSTEM_PREFERRED_RNG));
  381. }