Add KDFs to providers
[oweals/openssl.git] / providers / default / kdfs / scrypt.c
1 /*
2  * Copyright 2017-2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdlib.h>
11 #include <stdarg.h>
12 #include <string.h>
13 #include <openssl/evp.h>
14 #include <openssl/kdf.h>
15 #include <openssl/err.h>
16 #include <openssl/core_names.h>
17 #include "internal/evp_int.h"
18 #include "internal/numbers.h"
19 #include "internal/provider_algs.h"
20 #include "internal/provider_ctx.h"
21 #include "internal/providercommonerr.h"
22 #include "internal/provider_algs.h"
23
24 #ifndef OPENSSL_NO_SCRYPT
25
26 static OSSL_OP_kdf_newctx_fn kdf_scrypt_new;
27 static OSSL_OP_kdf_freectx_fn kdf_scrypt_free;
28 static OSSL_OP_kdf_reset_fn kdf_scrypt_reset;
29 static OSSL_OP_kdf_derive_fn kdf_scrypt_derive;
30 static OSSL_OP_kdf_settable_ctx_params_fn kdf_scrypt_settable_ctx_params;
31 static OSSL_OP_kdf_set_ctx_params_fn kdf_scrypt_set_ctx_params;
32
33 static int scrypt_alg(const char *pass, size_t passlen,
34                       const unsigned char *salt, size_t saltlen,
35                       uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
36                       unsigned char *key, size_t keylen, EVP_MD *sha256);
37
38 typedef struct {
39     void *provctx;
40     unsigned char *pass;
41     size_t pass_len;
42     unsigned char *salt;
43     size_t salt_len;
44     uint64_t N;
45     uint64_t r, p;
46     uint64_t maxmem_bytes;
47     EVP_MD *sha256;
48 } KDF_SCRYPT;
49
50 static void kdf_scrypt_init(KDF_SCRYPT *ctx);
51
52 static void *kdf_scrypt_new(void *provctx)
53 {
54     KDF_SCRYPT *ctx;
55
56     ctx = OPENSSL_zalloc(sizeof(*ctx));
57     if (ctx == NULL) {
58         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
59         return NULL;
60     }
61     ctx->provctx = provctx;
62     ctx->sha256 = EVP_MD_fetch(PROV_LIBRARY_CONTEXT_OF(provctx),
63                                "sha256", NULL);
64     if (ctx->sha256 == NULL) {
65         OPENSSL_free(ctx);
66         ERR_raise(ERR_LIB_PROV, PROV_R_UNABLE_TO_LOAD_SHA256);
67         return NULL;
68     }
69     kdf_scrypt_init(ctx);
70     return ctx;
71 }
72
73 static void kdf_scrypt_free(void *vctx)
74 {
75     KDF_SCRYPT *ctx = (KDF_SCRYPT *)vctx;
76
77     kdf_scrypt_reset(ctx);
78     EVP_MD_meth_free(ctx->sha256);
79     OPENSSL_free(ctx);
80 }
81
82 static void kdf_scrypt_reset(void *vctx)
83 {
84     KDF_SCRYPT *ctx = (KDF_SCRYPT *)vctx;
85
86     OPENSSL_free(ctx->salt);
87     OPENSSL_clear_free(ctx->pass, ctx->pass_len);
88     memset(ctx, 0, sizeof(*ctx));
89     kdf_scrypt_init(ctx);
90 }
91
92 static void kdf_scrypt_init(KDF_SCRYPT *ctx)
93 {
94     /* Default values are the most conservative recommendation given in the
95      * original paper of C. Percival. Derivation uses roughly 1 GiB of memory
96      * for this parameter choice (approx. 128 * r * N * p bytes).
97      */
98     ctx->N = 1 << 20;
99     ctx->r = 8;
100     ctx->p = 1;
101     ctx->maxmem_bytes = 1025 * 1024 * 1024;
102 }
103
104 static int scrypt_set_membuf(unsigned char **buffer, size_t *buflen,
105                              const OSSL_PARAM *p)
106 {
107     OPENSSL_clear_free(*buffer, *buflen);
108     if (p->data_size == 0) {
109         if ((*buffer = OPENSSL_malloc(1)) == NULL) {
110             ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
111             return 0;
112         }
113     } else if (p->data != NULL) {
114         *buffer = NULL;
115         if (!OSSL_PARAM_get_octet_string(p, (void **)buffer, 0, buflen))
116             return 0;
117     }
118     return 1;
119 }
120
121 static int kdf_scrypt_derive(void *vctx, unsigned char *key,
122                              size_t keylen)
123 {
124     KDF_SCRYPT *ctx = (KDF_SCRYPT *)vctx;
125
126     if (ctx->pass == NULL) {
127         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_PASS);
128         return 0;
129     }
130
131     if (ctx->salt == NULL) {
132         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SALT);
133         return 0;
134     }
135
136     return scrypt_alg((char *)ctx->pass, ctx->pass_len, ctx->salt,
137                       ctx->salt_len, ctx->N, ctx->r, ctx->p,
138                       ctx->maxmem_bytes, key, keylen, ctx->sha256);
139 }
140
141 static int is_power_of_two(uint64_t value)
142 {
143     return (value != 0) && ((value & (value - 1)) == 0);
144 }
145
146 static int kdf_scrypt_set_ctx_params(void *vctx, const OSSL_PARAM params[])
147 {
148     const OSSL_PARAM *p;
149     KDF_SCRYPT *ctx = vctx;
150     uint64_t u64_value;
151
152     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_PASSWORD)) != NULL)
153         if (!scrypt_set_membuf(&ctx->pass, &ctx->pass_len, p))
154             return 0;
155
156     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SALT)) != NULL)
157         if (!scrypt_set_membuf(&ctx->salt, &ctx->salt_len, p))
158             return 0;
159
160     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SCRYPT_N))
161         != NULL) {
162         if (!OSSL_PARAM_get_uint64(p, &u64_value)
163             || u64_value <= 1
164             || !is_power_of_two(u64_value))
165             return 0;
166         ctx->N = u64_value;
167     }
168
169     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SCRYPT_R))
170         != NULL) {
171         if (!OSSL_PARAM_get_uint64(p, &u64_value) || u64_value < 1)
172             return 0;
173         ctx->r = u64_value;
174     }
175
176     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SCRYPT_P))
177         != NULL) {
178         if (!OSSL_PARAM_get_uint64(p, &u64_value) || u64_value < 1)
179             return 0;
180         ctx->p = u64_value;
181     }
182
183     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SCRYPT_MAXMEM))
184         != NULL) {
185         if (!OSSL_PARAM_get_uint64(p, &u64_value) || u64_value < 1)
186             return 0;
187         ctx->maxmem_bytes = u64_value;
188     }
189     return 1;
190 }
191
192 static const OSSL_PARAM *kdf_scrypt_settable_ctx_params(void)
193 {
194     static const OSSL_PARAM known_settable_ctx_params[] = {
195         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_PASSWORD, NULL, 0),
196         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SALT, NULL, 0),
197         OSSL_PARAM_uint64(OSSL_KDF_PARAM_SCRYPT_N, NULL),
198         OSSL_PARAM_uint32(OSSL_KDF_PARAM_SCRYPT_R, NULL),
199         OSSL_PARAM_uint32(OSSL_KDF_PARAM_SCRYPT_P, NULL),
200         OSSL_PARAM_uint64(OSSL_KDF_PARAM_SCRYPT_MAXMEM, NULL),
201         OSSL_PARAM_END
202     };
203     return known_settable_ctx_params;
204 }
205
206 static int kdf_scrypt_get_ctx_params(void *vctx, OSSL_PARAM params[])
207 {
208     OSSL_PARAM *p;
209
210     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
211         return OSSL_PARAM_set_size_t(p, SIZE_MAX);
212     return -2;
213 }
214
215 static const OSSL_PARAM *kdf_scrypt_gettable_ctx_params(void)
216 {
217     static const OSSL_PARAM known_gettable_ctx_params[] = {
218         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
219         OSSL_PARAM_END
220     };
221     return known_gettable_ctx_params;
222 }
223
224 const OSSL_DISPATCH kdf_scrypt_functions[] = {
225     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))kdf_scrypt_new },
226     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))kdf_scrypt_free },
227     { OSSL_FUNC_KDF_RESET, (void(*)(void))kdf_scrypt_reset },
228     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))kdf_scrypt_derive },
229     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
230       (void(*)(void))kdf_scrypt_settable_ctx_params },
231     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))kdf_scrypt_set_ctx_params },
232     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
233       (void(*)(void))kdf_scrypt_gettable_ctx_params },
234     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))kdf_scrypt_get_ctx_params },
235     { 0, NULL }
236 };
237
238 #define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
239 static void salsa208_word_specification(uint32_t inout[16])
240 {
241     int i;
242     uint32_t x[16];
243
244     memcpy(x, inout, sizeof(x));
245     for (i = 8; i > 0; i -= 2) {
246         x[4] ^= R(x[0] + x[12], 7);
247         x[8] ^= R(x[4] + x[0], 9);
248         x[12] ^= R(x[8] + x[4], 13);
249         x[0] ^= R(x[12] + x[8], 18);
250         x[9] ^= R(x[5] + x[1], 7);
251         x[13] ^= R(x[9] + x[5], 9);
252         x[1] ^= R(x[13] + x[9], 13);
253         x[5] ^= R(x[1] + x[13], 18);
254         x[14] ^= R(x[10] + x[6], 7);
255         x[2] ^= R(x[14] + x[10], 9);
256         x[6] ^= R(x[2] + x[14], 13);
257         x[10] ^= R(x[6] + x[2], 18);
258         x[3] ^= R(x[15] + x[11], 7);
259         x[7] ^= R(x[3] + x[15], 9);
260         x[11] ^= R(x[7] + x[3], 13);
261         x[15] ^= R(x[11] + x[7], 18);
262         x[1] ^= R(x[0] + x[3], 7);
263         x[2] ^= R(x[1] + x[0], 9);
264         x[3] ^= R(x[2] + x[1], 13);
265         x[0] ^= R(x[3] + x[2], 18);
266         x[6] ^= R(x[5] + x[4], 7);
267         x[7] ^= R(x[6] + x[5], 9);
268         x[4] ^= R(x[7] + x[6], 13);
269         x[5] ^= R(x[4] + x[7], 18);
270         x[11] ^= R(x[10] + x[9], 7);
271         x[8] ^= R(x[11] + x[10], 9);
272         x[9] ^= R(x[8] + x[11], 13);
273         x[10] ^= R(x[9] + x[8], 18);
274         x[12] ^= R(x[15] + x[14], 7);
275         x[13] ^= R(x[12] + x[15], 9);
276         x[14] ^= R(x[13] + x[12], 13);
277         x[15] ^= R(x[14] + x[13], 18);
278     }
279     for (i = 0; i < 16; ++i)
280         inout[i] += x[i];
281     OPENSSL_cleanse(x, sizeof(x));
282 }
283
284 static void scryptBlockMix(uint32_t *B_, uint32_t *B, uint64_t r)
285 {
286     uint64_t i, j;
287     uint32_t X[16], *pB;
288
289     memcpy(X, B + (r * 2 - 1) * 16, sizeof(X));
290     pB = B;
291     for (i = 0; i < r * 2; i++) {
292         for (j = 0; j < 16; j++)
293             X[j] ^= *pB++;
294         salsa208_word_specification(X);
295         memcpy(B_ + (i / 2 + (i & 1) * r) * 16, X, sizeof(X));
296     }
297     OPENSSL_cleanse(X, sizeof(X));
298 }
299
300 static void scryptROMix(unsigned char *B, uint64_t r, uint64_t N,
301                         uint32_t *X, uint32_t *T, uint32_t *V)
302 {
303     unsigned char *pB;
304     uint32_t *pV;
305     uint64_t i, k;
306
307     /* Convert from little endian input */
308     for (pV = V, i = 0, pB = B; i < 32 * r; i++, pV++) {
309         *pV = *pB++;
310         *pV |= *pB++ << 8;
311         *pV |= *pB++ << 16;
312         *pV |= (uint32_t)*pB++ << 24;
313     }
314
315     for (i = 1; i < N; i++, pV += 32 * r)
316         scryptBlockMix(pV, pV - 32 * r, r);
317
318     scryptBlockMix(X, V + (N - 1) * 32 * r, r);
319
320     for (i = 0; i < N; i++) {
321         uint32_t j;
322         j = X[16 * (2 * r - 1)] % N;
323         pV = V + 32 * r * j;
324         for (k = 0; k < 32 * r; k++)
325             T[k] = X[k] ^ *pV++;
326         scryptBlockMix(X, T, r);
327     }
328     /* Convert output to little endian */
329     for (i = 0, pB = B; i < 32 * r; i++) {
330         uint32_t xtmp = X[i];
331         *pB++ = xtmp & 0xff;
332         *pB++ = (xtmp >> 8) & 0xff;
333         *pB++ = (xtmp >> 16) & 0xff;
334         *pB++ = (xtmp >> 24) & 0xff;
335     }
336 }
337
338 #ifndef SIZE_MAX
339 # define SIZE_MAX    ((size_t)-1)
340 #endif
341
342 /*
343  * Maximum power of two that will fit in uint64_t: this should work on
344  * most (all?) platforms.
345  */
346
347 #define LOG2_UINT64_MAX         (sizeof(uint64_t) * 8 - 1)
348
349 /*
350  * Maximum value of p * r:
351  * p <= ((2^32-1) * hLen) / MFLen =>
352  * p <= ((2^32-1) * 32) / (128 * r) =>
353  * p * r <= (2^30-1)
354  */
355
356 #define SCRYPT_PR_MAX   ((1 << 30) - 1)
357
358 static int scrypt_alg(const char *pass, size_t passlen,
359                       const unsigned char *salt, size_t saltlen,
360                       uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
361                       unsigned char *key, size_t keylen, EVP_MD *sha256)
362 {
363     int rv = 0;
364     unsigned char *B;
365     uint32_t *X, *V, *T;
366     uint64_t i, Blen, Vlen;
367
368     /* Sanity check parameters */
369     /* initial check, r,p must be non zero, N >= 2 and a power of 2 */
370     if (r == 0 || p == 0 || N < 2 || (N & (N - 1)))
371         return 0;
372     /* Check p * r < SCRYPT_PR_MAX avoiding overflow */
373     if (p > SCRYPT_PR_MAX / r) {
374         EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
375         return 0;
376     }
377
378     /*
379      * Need to check N: if 2^(128 * r / 8) overflows limit this is
380      * automatically satisfied since N <= UINT64_MAX.
381      */
382
383     if (16 * r <= LOG2_UINT64_MAX) {
384         if (N >= (((uint64_t)1) << (16 * r))) {
385             EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
386             return 0;
387         }
388     }
389
390     /* Memory checks: check total allocated buffer size fits in uint64_t */
391
392     /*
393      * B size in section 5 step 1.S
394      * Note: we know p * 128 * r < UINT64_MAX because we already checked
395      * p * r < SCRYPT_PR_MAX
396      */
397     Blen = p * 128 * r;
398     /*
399      * Yet we pass it as integer to PKCS5_PBKDF2_HMAC... [This would
400      * have to be revised when/if PKCS5_PBKDF2_HMAC accepts size_t.]
401      */
402     if (Blen > INT_MAX) {
403         EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
404         return 0;
405     }
406
407     /*
408      * Check 32 * r * (N + 2) * sizeof(uint32_t) fits in uint64_t
409      * This is combined size V, X and T (section 4)
410      */
411     i = UINT64_MAX / (32 * sizeof(uint32_t));
412     if (N + 2 > i / r) {
413         EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
414         return 0;
415     }
416     Vlen = 32 * r * (N + 2) * sizeof(uint32_t);
417
418     /* check total allocated size fits in uint64_t */
419     if (Blen > UINT64_MAX - Vlen) {
420         EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
421         return 0;
422     }
423
424     /* Check that the maximum memory doesn't exceed a size_t limits */
425     if (maxmem > SIZE_MAX)
426         maxmem = SIZE_MAX;
427
428     if (Blen + Vlen > maxmem) {
429         EVPerr(EVP_F_SCRYPT_ALG, EVP_R_MEMORY_LIMIT_EXCEEDED);
430         return 0;
431     }
432
433     /* If no key return to indicate parameters are OK */
434     if (key == NULL)
435         return 1;
436
437     B = OPENSSL_malloc((size_t)(Blen + Vlen));
438     if (B == NULL) {
439         EVPerr(EVP_F_SCRYPT_ALG, ERR_R_MALLOC_FAILURE);
440         return 0;
441     }
442     X = (uint32_t *)(B + Blen);
443     T = X + 32 * r;
444     V = T + 32 * r;
445     if (PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, 1, sha256,
446                           (int)Blen, B) == 0)
447         goto err;
448
449     for (i = 0; i < p; i++)
450         scryptROMix(B + 128 * r * i, r, N, X, T, V);
451
452     if (PKCS5_PBKDF2_HMAC(pass, passlen, B, (int)Blen, 1, sha256,
453                           keylen, key) == 0)
454         goto err;
455     rv = 1;
456  err:
457     if (rv == 0)
458         EVPerr(EVP_F_SCRYPT_ALG, EVP_R_PBKDF2_ERROR);
459
460     OPENSSL_clear_free(B, (size_t)(Blen + Vlen));
461     return rv;
462 }
463
464 #endif