crypt_and_hash.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /*
  2. * \brief Generic file encryption program using generic wrappers for configured
  3. * security.
  4. *
  5. * Copyright The Mbed TLS Contributors
  6. * SPDX-License-Identifier: Apache-2.0
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  9. * not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  16. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /* Enable definition of fileno() even when compiling with -std=c99. Must be
  21. * set before mbedtls_config.h, which pulls in glibc's features.h indirectly.
  22. * Harmless on other platforms. */
  23. #define _POSIX_C_SOURCE 200112L
  24. #include "mbedtls/build_info.h"
  25. #include "mbedtls/platform.h"
  26. #if defined(MBEDTLS_CIPHER_C) && defined(MBEDTLS_MD_C) && \
  27. defined(MBEDTLS_FS_IO)
  28. #include "mbedtls/cipher.h"
  29. #include "mbedtls/md.h"
  30. #include "mbedtls/platform_util.h"
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #endif
  35. #if defined(_WIN32)
  36. #include <windows.h>
  37. #if !defined(_WIN32_WCE)
  38. #include <io.h>
  39. #endif
  40. #else
  41. #include <sys/types.h>
  42. #include <unistd.h>
  43. #endif
  44. #define MODE_ENCRYPT 0
  45. #define MODE_DECRYPT 1
  46. #define USAGE \
  47. "\n crypt_and_hash <mode> <input filename> <output filename> <cipher> <mbedtls_md> <key>\n" \
  48. "\n <mode>: 0 = encrypt, 1 = decrypt\n" \
  49. "\n example: crypt_and_hash 0 file file.aes AES-128-CBC SHA1 hex:E76B2413958B00E193\n" \
  50. "\n"
  51. #if !defined(MBEDTLS_CIPHER_C) || !defined(MBEDTLS_MD_C) || \
  52. !defined(MBEDTLS_FS_IO)
  53. int main(void)
  54. {
  55. mbedtls_printf("MBEDTLS_CIPHER_C and/or MBEDTLS_MD_C and/or MBEDTLS_FS_IO not defined.\n");
  56. mbedtls_exit(0);
  57. }
  58. #else
  59. int main(int argc, char *argv[])
  60. {
  61. int ret = 1, i;
  62. unsigned n;
  63. int exit_code = MBEDTLS_EXIT_FAILURE;
  64. int mode;
  65. size_t keylen, ilen, olen;
  66. FILE *fkey, *fin = NULL, *fout = NULL;
  67. char *p;
  68. unsigned char IV[16];
  69. unsigned char key[512];
  70. unsigned char digest[MBEDTLS_MD_MAX_SIZE];
  71. unsigned char buffer[1024];
  72. unsigned char output[1024];
  73. unsigned char diff;
  74. const mbedtls_cipher_info_t *cipher_info;
  75. const mbedtls_md_info_t *md_info;
  76. mbedtls_cipher_context_t cipher_ctx;
  77. mbedtls_md_context_t md_ctx;
  78. #if defined(_WIN32_WCE)
  79. long filesize, offset;
  80. #elif defined(_WIN32)
  81. LARGE_INTEGER li_size;
  82. __int64 filesize, offset;
  83. #else
  84. off_t filesize, offset;
  85. #endif
  86. mbedtls_cipher_init(&cipher_ctx);
  87. mbedtls_md_init(&md_ctx);
  88. /*
  89. * Parse the command-line arguments.
  90. */
  91. if (argc != 7) {
  92. const int *list;
  93. mbedtls_printf(USAGE);
  94. mbedtls_printf("Available ciphers:\n");
  95. list = mbedtls_cipher_list();
  96. while (*list) {
  97. cipher_info = mbedtls_cipher_info_from_type(*list);
  98. mbedtls_printf(" %s\n", mbedtls_cipher_info_get_name(cipher_info));
  99. list++;
  100. }
  101. mbedtls_printf("\nAvailable message digests:\n");
  102. list = mbedtls_md_list();
  103. while (*list) {
  104. md_info = mbedtls_md_info_from_type(*list);
  105. mbedtls_printf(" %s\n", mbedtls_md_get_name(md_info));
  106. list++;
  107. }
  108. goto exit;
  109. }
  110. mode = atoi(argv[1]);
  111. if (mode != MODE_ENCRYPT && mode != MODE_DECRYPT) {
  112. mbedtls_fprintf(stderr, "invalid operation mode\n");
  113. goto exit;
  114. }
  115. if (strcmp(argv[2], argv[3]) == 0) {
  116. mbedtls_fprintf(stderr, "input and output filenames must differ\n");
  117. goto exit;
  118. }
  119. if ((fin = fopen(argv[2], "rb")) == NULL) {
  120. mbedtls_fprintf(stderr, "fopen(%s,rb) failed\n", argv[2]);
  121. goto exit;
  122. }
  123. if ((fout = fopen(argv[3], "wb+")) == NULL) {
  124. mbedtls_fprintf(stderr, "fopen(%s,wb+) failed\n", argv[3]);
  125. goto exit;
  126. }
  127. /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
  128. mbedtls_setbuf(fin, NULL);
  129. mbedtls_setbuf(fout, NULL);
  130. /*
  131. * Read the Cipher and MD from the command line
  132. */
  133. cipher_info = mbedtls_cipher_info_from_string(argv[4]);
  134. if (cipher_info == NULL) {
  135. mbedtls_fprintf(stderr, "Cipher '%s' not found\n", argv[4]);
  136. goto exit;
  137. }
  138. if ((ret = mbedtls_cipher_setup(&cipher_ctx, cipher_info)) != 0) {
  139. mbedtls_fprintf(stderr, "mbedtls_cipher_setup failed\n");
  140. goto exit;
  141. }
  142. md_info = mbedtls_md_info_from_string(argv[5]);
  143. if (md_info == NULL) {
  144. mbedtls_fprintf(stderr, "Message Digest '%s' not found\n", argv[5]);
  145. goto exit;
  146. }
  147. if (mbedtls_md_setup(&md_ctx, md_info, 1) != 0) {
  148. mbedtls_fprintf(stderr, "mbedtls_md_setup failed\n");
  149. goto exit;
  150. }
  151. /*
  152. * Read the secret key from file or command line
  153. */
  154. if ((fkey = fopen(argv[6], "rb")) != NULL) {
  155. keylen = fread(key, 1, sizeof(key), fkey);
  156. fclose(fkey);
  157. } else {
  158. if (memcmp(argv[6], "hex:", 4) == 0) {
  159. p = &argv[6][4];
  160. keylen = 0;
  161. while (sscanf(p, "%02X", (unsigned int *) &n) > 0 &&
  162. keylen < (int) sizeof(key)) {
  163. key[keylen++] = (unsigned char) n;
  164. p += 2;
  165. }
  166. } else {
  167. keylen = strlen(argv[6]);
  168. if (keylen > (int) sizeof(key)) {
  169. keylen = (int) sizeof(key);
  170. }
  171. memcpy(key, argv[6], keylen);
  172. }
  173. }
  174. #if defined(_WIN32_WCE)
  175. filesize = fseek(fin, 0L, SEEK_END);
  176. #else
  177. #if defined(_WIN32)
  178. /*
  179. * Support large files (> 2Gb) on Win32
  180. */
  181. li_size.QuadPart = 0;
  182. li_size.LowPart =
  183. SetFilePointer((HANDLE) _get_osfhandle(_fileno(fin)),
  184. li_size.LowPart, &li_size.HighPart, FILE_END);
  185. if (li_size.LowPart == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
  186. mbedtls_fprintf(stderr, "SetFilePointer(0,FILE_END) failed\n");
  187. goto exit;
  188. }
  189. filesize = li_size.QuadPart;
  190. #else
  191. if ((filesize = lseek(fileno(fin), 0, SEEK_END)) < 0) {
  192. perror("lseek");
  193. goto exit;
  194. }
  195. #endif
  196. #endif
  197. if (fseek(fin, 0, SEEK_SET) < 0) {
  198. mbedtls_fprintf(stderr, "fseek(0,SEEK_SET) failed\n");
  199. goto exit;
  200. }
  201. if (mode == MODE_ENCRYPT) {
  202. /*
  203. * Generate the initialization vector as:
  204. * IV = MD( filesize || filename )[0..15]
  205. */
  206. for (i = 0; i < 8; i++) {
  207. buffer[i] = (unsigned char) (filesize >> (i << 3));
  208. }
  209. p = argv[2];
  210. if (mbedtls_md_starts(&md_ctx) != 0) {
  211. mbedtls_fprintf(stderr, "mbedtls_md_starts() returned error\n");
  212. goto exit;
  213. }
  214. if (mbedtls_md_update(&md_ctx, buffer, 8) != 0) {
  215. mbedtls_fprintf(stderr, "mbedtls_md_update() returned error\n");
  216. goto exit;
  217. }
  218. if (mbedtls_md_update(&md_ctx, (unsigned char *) p, strlen(p))
  219. != 0) {
  220. mbedtls_fprintf(stderr, "mbedtls_md_update() returned error\n");
  221. goto exit;
  222. }
  223. if (mbedtls_md_finish(&md_ctx, digest) != 0) {
  224. mbedtls_fprintf(stderr, "mbedtls_md_finish() returned error\n");
  225. goto exit;
  226. }
  227. memcpy(IV, digest, 16);
  228. /*
  229. * Append the IV at the beginning of the output.
  230. */
  231. if (fwrite(IV, 1, 16, fout) != 16) {
  232. mbedtls_fprintf(stderr, "fwrite(%d bytes) failed\n", 16);
  233. goto exit;
  234. }
  235. /*
  236. * Hash the IV and the secret key together 8192 times
  237. * using the result to setup the AES context and HMAC.
  238. */
  239. memset(digest, 0, 32);
  240. memcpy(digest, IV, 16);
  241. for (i = 0; i < 8192; i++) {
  242. if (mbedtls_md_starts(&md_ctx) != 0) {
  243. mbedtls_fprintf(stderr,
  244. "mbedtls_md_starts() returned error\n");
  245. goto exit;
  246. }
  247. if (mbedtls_md_update(&md_ctx, digest, 32) != 0) {
  248. mbedtls_fprintf(stderr,
  249. "mbedtls_md_update() returned error\n");
  250. goto exit;
  251. }
  252. if (mbedtls_md_update(&md_ctx, key, keylen) != 0) {
  253. mbedtls_fprintf(stderr,
  254. "mbedtls_md_update() returned error\n");
  255. goto exit;
  256. }
  257. if (mbedtls_md_finish(&md_ctx, digest) != 0) {
  258. mbedtls_fprintf(stderr,
  259. "mbedtls_md_finish() returned error\n");
  260. goto exit;
  261. }
  262. }
  263. if (mbedtls_cipher_setkey(&cipher_ctx,
  264. digest,
  265. (int) mbedtls_cipher_info_get_key_bitlen(cipher_info),
  266. MBEDTLS_ENCRYPT) != 0) {
  267. mbedtls_fprintf(stderr, "mbedtls_cipher_setkey() returned error\n");
  268. goto exit;
  269. }
  270. if (mbedtls_cipher_set_iv(&cipher_ctx, IV, 16) != 0) {
  271. mbedtls_fprintf(stderr, "mbedtls_cipher_set_iv() returned error\n");
  272. goto exit;
  273. }
  274. if (mbedtls_cipher_reset(&cipher_ctx) != 0) {
  275. mbedtls_fprintf(stderr, "mbedtls_cipher_reset() returned error\n");
  276. goto exit;
  277. }
  278. if (mbedtls_md_hmac_starts(&md_ctx, digest, 32) != 0) {
  279. mbedtls_fprintf(stderr, "mbedtls_md_hmac_starts() returned error\n");
  280. goto exit;
  281. }
  282. /*
  283. * Encrypt and write the ciphertext.
  284. */
  285. for (offset = 0; offset < filesize; offset += mbedtls_cipher_get_block_size(&cipher_ctx)) {
  286. ilen = ((unsigned int) filesize - offset > mbedtls_cipher_get_block_size(&cipher_ctx)) ?
  287. mbedtls_cipher_get_block_size(&cipher_ctx) : (unsigned int) (filesize - offset);
  288. if (fread(buffer, 1, ilen, fin) != ilen) {
  289. mbedtls_fprintf(stderr, "fread(%ld bytes) failed\n", (long) ilen);
  290. goto exit;
  291. }
  292. if (mbedtls_cipher_update(&cipher_ctx, buffer, ilen, output, &olen) != 0) {
  293. mbedtls_fprintf(stderr, "mbedtls_cipher_update() returned error\n");
  294. goto exit;
  295. }
  296. if (mbedtls_md_hmac_update(&md_ctx, output, olen) != 0) {
  297. mbedtls_fprintf(stderr, "mbedtls_md_hmac_update() returned error\n");
  298. goto exit;
  299. }
  300. if (fwrite(output, 1, olen, fout) != olen) {
  301. mbedtls_fprintf(stderr, "fwrite(%ld bytes) failed\n", (long) olen);
  302. goto exit;
  303. }
  304. }
  305. if (mbedtls_cipher_finish(&cipher_ctx, output, &olen) != 0) {
  306. mbedtls_fprintf(stderr, "mbedtls_cipher_finish() returned error\n");
  307. goto exit;
  308. }
  309. if (mbedtls_md_hmac_update(&md_ctx, output, olen) != 0) {
  310. mbedtls_fprintf(stderr, "mbedtls_md_hmac_update() returned error\n");
  311. goto exit;
  312. }
  313. if (fwrite(output, 1, olen, fout) != olen) {
  314. mbedtls_fprintf(stderr, "fwrite(%ld bytes) failed\n", (long) olen);
  315. goto exit;
  316. }
  317. /*
  318. * Finally write the HMAC.
  319. */
  320. if (mbedtls_md_hmac_finish(&md_ctx, digest) != 0) {
  321. mbedtls_fprintf(stderr, "mbedtls_md_hmac_finish() returned error\n");
  322. goto exit;
  323. }
  324. if (fwrite(digest, 1, mbedtls_md_get_size(md_info), fout) != mbedtls_md_get_size(md_info)) {
  325. mbedtls_fprintf(stderr, "fwrite(%d bytes) failed\n", mbedtls_md_get_size(md_info));
  326. goto exit;
  327. }
  328. }
  329. if (mode == MODE_DECRYPT) {
  330. /*
  331. * The encrypted file must be structured as follows:
  332. *
  333. * 00 .. 15 Initialization Vector
  334. * 16 .. 31 Encrypted Block #1
  335. * ..
  336. * N*16 .. (N+1)*16 - 1 Encrypted Block #N
  337. * (N+1)*16 .. (N+1)*16 + n Hash(ciphertext)
  338. */
  339. if (filesize < 16 + mbedtls_md_get_size(md_info)) {
  340. mbedtls_fprintf(stderr, "File too short to be encrypted.\n");
  341. goto exit;
  342. }
  343. if (mbedtls_cipher_get_block_size(&cipher_ctx) == 0) {
  344. mbedtls_fprintf(stderr, "Invalid cipher block size: 0. \n");
  345. goto exit;
  346. }
  347. /*
  348. * Check the file size.
  349. */
  350. if (mbedtls_cipher_info_get_mode(cipher_info) != MBEDTLS_MODE_GCM &&
  351. ((filesize - mbedtls_md_get_size(md_info)) %
  352. mbedtls_cipher_get_block_size(&cipher_ctx)) != 0) {
  353. mbedtls_fprintf(stderr, "File content not a multiple of the block size (%u).\n",
  354. mbedtls_cipher_get_block_size(&cipher_ctx));
  355. goto exit;
  356. }
  357. /*
  358. * Subtract the IV + HMAC length.
  359. */
  360. filesize -= (16 + mbedtls_md_get_size(md_info));
  361. /*
  362. * Read the IV and original filesize modulo 16.
  363. */
  364. if (fread(buffer, 1, 16, fin) != 16) {
  365. mbedtls_fprintf(stderr, "fread(%d bytes) failed\n", 16);
  366. goto exit;
  367. }
  368. memcpy(IV, buffer, 16);
  369. /*
  370. * Hash the IV and the secret key together 8192 times
  371. * using the result to setup the AES context and HMAC.
  372. */
  373. memset(digest, 0, 32);
  374. memcpy(digest, IV, 16);
  375. for (i = 0; i < 8192; i++) {
  376. if (mbedtls_md_starts(&md_ctx) != 0) {
  377. mbedtls_fprintf(stderr, "mbedtls_md_starts() returned error\n");
  378. goto exit;
  379. }
  380. if (mbedtls_md_update(&md_ctx, digest, 32) != 0) {
  381. mbedtls_fprintf(stderr, "mbedtls_md_update() returned error\n");
  382. goto exit;
  383. }
  384. if (mbedtls_md_update(&md_ctx, key, keylen) != 0) {
  385. mbedtls_fprintf(stderr, "mbedtls_md_update() returned error\n");
  386. goto exit;
  387. }
  388. if (mbedtls_md_finish(&md_ctx, digest) != 0) {
  389. mbedtls_fprintf(stderr, "mbedtls_md_finish() returned error\n");
  390. goto exit;
  391. }
  392. }
  393. if (mbedtls_cipher_setkey(&cipher_ctx,
  394. digest,
  395. (int) mbedtls_cipher_info_get_key_bitlen(cipher_info),
  396. MBEDTLS_DECRYPT) != 0) {
  397. mbedtls_fprintf(stderr, "mbedtls_cipher_setkey() returned error\n");
  398. goto exit;
  399. }
  400. if (mbedtls_cipher_set_iv(&cipher_ctx, IV, 16) != 0) {
  401. mbedtls_fprintf(stderr, "mbedtls_cipher_set_iv() returned error\n");
  402. goto exit;
  403. }
  404. if (mbedtls_cipher_reset(&cipher_ctx) != 0) {
  405. mbedtls_fprintf(stderr, "mbedtls_cipher_reset() returned error\n");
  406. goto exit;
  407. }
  408. if (mbedtls_md_hmac_starts(&md_ctx, digest, 32) != 0) {
  409. mbedtls_fprintf(stderr, "mbedtls_md_hmac_starts() returned error\n");
  410. goto exit;
  411. }
  412. /*
  413. * Decrypt and write the plaintext.
  414. */
  415. for (offset = 0; offset < filesize; offset += mbedtls_cipher_get_block_size(&cipher_ctx)) {
  416. ilen = ((unsigned int) filesize - offset > mbedtls_cipher_get_block_size(&cipher_ctx)) ?
  417. mbedtls_cipher_get_block_size(&cipher_ctx) : (unsigned int) (filesize - offset);
  418. if (fread(buffer, 1, ilen, fin) != ilen) {
  419. mbedtls_fprintf(stderr, "fread(%u bytes) failed\n",
  420. mbedtls_cipher_get_block_size(&cipher_ctx));
  421. goto exit;
  422. }
  423. if (mbedtls_md_hmac_update(&md_ctx, buffer, ilen) != 0) {
  424. mbedtls_fprintf(stderr, "mbedtls_md_hmac_update() returned error\n");
  425. goto exit;
  426. }
  427. if (mbedtls_cipher_update(&cipher_ctx, buffer, ilen, output,
  428. &olen) != 0) {
  429. mbedtls_fprintf(stderr, "mbedtls_cipher_update() returned error\n");
  430. goto exit;
  431. }
  432. if (fwrite(output, 1, olen, fout) != olen) {
  433. mbedtls_fprintf(stderr, "fwrite(%ld bytes) failed\n", (long) olen);
  434. goto exit;
  435. }
  436. }
  437. /*
  438. * Verify the message authentication code.
  439. */
  440. if (mbedtls_md_hmac_finish(&md_ctx, digest) != 0) {
  441. mbedtls_fprintf(stderr, "mbedtls_md_hmac_finish() returned error\n");
  442. goto exit;
  443. }
  444. if (fread(buffer, 1, mbedtls_md_get_size(md_info), fin) != mbedtls_md_get_size(md_info)) {
  445. mbedtls_fprintf(stderr, "fread(%d bytes) failed\n", mbedtls_md_get_size(md_info));
  446. goto exit;
  447. }
  448. /* Use constant-time buffer comparison */
  449. diff = 0;
  450. for (i = 0; i < mbedtls_md_get_size(md_info); i++) {
  451. diff |= digest[i] ^ buffer[i];
  452. }
  453. if (diff != 0) {
  454. mbedtls_fprintf(stderr, "HMAC check failed: wrong key, "
  455. "or file corrupted.\n");
  456. goto exit;
  457. }
  458. /*
  459. * Write the final block of data
  460. */
  461. if (mbedtls_cipher_finish(&cipher_ctx, output, &olen) != 0) {
  462. mbedtls_fprintf(stderr, "mbedtls_cipher_finish() returned error\n");
  463. goto exit;
  464. }
  465. if (fwrite(output, 1, olen, fout) != olen) {
  466. mbedtls_fprintf(stderr, "fwrite(%ld bytes) failed\n", (long) olen);
  467. goto exit;
  468. }
  469. }
  470. exit_code = MBEDTLS_EXIT_SUCCESS;
  471. exit:
  472. if (fin) {
  473. fclose(fin);
  474. }
  475. if (fout) {
  476. fclose(fout);
  477. }
  478. /* Zeroize all command line arguments to also cover
  479. the case when the user has missed or reordered some,
  480. in which case the key might not be in argv[6]. */
  481. for (i = 0; i < argc; i++) {
  482. mbedtls_platform_zeroize(argv[i], strlen(argv[i]));
  483. }
  484. mbedtls_platform_zeroize(IV, sizeof(IV));
  485. mbedtls_platform_zeroize(key, sizeof(key));
  486. mbedtls_platform_zeroize(buffer, sizeof(buffer));
  487. mbedtls_platform_zeroize(output, sizeof(output));
  488. mbedtls_platform_zeroize(digest, sizeof(digest));
  489. mbedtls_cipher_free(&cipher_ctx);
  490. mbedtls_md_free(&md_ctx);
  491. mbedtls_exit(exit_code);
  492. }
  493. #endif /* MBEDTLS_CIPHER_C && MBEDTLS_MD_C && MBEDTLS_FS_IO */