scryptenc.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. /*-
  2. * Copyright 2009 Colin Percival
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  15. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  18. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  20. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  21. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  22. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  23. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  24. * SUCH DAMAGE.
  25. *
  26. * This file was originally written by Colin Percival as part of the Tarsnap
  27. * online backup system.
  28. */
  29. #include <assert.h>
  30. #include <inttypes.h>
  31. #include <stdint.h>
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #include "crypto_aes.h"
  36. #include "crypto_aesctr.h"
  37. #include "crypto_entropy.h"
  38. #include "crypto_verify_bytes.h"
  39. #include "humansize.h"
  40. #include "insecure_memzero.h"
  41. #include "sha256.h"
  42. #include "sysendian.h"
  43. #include "warnp.h"
  44. #include "crypto_scrypt.h"
  45. #include "memlimit.h"
  46. #include "scryptenc_cpuperf.h"
  47. #include "scryptenc.h"
  48. #define ENCBLOCK 65536
  49. static int pickparams(size_t, double, double,
  50. int *, uint32_t *, uint32_t *, int);
  51. static int checkparams(size_t, double, double, int, uint32_t, uint32_t, int,
  52. int);
  53. #ifdef POSIXFAIL_ABSTRACT_DECLARATOR
  54. static int scryptdec_file_load_header(FILE * infile, uint8_t header[static 96]);
  55. #else
  56. static int scryptdec_file_load_header(FILE *, uint8_t[static 96]);
  57. #endif
  58. struct scryptdec_file_cookie {
  59. FILE * infile; /* This is not owned by this cookie. */
  60. uint8_t header[96];
  61. uint8_t dk[64];
  62. };
  63. static void
  64. display_params(int logN, uint32_t r, uint32_t p, size_t memlimit,
  65. double opps, double maxtime)
  66. {
  67. uint64_t N = (uint64_t)(1) << logN;
  68. uint64_t mem_minimum = 128 * r * N;
  69. double expected_seconds = opps > 0 ? (double)(4 * N * r * p) / opps : 0;
  70. char * human_memlimit = humansize(memlimit);
  71. char * human_mem_minimum = humansize(mem_minimum);
  72. /* Parameters */
  73. fprintf(stderr, "Parameters used: N = %" PRIu64 "; r = %" PRIu32
  74. "; p = %" PRIu32 ";\n", N, r, p);
  75. /* Memory */
  76. fprintf(stderr, " Decrypting this file requires at least"
  77. " %s of memory", human_mem_minimum);
  78. if (memlimit > 0)
  79. fprintf(stderr, " (%s available)", human_memlimit);
  80. /* CPU time */
  81. if (opps > 0)
  82. fprintf(stderr, ",\n and will take approximately %.1f "
  83. "seconds (limit: %.1f seconds)", expected_seconds, maxtime);
  84. fprintf(stderr, ".\n");
  85. /* Clean up */
  86. free(human_memlimit);
  87. free(human_mem_minimum);
  88. }
  89. static int
  90. pickparams(size_t maxmem, double maxmemfrac, double maxtime,
  91. int * logN, uint32_t * r, uint32_t * p, int verbose)
  92. {
  93. size_t memlimit;
  94. double opps;
  95. double opslimit;
  96. double maxN, maxrp;
  97. uint64_t checkN;
  98. int rc;
  99. /* Figure out how much memory to use. */
  100. if (memtouse(maxmem, maxmemfrac, &memlimit))
  101. return (SCRYPT_ELIMIT);
  102. /* Figure out how fast the CPU is. */
  103. if ((rc = scryptenc_cpuperf(&opps)) != SCRYPT_OK)
  104. return (rc);
  105. opslimit = opps * maxtime;
  106. /* Allow a minimum of 2^15 salsa20/8 cores. */
  107. if (opslimit < 32768)
  108. opslimit = 32768;
  109. /* Fix r = 8 for now. */
  110. *r = 8;
  111. /*
  112. * The memory limit requires that 128Nr <= memlimit, while the CPU
  113. * limit requires that 4Nrp <= opslimit. If opslimit < memlimit/32,
  114. * opslimit imposes the stronger limit on N.
  115. */
  116. #ifdef DEBUG
  117. fprintf(stderr, "Requiring 128Nr <= %zu, 4Nrp <= %f\n",
  118. memlimit, opslimit);
  119. #endif
  120. if (opslimit < (double)memlimit / 32) {
  121. /* Set p = 1 and choose N based on the CPU limit. */
  122. *p = 1;
  123. maxN = opslimit / (*r * 4);
  124. for (*logN = 1; *logN < 63; *logN += 1) {
  125. checkN = (uint64_t)(1) << *logN;
  126. /*
  127. * Find the largest power of two <= maxN, which is
  128. * also the least power of two > maxN/2.
  129. */
  130. if ((double)checkN > maxN / 2)
  131. break;
  132. }
  133. } else {
  134. /* Set N based on the memory limit. */
  135. maxN = (double)(memlimit / (*r * 128));
  136. for (*logN = 1; *logN < 63; *logN += 1) {
  137. checkN = (uint64_t)(1) << *logN;
  138. if ((double)checkN > maxN / 2)
  139. break;
  140. }
  141. /* Choose p based on the CPU limit. */
  142. checkN = (uint64_t)(1) << *logN;
  143. maxrp = (opslimit / 4) / (double)checkN;
  144. if (maxrp > 0x3fffffff)
  145. maxrp = 0x3fffffff;
  146. *p = (uint32_t)(maxrp) / *r;
  147. }
  148. if (verbose)
  149. display_params(*logN, *r, *p, memlimit, opps, maxtime);
  150. /* Success! */
  151. return (SCRYPT_OK);
  152. }
  153. static int
  154. checkparams(size_t maxmem, double maxmemfrac, double maxtime,
  155. int logN, uint32_t r, uint32_t p, int verbose, int force)
  156. {
  157. size_t memlimit;
  158. double opps;
  159. double opslimit;
  160. uint64_t N;
  161. int rc;
  162. /* Sanity-check values. */
  163. if ((logN < 1) || (logN > 63))
  164. return (SCRYPT_EINVAL);
  165. if ((uint64_t)(r) * (uint64_t)(p) >= 0x40000000)
  166. return (SCRYPT_EINVAL);
  167. if ((r == 0) || (p == 0))
  168. return (SCRYPT_EINVAL);
  169. /* Are we forcing decryption, regardless of resource limits? */
  170. if (!force) {
  171. /* Figure out the maximum amount of memory we can use. */
  172. if (memtouse(maxmem, maxmemfrac, &memlimit))
  173. return (SCRYPT_ELIMIT);
  174. /* Figure out how fast the CPU is. */
  175. if ((rc = scryptenc_cpuperf(&opps)) != SCRYPT_OK)
  176. return (rc);
  177. opslimit = opps * maxtime;
  178. if (verbose)
  179. display_params(logN, r, p, memlimit, opps, maxtime);
  180. /* Check limits. */
  181. N = (uint64_t)(1) << logN;
  182. if (((memlimit / N) / r < 128) &&
  183. (((opslimit / (double)N) / r) / p < 4))
  184. return (SCRYPT_EBIGSLOW);
  185. if ((memlimit / N) / r < 128)
  186. return (SCRYPT_ETOOBIG);
  187. if (((opslimit / (double)N) / r) / p < 4)
  188. return (SCRYPT_ETOOSLOW);
  189. } else {
  190. /* We have no limit. */
  191. memlimit = 0;
  192. opps = 0;
  193. if (verbose)
  194. display_params(logN, r, p, memlimit, opps, maxtime);
  195. }
  196. /* Success! */
  197. return (SCRYPT_OK);
  198. }
  199. /*
  200. * NOTE: The caller is responsible for sanitizing ${dk}, including if this
  201. * function fails.
  202. */
  203. static int
  204. scryptenc_setup(uint8_t header[96], uint8_t dk[64],
  205. const uint8_t * passwd, size_t passwdlen,
  206. struct scryptenc_params * P, int verbose, int force)
  207. {
  208. uint8_t salt[32];
  209. uint8_t hbuf[32];
  210. uint64_t N;
  211. SHA256_CTX ctx;
  212. uint8_t * key_hmac = &dk[32];
  213. HMAC_SHA256_CTX hctx;
  214. int rc;
  215. /* Determine parameters. */
  216. if (P->logN != 0) {
  217. /* Check logN, r, p. */
  218. if ((rc = checkparams(P->maxmem, P->maxmemfrac, P->maxtime,
  219. P->logN, P->r, P->p, verbose, force)) != 0) {
  220. /* Warn about resource limit, but suppress the error. */
  221. if ((rc == SCRYPT_ETOOBIG) || (rc == SCRYPT_EBIGSLOW))
  222. warn0("Warning: Explicit parameters"
  223. " might exceed memory limit");
  224. if ((rc == SCRYPT_ETOOSLOW) || (rc == SCRYPT_EBIGSLOW))
  225. warn0("Warning: Explicit parameters"
  226. " might exceed time limit");
  227. if ((rc == SCRYPT_ETOOBIG) || (rc == SCRYPT_ETOOSLOW) ||
  228. (rc == SCRYPT_EBIGSLOW))
  229. rc = 0;
  230. /* Provide a more meaningful error message. */
  231. if (rc == SCRYPT_EINVAL)
  232. rc = SCRYPT_EPARAM;
  233. /* Bail if we haven't suppressed the error. */
  234. if (rc != 0)
  235. return (rc);
  236. }
  237. } else {
  238. /* Pick values for N, r, p. */
  239. if ((rc = pickparams(P->maxmem, P->maxmemfrac, P->maxtime,
  240. &P->logN, &P->r, &P->p, verbose)) != 0)
  241. return (rc);
  242. }
  243. /* Sanity check. */
  244. assert((P->logN > 0) && (P->logN < 64));
  245. /* Set N. */
  246. N = (uint64_t)(1) << P->logN;
  247. /* Get some salt. */
  248. if (crypto_entropy_read(salt, 32))
  249. return (SCRYPT_ESALT);
  250. /* Generate the derived keys. */
  251. if (crypto_scrypt(passwd, passwdlen, salt, 32, N, P->r, P->p, dk, 64))
  252. return (SCRYPT_EKEY);
  253. /* Construct the file header. */
  254. memcpy(header, "scrypt", 6);
  255. header[6] = 0;
  256. header[7] = P->logN & 0xff;
  257. be32enc(&header[8], P->r);
  258. be32enc(&header[12], P->p);
  259. memcpy(&header[16], salt, 32);
  260. /* Add header checksum. */
  261. SHA256_Init(&ctx);
  262. SHA256_Update(&ctx, header, 48);
  263. SHA256_Final(hbuf, &ctx);
  264. memcpy(&header[48], hbuf, 16);
  265. /* Add header signature (used for verifying password). */
  266. HMAC_SHA256_Init(&hctx, key_hmac, 32);
  267. HMAC_SHA256_Update(&hctx, header, 64);
  268. HMAC_SHA256_Final(hbuf, &hctx);
  269. memcpy(&header[64], hbuf, 32);
  270. /* Success! */
  271. return (SCRYPT_OK);
  272. }
  273. /**
  274. * scryptdec_file_printparams(infile):
  275. * Print the encryption parameters (N, r, p) used for the encrypted ${infile}.
  276. */
  277. int
  278. scryptdec_file_printparams(FILE * infile)
  279. {
  280. uint8_t header[96];
  281. int logN;
  282. uint32_t r;
  283. uint32_t p;
  284. int rc;
  285. /* Load the header. */
  286. if ((rc = scryptdec_file_load_header(infile, header)) != 0)
  287. goto err0;
  288. /* Parse N, r, p. */
  289. logN = header[7];
  290. r = be32dec(&header[8]);
  291. p = be32dec(&header[12]);
  292. /* Print parameters. */
  293. display_params(logN, r, p, 0, 0, 0);
  294. /* Success! */
  295. return (SCRYPT_OK);
  296. err0:
  297. /* Failure! */
  298. return (rc);
  299. }
  300. /*
  301. * NOTE: The caller is responsible for sanitizing ${dk}, including if this
  302. * function fails.
  303. */
  304. static int
  305. scryptdec_setup(const uint8_t header[96], uint8_t dk[64],
  306. const uint8_t * passwd, size_t passwdlen,
  307. struct scryptenc_params * P, int verbose,
  308. int force)
  309. {
  310. uint8_t salt[32];
  311. uint8_t hbuf[32];
  312. uint64_t N;
  313. SHA256_CTX ctx;
  314. uint8_t * key_hmac = &dk[32];
  315. HMAC_SHA256_CTX hctx;
  316. int rc;
  317. /* Parse N, r, p, salt. */
  318. P->logN = header[7];
  319. P->r = be32dec(&header[8]);
  320. P->p = be32dec(&header[12]);
  321. memcpy(salt, &header[16], 32);
  322. /* Verify header checksum. */
  323. SHA256_Init(&ctx);
  324. SHA256_Update(&ctx, header, 48);
  325. SHA256_Final(hbuf, &ctx);
  326. if (crypto_verify_bytes(&header[48], hbuf, 16))
  327. return (SCRYPT_EINVAL);
  328. /*
  329. * Check whether the provided parameters are valid and whether the
  330. * key derivation function can be computed within the allowed memory
  331. * and CPU time, unless the user chose to disable this test.
  332. */
  333. if ((rc = checkparams(P->maxmem, P->maxmemfrac, P->maxtime, P->logN,
  334. P->r, P->p, verbose, force)) != 0)
  335. return (rc);
  336. /* Compute the derived keys. */
  337. N = (uint64_t)(1) << P->logN;
  338. if (crypto_scrypt(passwd, passwdlen, salt, 32, N, P->r, P->p, dk, 64))
  339. return (SCRYPT_EKEY);
  340. /* Check header signature (i.e., verify password). */
  341. HMAC_SHA256_Init(&hctx, key_hmac, 32);
  342. HMAC_SHA256_Update(&hctx, header, 64);
  343. HMAC_SHA256_Final(hbuf, &hctx);
  344. if (crypto_verify_bytes(hbuf, &header[64], 32))
  345. return (SCRYPT_EPASS);
  346. /* Success! */
  347. return (SCRYPT_OK);
  348. }
  349. /**
  350. * scryptenc_buf(inbuf, inbuflen, outbuf, passwd, passwdlen,
  351. * params, verbose, force):
  352. * Encrypt ${inbuflen} bytes from ${inbuf}, writing the resulting
  353. * ${inbuflen} + 128 bytes to ${outbuf}. If ${force} is 1, do not check
  354. * whether decryption will exceed the estimated available memory or time.
  355. * The explicit parameters within ${params} must be zero or must all be
  356. * non-zero. If explicit parameters are used and the computation is estimated
  357. * to exceed resource limits, print a warning instead of returning an error.
  358. * Return the explicit parameters used via ${params}.
  359. */
  360. int
  361. scryptenc_buf(const uint8_t * inbuf, size_t inbuflen, uint8_t * outbuf,
  362. const uint8_t * passwd, size_t passwdlen,
  363. struct scryptenc_params * P, int verbose, int force)
  364. {
  365. uint8_t dk[64];
  366. uint8_t hbuf[32];
  367. uint8_t header[96];
  368. uint8_t * key_enc = dk;
  369. uint8_t * key_hmac = &dk[32];
  370. int rc;
  371. HMAC_SHA256_CTX hctx;
  372. struct crypto_aes_key * key_enc_exp;
  373. struct crypto_aesctr * AES;
  374. /* The explicit parameters must be zero, or all non-zero. */
  375. assert(((P->logN == 0) && (P->r == 0) && (P->p == 0)) ||
  376. ((P->logN != 0) && (P->r != 0) && (P->p != 0)));
  377. /* Generate the header and derived key. */
  378. if ((rc = scryptenc_setup(header, dk, passwd, passwdlen,
  379. P, verbose, force)) != 0)
  380. goto err1;
  381. /* Copy header into output buffer. */
  382. memcpy(outbuf, header, 96);
  383. /* Encrypt data. */
  384. if ((key_enc_exp = crypto_aes_key_expand(key_enc, 32)) == NULL) {
  385. rc = SCRYPT_EOPENSSL;
  386. goto err1;
  387. }
  388. if ((AES = crypto_aesctr_init(key_enc_exp, 0)) == NULL) {
  389. crypto_aes_key_free(key_enc_exp);
  390. rc = SCRYPT_ENOMEM;
  391. goto err1;
  392. }
  393. crypto_aesctr_stream(AES, inbuf, &outbuf[96], inbuflen);
  394. crypto_aesctr_free(AES);
  395. crypto_aes_key_free(key_enc_exp);
  396. /* Add signature. */
  397. HMAC_SHA256_Init(&hctx, key_hmac, 32);
  398. HMAC_SHA256_Update(&hctx, outbuf, 96 + inbuflen);
  399. HMAC_SHA256_Final(hbuf, &hctx);
  400. memcpy(&outbuf[96 + inbuflen], hbuf, 32);
  401. /* Zero sensitive data. */
  402. insecure_memzero(dk, 64);
  403. /* Success! */
  404. return (SCRYPT_OK);
  405. err1:
  406. insecure_memzero(dk, 64);
  407. /* Failure! */
  408. return (rc);
  409. }
  410. /**
  411. * scryptdec_buf(inbuf, inbuflen, outbuf, outlen, passwd, passwdlen,
  412. * params, verbose, force):
  413. * Decrypt ${inbuflen} bytes from ${inbuf}, writing the result into ${outbuf}
  414. * and the decrypted data length to ${outlen}. The allocated length of
  415. * ${outbuf} must be at least ${inbuflen}. If ${force} is 1, do not check
  416. * whether decryption will exceed the estimated available memory or time.
  417. * The explicit parameters within ${params} must be zero. Return the explicit
  418. * parameters used via ${params}.
  419. */
  420. int
  421. scryptdec_buf(const uint8_t * inbuf, size_t inbuflen, uint8_t * outbuf,
  422. size_t * outlen, const uint8_t * passwd, size_t passwdlen,
  423. struct scryptenc_params * P, int verbose,
  424. int force)
  425. {
  426. uint8_t hbuf[32];
  427. uint8_t dk[64];
  428. uint8_t * key_enc = dk;
  429. uint8_t * key_hmac = &dk[32];
  430. int rc;
  431. HMAC_SHA256_CTX hctx;
  432. struct crypto_aes_key * key_enc_exp;
  433. struct crypto_aesctr * AES;
  434. /* The explicit parameters must be zero. */
  435. assert((P->logN == 0) && (P->r == 0) && (P->p == 0));
  436. /*
  437. * All versions of the scrypt format will start with "scrypt" and
  438. * have at least 7 bytes of header.
  439. */
  440. if ((inbuflen < 7) || (memcmp(inbuf, "scrypt", 6) != 0)) {
  441. rc = SCRYPT_EINVAL;
  442. goto err0;
  443. }
  444. /* Check the format. */
  445. if (inbuf[6] != 0) {
  446. rc = SCRYPT_EVERSION;
  447. goto err0;
  448. }
  449. /* We must have at least 128 bytes. */
  450. if (inbuflen < 128) {
  451. rc = SCRYPT_EINVAL;
  452. goto err0;
  453. }
  454. /* Parse the header and generate derived keys. */
  455. if ((rc = scryptdec_setup(inbuf, dk, passwd, passwdlen,
  456. P, verbose, force)) != 0)
  457. goto err1;
  458. /* Decrypt data. */
  459. if ((key_enc_exp = crypto_aes_key_expand(key_enc, 32)) == NULL) {
  460. rc = SCRYPT_EOPENSSL;
  461. goto err1;
  462. }
  463. if ((AES = crypto_aesctr_init(key_enc_exp, 0)) == NULL) {
  464. crypto_aes_key_free(key_enc_exp);
  465. rc = SCRYPT_ENOMEM;
  466. goto err1;
  467. }
  468. crypto_aesctr_stream(AES, &inbuf[96], outbuf, inbuflen - 128);
  469. crypto_aesctr_free(AES);
  470. crypto_aes_key_free(key_enc_exp);
  471. *outlen = inbuflen - 128;
  472. /* Verify signature. */
  473. HMAC_SHA256_Init(&hctx, key_hmac, 32);
  474. HMAC_SHA256_Update(&hctx, inbuf, inbuflen - 32);
  475. HMAC_SHA256_Final(hbuf, &hctx);
  476. if (crypto_verify_bytes(hbuf, &inbuf[inbuflen - 32], 32)) {
  477. rc = SCRYPT_EINVAL;
  478. goto err1;
  479. }
  480. /* Zero sensitive data. */
  481. insecure_memzero(dk, 64);
  482. /* Success! */
  483. return (SCRYPT_OK);
  484. err1:
  485. insecure_memzero(dk, 64);
  486. err0:
  487. /* Failure! */
  488. return (rc);
  489. }
  490. /**
  491. * scryptenc_file(infile, outfile, passwd, passwdlen, params, verbose, force):
  492. * Read a stream from ${infile} and encrypt it, writing the resulting stream
  493. * to ${outfile}. If ${force} is 1, do not check whether decryption will
  494. * exceed the estimated available memory or time. The explicit parameters
  495. * within ${params} must be zero or must all be non-zero. If explicit
  496. * parameters are used and the computation is estimated to exceed resource
  497. * limits, print a warning instead of returning an error. Return the explicit
  498. * parameters used via ${params}.
  499. */
  500. int
  501. scryptenc_file(FILE * infile, FILE * outfile,
  502. const uint8_t * passwd, size_t passwdlen,
  503. struct scryptenc_params * P, int verbose, int force)
  504. {
  505. uint8_t buf[ENCBLOCK];
  506. uint8_t dk[64];
  507. uint8_t hbuf[32];
  508. uint8_t header[96];
  509. uint8_t * key_enc = dk;
  510. uint8_t * key_hmac = &dk[32];
  511. size_t readlen;
  512. HMAC_SHA256_CTX hctx;
  513. struct crypto_aes_key * key_enc_exp;
  514. struct crypto_aesctr * AES;
  515. int rc;
  516. /* The explicit parameters must be zero, or all non-zero. */
  517. assert(((P->logN == 0) && (P->r == 0) && (P->p == 0)) ||
  518. ((P->logN != 0) && (P->r != 0) && (P->p != 0)));
  519. /* Generate the header and derived key. */
  520. if ((rc = scryptenc_setup(header, dk, passwd, passwdlen,
  521. P, verbose, force)) != 0)
  522. goto err1;
  523. /* Hash and write the header. */
  524. HMAC_SHA256_Init(&hctx, key_hmac, 32);
  525. HMAC_SHA256_Update(&hctx, header, 96);
  526. if (fwrite(header, 96, 1, outfile) != 1) {
  527. rc = SCRYPT_EWRFILE;
  528. goto err1;
  529. }
  530. /*
  531. * Read blocks of data, encrypt them, and write them out; hash the
  532. * data as it is produced.
  533. */
  534. if ((key_enc_exp = crypto_aes_key_expand(key_enc, 32)) == NULL) {
  535. rc = SCRYPT_EOPENSSL;
  536. goto err1;
  537. }
  538. if ((AES = crypto_aesctr_init(key_enc_exp, 0)) == NULL) {
  539. crypto_aes_key_free(key_enc_exp);
  540. rc = SCRYPT_ENOMEM;
  541. goto err1;
  542. }
  543. do {
  544. if ((readlen = fread(buf, 1, ENCBLOCK, infile)) == 0)
  545. break;
  546. crypto_aesctr_stream(AES, buf, buf, readlen);
  547. HMAC_SHA256_Update(&hctx, buf, readlen);
  548. if (fwrite(buf, 1, readlen, outfile) < readlen) {
  549. crypto_aesctr_free(AES);
  550. rc = SCRYPT_EWRFILE;
  551. goto err1;
  552. }
  553. } while (1);
  554. crypto_aesctr_free(AES);
  555. crypto_aes_key_free(key_enc_exp);
  556. /* Did we exit the loop due to a read error? */
  557. if (ferror(infile)) {
  558. rc = SCRYPT_ERDFILE;
  559. goto err1;
  560. }
  561. /* Compute the final HMAC and output it. */
  562. HMAC_SHA256_Final(hbuf, &hctx);
  563. if (fwrite(hbuf, 32, 1, outfile) != 1) {
  564. rc = SCRYPT_EWRFILE;
  565. goto err1;
  566. }
  567. /* Zero sensitive data. */
  568. insecure_memzero(dk, 64);
  569. /* Success! */
  570. return (SCRYPT_OK);
  571. err1:
  572. insecure_memzero(dk, 64);
  573. /* Failure! */
  574. return (rc);
  575. }
  576. /**
  577. * scryptdec_file_cookie_free(cookie):
  578. * Free the ${cookie}.
  579. */
  580. void
  581. scryptdec_file_cookie_free(struct scryptdec_file_cookie * C)
  582. {
  583. /* Behave consistently with free(NULL). */
  584. if (C == NULL)
  585. return;
  586. /* Zero sensitive data. */
  587. insecure_memzero(C->dk, 64);
  588. /* We do not free C->infile because it is not owned by this cookie. */
  589. /* Free the cookie. */
  590. free(C);
  591. }
  592. /* Load the header and check the magic. */
  593. static int
  594. scryptdec_file_load_header(FILE * infile, uint8_t header[static 96])
  595. {
  596. int rc;
  597. /*
  598. * Read the first 7 bytes of the file; all future versions of scrypt
  599. * are guaranteed to have at least 7 bytes of header.
  600. */
  601. if (fread(header, 7, 1, infile) < 1) {
  602. if (ferror(infile)) {
  603. rc = SCRYPT_ERDFILE;
  604. goto err0;
  605. } else {
  606. rc = SCRYPT_EINVAL;
  607. goto err0;
  608. }
  609. }
  610. /* Do we have the right magic? */
  611. if (memcmp(header, "scrypt", 6)) {
  612. rc = SCRYPT_EINVAL;
  613. goto err0;
  614. }
  615. if (header[6] != 0) {
  616. rc = SCRYPT_EVERSION;
  617. goto err0;
  618. }
  619. /*
  620. * Read another 89 bytes of the file; version 0 of the scrypt file
  621. * format has a 96-byte header.
  622. */
  623. if (fread(&header[7], 89, 1, infile) < 1) {
  624. if (ferror(infile)) {
  625. rc = SCRYPT_ERDFILE;
  626. goto err0;
  627. } else {
  628. rc = SCRYPT_EINVAL;
  629. goto err0;
  630. }
  631. }
  632. /* Success! */
  633. return (SCRYPT_OK);
  634. err0:
  635. /* Failure! */
  636. return (rc);
  637. }
  638. /**
  639. * scryptdec_file_prep(infile, passwd, passwdlen, params, verbose, force,
  640. * cookie):
  641. * Prepare to decrypt ${infile}, including checking the passphrase. Allocate
  642. * a cookie at ${cookie}. After calling this function, ${infile} should not
  643. * be modified until the decryption is completed by scryptdec_file_copy().
  644. * If ${force} is 1, do not check whether decryption will exceed the estimated
  645. * available memory or time. The explicit parameters within ${params} must be
  646. * zero. Return the explicit parameters to be used via ${params}.
  647. */
  648. int
  649. scryptdec_file_prep(FILE * infile, const uint8_t * passwd,
  650. size_t passwdlen, struct scryptenc_params * P,
  651. int verbose, int force, struct scryptdec_file_cookie ** cookie)
  652. {
  653. struct scryptdec_file_cookie * C;
  654. int rc;
  655. /* The explicit parameters must be zero. */
  656. assert((P->logN == 0) && (P->r == 0) && (P->p == 0));
  657. /* Allocate the cookie. */
  658. if ((C = malloc(sizeof(struct scryptdec_file_cookie))) == NULL)
  659. return (SCRYPT_ENOMEM);
  660. C->infile = infile;
  661. /* Load the header. */
  662. if ((rc = scryptdec_file_load_header(infile, C->header)) != 0)
  663. goto err1;
  664. /* Parse the header and generate derived keys. */
  665. if ((rc = scryptdec_setup(C->header, C->dk, passwd, passwdlen,
  666. P, verbose, force)) != 0)
  667. goto err1;
  668. /* Set cookie for calling function. */
  669. *cookie = C;
  670. /* Success! */
  671. return (SCRYPT_OK);
  672. err1:
  673. scryptdec_file_cookie_free(C);
  674. /* Failure! */
  675. return (rc);
  676. }
  677. /**
  678. * scryptdec_file_copy(cookie, outfile):
  679. * Read a stream from the file that was passed into the ${cookie} by
  680. * scryptdec_file_prep(), decrypt it, and write the resulting stream to
  681. * ${outfile}. After this function completes, it is safe to modify/close
  682. * ${outfile} and the ${infile} which was given to scryptdec_file_prep().
  683. */
  684. int
  685. scryptdec_file_copy(struct scryptdec_file_cookie * C, FILE * outfile)
  686. {
  687. uint8_t buf[ENCBLOCK + 32];
  688. uint8_t hbuf[32];
  689. uint8_t * key_enc;
  690. uint8_t * key_hmac;
  691. size_t buflen = 0;
  692. size_t readlen;
  693. HMAC_SHA256_CTX hctx;
  694. struct crypto_aes_key * key_enc_exp;
  695. struct crypto_aesctr * AES;
  696. int rc;
  697. /* Sanity check. */
  698. assert(C != NULL);
  699. /* Use existing array for these pointers. */
  700. key_enc = C->dk;
  701. key_hmac = &C->dk[32];
  702. /* Start hashing with the header. */
  703. HMAC_SHA256_Init(&hctx, key_hmac, 32);
  704. HMAC_SHA256_Update(&hctx, C->header, 96);
  705. /*
  706. * We don't know how long the encrypted data block is (we can't know,
  707. * since data can be streamed into 'scrypt enc') so we need to read
  708. * data and decrypt all of it except the final 32 bytes, then check
  709. * if that final 32 bytes is the correct signature.
  710. */
  711. if ((key_enc_exp = crypto_aes_key_expand(key_enc, 32)) == NULL) {
  712. rc = SCRYPT_EOPENSSL;
  713. goto err0;
  714. }
  715. if ((AES = crypto_aesctr_init(key_enc_exp, 0)) == NULL) {
  716. crypto_aes_key_free(key_enc_exp);
  717. rc = SCRYPT_ENOMEM;
  718. goto err0;
  719. }
  720. do {
  721. /* Read data until we have more than 32 bytes of it. */
  722. if ((readlen = fread(&buf[buflen], 1,
  723. ENCBLOCK + 32 - buflen, C->infile)) == 0)
  724. break;
  725. buflen += readlen;
  726. if (buflen <= 32)
  727. continue;
  728. /*
  729. * Decrypt, hash, and output everything except the last 32
  730. * bytes out of what we have in our buffer.
  731. */
  732. HMAC_SHA256_Update(&hctx, buf, buflen - 32);
  733. crypto_aesctr_stream(AES, buf, buf, buflen - 32);
  734. if (fwrite(buf, 1, buflen - 32, outfile) < buflen - 32) {
  735. crypto_aesctr_free(AES);
  736. rc = SCRYPT_EWRFILE;
  737. goto err0;
  738. }
  739. /* Move the last 32 bytes to the start of the buffer. */
  740. memmove(buf, &buf[buflen - 32], 32);
  741. buflen = 32;
  742. } while (1);
  743. crypto_aesctr_free(AES);
  744. crypto_aes_key_free(key_enc_exp);
  745. /* Did we exit the loop due to a read error? */
  746. if (ferror(C->infile)) {
  747. rc = SCRYPT_ERDFILE;
  748. goto err0;
  749. }
  750. /* Did we read enough data that we *might* have a valid signature? */
  751. if (buflen < 32) {
  752. rc = SCRYPT_EINVAL;
  753. goto err0;
  754. }
  755. /* Verify signature. */
  756. HMAC_SHA256_Final(hbuf, &hctx);
  757. if (crypto_verify_bytes(hbuf, buf, 32)) {
  758. rc = SCRYPT_EINVAL;
  759. goto err0;
  760. }
  761. /* Success! */
  762. return (SCRYPT_OK);
  763. err0:
  764. /* Failure! */
  765. return (rc);
  766. }
  767. /**
  768. * scryptdec_file(infile, outfile, passwd, passwdlen, params, verbose, force):
  769. * Read a stream from ${infile} and decrypt it, writing the resulting stream
  770. * to ${outfile}. If ${force} is 1, do not check whether decryption
  771. * will exceed the estimated available memory or time. The explicit
  772. * parameters within ${params} must be zero. Return the explicit parameters
  773. * used via ${params}.
  774. */
  775. int
  776. scryptdec_file(FILE * infile, FILE * outfile, const uint8_t * passwd,
  777. size_t passwdlen, struct scryptenc_params * P,
  778. int verbose, int force)
  779. {
  780. struct scryptdec_file_cookie * C;
  781. int rc;
  782. /* The explicit parameters must be zero. */
  783. assert((P->logN == 0) && (P->r == 0) && (P->p == 0));
  784. /* Check header, including passphrase. */
  785. if ((rc = scryptdec_file_prep(infile, passwd, passwdlen, P,
  786. verbose, force, &C)) != 0)
  787. goto err0;
  788. /* Copy unencrypted data to outfile. */
  789. if ((rc = scryptdec_file_copy(C, outfile)) != 0)
  790. goto err1;
  791. /* Clean up cookie, attempting to zero sensitive data. */
  792. scryptdec_file_cookie_free(C);
  793. /* Success! */
  794. return (SCRYPT_OK);
  795. err1:
  796. scryptdec_file_cookie_free(C);
  797. err0:
  798. /* Failure! */
  799. return (rc);
  800. }