crypto: drbg - panic on continuous self test error
[firefly-linux-kernel-4.4.55.git] / crypto / drbg.c
1 /*
2  * DRBG: Deterministic Random Bits Generator
3  *       Based on NIST Recommended DRBG from NIST SP800-90A with the following
4  *       properties:
5  *              * CTR DRBG with DF with AES-128, AES-192, AES-256 cores
6  *              * Hash DRBG with DF with SHA-1, SHA-256, SHA-384, SHA-512 cores
7  *              * HMAC DRBG with DF with SHA-1, SHA-256, SHA-384, SHA-512 cores
8  *              * with and without prediction resistance
9  *
10  * Copyright Stephan Mueller <smueller@chronox.de>, 2014
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, and the entire permission notice in its entirety,
17  *    including the disclaimer of warranties.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. The name of the author may not be used to endorse or promote
22  *    products derived from this software without specific prior
23  *    written permission.
24  *
25  * ALTERNATIVELY, this product may be distributed under the terms of
26  * the GNU General Public License, in which case the provisions of the GPL are
27  * required INSTEAD OF the above restrictions.  (This clause is
28  * necessary due to a potential bad interaction between the GPL and
29  * the restrictions contained in a BSD-style copyright.)
30  *
31  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
32  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
34  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
35  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
36  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
37  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
38  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
39  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
41  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
42  * DAMAGE.
43  *
44  * DRBG Usage
45  * ==========
46  * The SP 800-90A DRBG allows the user to specify a personalization string
47  * for initialization as well as an additional information string for each
48  * random number request. The following code fragments show how a caller
49  * uses the kernel crypto API to use the full functionality of the DRBG.
50  *
51  * Usage without any additional data
52  * ---------------------------------
53  * struct crypto_rng *drng;
54  * int err;
55  * char data[DATALEN];
56  *
57  * drng = crypto_alloc_rng(drng_name, 0, 0);
58  * err = crypto_rng_get_bytes(drng, &data, DATALEN);
59  * crypto_free_rng(drng);
60  *
61  *
62  * Usage with personalization string during initialization
63  * -------------------------------------------------------
64  * struct crypto_rng *drng;
65  * int err;
66  * char data[DATALEN];
67  * struct drbg_string pers;
68  * char personalization[11] = "some-string";
69  *
70  * drbg_string_fill(&pers, personalization, strlen(personalization));
71  * drng = crypto_alloc_rng(drng_name, 0, 0);
72  * // The reset completely re-initializes the DRBG with the provided
73  * // personalization string
74  * err = crypto_rng_reset(drng, &personalization, strlen(personalization));
75  * err = crypto_rng_get_bytes(drng, &data, DATALEN);
76  * crypto_free_rng(drng);
77  *
78  *
79  * Usage with additional information string during random number request
80  * ---------------------------------------------------------------------
81  * struct crypto_rng *drng;
82  * int err;
83  * char data[DATALEN];
84  * char addtl_string[11] = "some-string";
85  * string drbg_string addtl;
86  *
87  * drbg_string_fill(&addtl, addtl_string, strlen(addtl_string));
88  * drng = crypto_alloc_rng(drng_name, 0, 0);
89  * // The following call is a wrapper to crypto_rng_get_bytes() and returns
90  * // the same error codes.
91  * err = crypto_drbg_get_bytes_addtl(drng, &data, DATALEN, &addtl);
92  * crypto_free_rng(drng);
93  *
94  *
95  * Usage with personalization and additional information strings
96  * -------------------------------------------------------------
97  * Just mix both scenarios above.
98  */
99
100 #include <crypto/drbg.h>
101 #include <linux/string.h>
102
103 /***************************************************************
104  * Backend cipher definitions available to DRBG
105  ***************************************************************/
106
107 /*
108  * The order of the DRBG definitions here matter: every DRBG is registered
109  * as stdrng. Each DRBG receives an increasing cra_priority values the later
110  * they are defined in this array (see drbg_fill_array).
111  *
112  * HMAC DRBGs are favored over Hash DRBGs over CTR DRBGs, and
113  * the SHA256 / AES 256 over other ciphers. Thus, the favored
114  * DRBGs are the latest entries in this array.
115  */
116 static const struct drbg_core drbg_cores[] = {
117 #ifdef CONFIG_CRYPTO_DRBG_CTR
118         {
119                 .flags = DRBG_CTR | DRBG_STRENGTH128,
120                 .statelen = 32, /* 256 bits as defined in 10.2.1 */
121                 .blocklen_bytes = 16,
122                 .cra_name = "ctr_aes128",
123                 .backend_cra_name = "ecb(aes)",
124         }, {
125                 .flags = DRBG_CTR | DRBG_STRENGTH192,
126                 .statelen = 40, /* 320 bits as defined in 10.2.1 */
127                 .blocklen_bytes = 16,
128                 .cra_name = "ctr_aes192",
129                 .backend_cra_name = "ecb(aes)",
130         }, {
131                 .flags = DRBG_CTR | DRBG_STRENGTH256,
132                 .statelen = 48, /* 384 bits as defined in 10.2.1 */
133                 .blocklen_bytes = 16,
134                 .cra_name = "ctr_aes256",
135                 .backend_cra_name = "ecb(aes)",
136         },
137 #endif /* CONFIG_CRYPTO_DRBG_CTR */
138 #ifdef CONFIG_CRYPTO_DRBG_HASH
139         {
140                 .flags = DRBG_HASH | DRBG_STRENGTH128,
141                 .statelen = 55, /* 440 bits */
142                 .blocklen_bytes = 20,
143                 .cra_name = "sha1",
144                 .backend_cra_name = "sha1",
145         }, {
146                 .flags = DRBG_HASH | DRBG_STRENGTH256,
147                 .statelen = 111, /* 888 bits */
148                 .blocklen_bytes = 48,
149                 .cra_name = "sha384",
150                 .backend_cra_name = "sha384",
151         }, {
152                 .flags = DRBG_HASH | DRBG_STRENGTH256,
153                 .statelen = 111, /* 888 bits */
154                 .blocklen_bytes = 64,
155                 .cra_name = "sha512",
156                 .backend_cra_name = "sha512",
157         }, {
158                 .flags = DRBG_HASH | DRBG_STRENGTH256,
159                 .statelen = 55, /* 440 bits */
160                 .blocklen_bytes = 32,
161                 .cra_name = "sha256",
162                 .backend_cra_name = "sha256",
163         },
164 #endif /* CONFIG_CRYPTO_DRBG_HASH */
165 #ifdef CONFIG_CRYPTO_DRBG_HMAC
166         {
167                 .flags = DRBG_HMAC | DRBG_STRENGTH128,
168                 .statelen = 20, /* block length of cipher */
169                 .blocklen_bytes = 20,
170                 .cra_name = "hmac_sha1",
171                 .backend_cra_name = "hmac(sha1)",
172         }, {
173                 .flags = DRBG_HMAC | DRBG_STRENGTH256,
174                 .statelen = 48, /* block length of cipher */
175                 .blocklen_bytes = 48,
176                 .cra_name = "hmac_sha384",
177                 .backend_cra_name = "hmac(sha384)",
178         }, {
179                 .flags = DRBG_HMAC | DRBG_STRENGTH256,
180                 .statelen = 64, /* block length of cipher */
181                 .blocklen_bytes = 64,
182                 .cra_name = "hmac_sha512",
183                 .backend_cra_name = "hmac(sha512)",
184         }, {
185                 .flags = DRBG_HMAC | DRBG_STRENGTH256,
186                 .statelen = 32, /* block length of cipher */
187                 .blocklen_bytes = 32,
188                 .cra_name = "hmac_sha256",
189                 .backend_cra_name = "hmac(sha256)",
190         },
191 #endif /* CONFIG_CRYPTO_DRBG_HMAC */
192 };
193
194 /******************************************************************
195  * Generic helper functions
196  ******************************************************************/
197
198 /*
199  * Return strength of DRBG according to SP800-90A section 8.4
200  *
201  * @flags DRBG flags reference
202  *
203  * Return: normalized strength in *bytes* value or 32 as default
204  *         to counter programming errors
205  */
206 static inline unsigned short drbg_sec_strength(drbg_flag_t flags)
207 {
208         switch (flags & DRBG_STRENGTH_MASK) {
209         case DRBG_STRENGTH128:
210                 return 16;
211         case DRBG_STRENGTH192:
212                 return 24;
213         case DRBG_STRENGTH256:
214                 return 32;
215         default:
216                 return 32;
217         }
218 }
219
220 /*
221  * FIPS 140-2 continuous self test
222  * The test is performed on the result of one round of the output
223  * function. Thus, the function implicitly knows the size of the
224  * buffer.
225  *
226  * @drbg DRBG handle
227  * @buf output buffer of random data to be checked
228  *
229  * return:
230  *      true on success
231  *      false on error
232  */
233 static bool drbg_fips_continuous_test(struct drbg_state *drbg,
234                                       const unsigned char *buf)
235 {
236 #ifdef CONFIG_CRYPTO_FIPS
237         int ret = 0;
238         /* skip test if we test the overall system */
239         if (drbg->test_data)
240                 return true;
241         /* only perform test in FIPS mode */
242         if (0 == fips_enabled)
243                 return true;
244         if (!drbg->fips_primed) {
245                 /* Priming of FIPS test */
246                 memcpy(drbg->prev, buf, drbg_blocklen(drbg));
247                 drbg->fips_primed = true;
248                 /* return false due to priming, i.e. another round is needed */
249                 return false;
250         }
251         ret = memcmp(drbg->prev, buf, drbg_blocklen(drbg));
252         if (!ret)
253                 panic("DRBG continuous self test failed\n");
254         memcpy(drbg->prev, buf, drbg_blocklen(drbg));
255         /* the test shall pass when the two compared values are not equal */
256         return ret != 0;
257 #else
258         return true;
259 #endif /* CONFIG_CRYPTO_FIPS */
260 }
261
262 /*
263  * Convert an integer into a byte representation of this integer.
264  * The byte representation is big-endian
265  *
266  * @val value to be converted
267  * @buf buffer holding the converted integer -- caller must ensure that
268  *      buffer size is at least 32 bit
269  */
270 #if (defined(CONFIG_CRYPTO_DRBG_HASH) || defined(CONFIG_CRYPTO_DRBG_CTR))
271 static inline void drbg_cpu_to_be32(__u32 val, unsigned char *buf)
272 {
273         struct s {
274                 __be32 conv;
275         };
276         struct s *conversion = (struct s *) buf;
277
278         conversion->conv = cpu_to_be32(val);
279 }
280 #endif /* defined(CONFIG_CRYPTO_DRBG_HASH) || defined(CONFIG_CRYPTO_DRBG_CTR) */
281
282 /******************************************************************
283  * CTR DRBG callback functions
284  ******************************************************************/
285
286 #ifdef CONFIG_CRYPTO_DRBG_CTR
287 #define CRYPTO_DRBG_CTR_STRING "CTR "
288 MODULE_ALIAS_CRYPTO("drbg_pr_ctr_aes256");
289 MODULE_ALIAS_CRYPTO("drbg_nopr_ctr_aes256");
290 MODULE_ALIAS_CRYPTO("drbg_pr_ctr_aes192");
291 MODULE_ALIAS_CRYPTO("drbg_nopr_ctr_aes192");
292 MODULE_ALIAS_CRYPTO("drbg_pr_ctr_aes128");
293 MODULE_ALIAS_CRYPTO("drbg_nopr_ctr_aes128");
294
295 static int drbg_kcapi_sym(struct drbg_state *drbg, const unsigned char *key,
296                           unsigned char *outval, const struct drbg_string *in);
297 static int drbg_init_sym_kernel(struct drbg_state *drbg);
298 static int drbg_fini_sym_kernel(struct drbg_state *drbg);
299
300 /* BCC function for CTR DRBG as defined in 10.4.3 */
301 static int drbg_ctr_bcc(struct drbg_state *drbg,
302                         unsigned char *out, const unsigned char *key,
303                         struct list_head *in)
304 {
305         int ret = 0;
306         struct drbg_string *curr = NULL;
307         struct drbg_string data;
308         short cnt = 0;
309
310         drbg_string_fill(&data, out, drbg_blocklen(drbg));
311
312         /* 10.4.3 step 1 */
313         memset(out, 0, drbg_blocklen(drbg));
314
315         /* 10.4.3 step 2 / 4 */
316         list_for_each_entry(curr, in, list) {
317                 const unsigned char *pos = curr->buf;
318                 size_t len = curr->len;
319                 /* 10.4.3 step 4.1 */
320                 while (len) {
321                         /* 10.4.3 step 4.2 */
322                         if (drbg_blocklen(drbg) == cnt) {
323                                 cnt = 0;
324                                 ret = drbg_kcapi_sym(drbg, key, out, &data);
325                                 if (ret)
326                                         return ret;
327                         }
328                         out[cnt] ^= *pos;
329                         pos++;
330                         cnt++;
331                         len--;
332                 }
333         }
334         /* 10.4.3 step 4.2 for last block */
335         if (cnt)
336                 ret = drbg_kcapi_sym(drbg, key, out, &data);
337
338         return ret;
339 }
340
341 /*
342  * scratchpad usage: drbg_ctr_update is interlinked with drbg_ctr_df
343  * (and drbg_ctr_bcc, but this function does not need any temporary buffers),
344  * the scratchpad is used as follows:
345  * drbg_ctr_update:
346  *      temp
347  *              start: drbg->scratchpad
348  *              length: drbg_statelen(drbg) + drbg_blocklen(drbg)
349  *                      note: the cipher writing into this variable works
350  *                      blocklen-wise. Now, when the statelen is not a multiple
351  *                      of blocklen, the generateion loop below "spills over"
352  *                      by at most blocklen. Thus, we need to give sufficient
353  *                      memory.
354  *      df_data
355  *              start: drbg->scratchpad +
356  *                              drbg_statelen(drbg) + drbg_blocklen(drbg)
357  *              length: drbg_statelen(drbg)
358  *
359  * drbg_ctr_df:
360  *      pad
361  *              start: df_data + drbg_statelen(drbg)
362  *              length: drbg_blocklen(drbg)
363  *      iv
364  *              start: pad + drbg_blocklen(drbg)
365  *              length: drbg_blocklen(drbg)
366  *      temp
367  *              start: iv + drbg_blocklen(drbg)
368  *              length: drbg_satelen(drbg) + drbg_blocklen(drbg)
369  *                      note: temp is the buffer that the BCC function operates
370  *                      on. BCC operates blockwise. drbg_statelen(drbg)
371  *                      is sufficient when the DRBG state length is a multiple
372  *                      of the block size. For AES192 (and maybe other ciphers)
373  *                      this is not correct and the length for temp is
374  *                      insufficient (yes, that also means for such ciphers,
375  *                      the final output of all BCC rounds are truncated).
376  *                      Therefore, add drbg_blocklen(drbg) to cover all
377  *                      possibilities.
378  */
379
380 /* Derivation Function for CTR DRBG as defined in 10.4.2 */
381 static int drbg_ctr_df(struct drbg_state *drbg,
382                        unsigned char *df_data, size_t bytes_to_return,
383                        struct list_head *seedlist)
384 {
385         int ret = -EFAULT;
386         unsigned char L_N[8];
387         /* S3 is input */
388         struct drbg_string S1, S2, S4, cipherin;
389         LIST_HEAD(bcc_list);
390         unsigned char *pad = df_data + drbg_statelen(drbg);
391         unsigned char *iv = pad + drbg_blocklen(drbg);
392         unsigned char *temp = iv + drbg_blocklen(drbg);
393         size_t padlen = 0;
394         unsigned int templen = 0;
395         /* 10.4.2 step 7 */
396         unsigned int i = 0;
397         /* 10.4.2 step 8 */
398         const unsigned char *K = (unsigned char *)
399                            "\x00\x01\x02\x03\x04\x05\x06\x07"
400                            "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
401                            "\x10\x11\x12\x13\x14\x15\x16\x17"
402                            "\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f";
403         unsigned char *X;
404         size_t generated_len = 0;
405         size_t inputlen = 0;
406         struct drbg_string *seed = NULL;
407
408         memset(pad, 0, drbg_blocklen(drbg));
409         memset(iv, 0, drbg_blocklen(drbg));
410         memset(temp, 0, drbg_statelen(drbg));
411
412         /* 10.4.2 step 1 is implicit as we work byte-wise */
413
414         /* 10.4.2 step 2 */
415         if ((512/8) < bytes_to_return)
416                 return -EINVAL;
417
418         /* 10.4.2 step 2 -- calculate the entire length of all input data */
419         list_for_each_entry(seed, seedlist, list)
420                 inputlen += seed->len;
421         drbg_cpu_to_be32(inputlen, &L_N[0]);
422
423         /* 10.4.2 step 3 */
424         drbg_cpu_to_be32(bytes_to_return, &L_N[4]);
425
426         /* 10.4.2 step 5: length is L_N, input_string, one byte, padding */
427         padlen = (inputlen + sizeof(L_N) + 1) % (drbg_blocklen(drbg));
428         /* wrap the padlen appropriately */
429         if (padlen)
430                 padlen = drbg_blocklen(drbg) - padlen;
431         /*
432          * pad / padlen contains the 0x80 byte and the following zero bytes.
433          * As the calculated padlen value only covers the number of zero
434          * bytes, this value has to be incremented by one for the 0x80 byte.
435          */
436         padlen++;
437         pad[0] = 0x80;
438
439         /* 10.4.2 step 4 -- first fill the linked list and then order it */
440         drbg_string_fill(&S1, iv, drbg_blocklen(drbg));
441         list_add_tail(&S1.list, &bcc_list);
442         drbg_string_fill(&S2, L_N, sizeof(L_N));
443         list_add_tail(&S2.list, &bcc_list);
444         list_splice_tail(seedlist, &bcc_list);
445         drbg_string_fill(&S4, pad, padlen);
446         list_add_tail(&S4.list, &bcc_list);
447
448         /* 10.4.2 step 9 */
449         while (templen < (drbg_keylen(drbg) + (drbg_blocklen(drbg)))) {
450                 /*
451                  * 10.4.2 step 9.1 - the padding is implicit as the buffer
452                  * holds zeros after allocation -- even the increment of i
453                  * is irrelevant as the increment remains within length of i
454                  */
455                 drbg_cpu_to_be32(i, iv);
456                 /* 10.4.2 step 9.2 -- BCC and concatenation with temp */
457                 ret = drbg_ctr_bcc(drbg, temp + templen, K, &bcc_list);
458                 if (ret)
459                         goto out;
460                 /* 10.4.2 step 9.3 */
461                 i++;
462                 templen += drbg_blocklen(drbg);
463         }
464
465         /* 10.4.2 step 11 */
466         X = temp + (drbg_keylen(drbg));
467         drbg_string_fill(&cipherin, X, drbg_blocklen(drbg));
468
469         /* 10.4.2 step 12: overwriting of outval is implemented in next step */
470
471         /* 10.4.2 step 13 */
472         while (generated_len < bytes_to_return) {
473                 short blocklen = 0;
474                 /*
475                  * 10.4.2 step 13.1: the truncation of the key length is
476                  * implicit as the key is only drbg_blocklen in size based on
477                  * the implementation of the cipher function callback
478                  */
479                 ret = drbg_kcapi_sym(drbg, temp, X, &cipherin);
480                 if (ret)
481                         goto out;
482                 blocklen = (drbg_blocklen(drbg) <
483                                 (bytes_to_return - generated_len)) ?
484                             drbg_blocklen(drbg) :
485                                 (bytes_to_return - generated_len);
486                 /* 10.4.2 step 13.2 and 14 */
487                 memcpy(df_data + generated_len, X, blocklen);
488                 generated_len += blocklen;
489         }
490
491         ret = 0;
492
493 out:
494         memzero_explicit(iv, drbg_blocklen(drbg));
495         memzero_explicit(temp, drbg_statelen(drbg));
496         memzero_explicit(pad, drbg_blocklen(drbg));
497         return ret;
498 }
499
500 /*
501  * update function of CTR DRBG as defined in 10.2.1.2
502  *
503  * The reseed variable has an enhanced meaning compared to the update
504  * functions of the other DRBGs as follows:
505  * 0 => initial seed from initialization
506  * 1 => reseed via drbg_seed
507  * 2 => first invocation from drbg_ctr_update when addtl is present. In
508  *      this case, the df_data scratchpad is not deleted so that it is
509  *      available for another calls to prevent calling the DF function
510  *      again.
511  * 3 => second invocation from drbg_ctr_update. When the update function
512  *      was called with addtl, the df_data memory already contains the
513  *      DFed addtl information and we do not need to call DF again.
514  */
515 static int drbg_ctr_update(struct drbg_state *drbg, struct list_head *seed,
516                            int reseed)
517 {
518         int ret = -EFAULT;
519         /* 10.2.1.2 step 1 */
520         unsigned char *temp = drbg->scratchpad;
521         unsigned char *df_data = drbg->scratchpad + drbg_statelen(drbg) +
522                                  drbg_blocklen(drbg);
523         unsigned char *temp_p, *df_data_p; /* pointer to iterate over buffers */
524         unsigned int len = 0;
525         struct drbg_string cipherin;
526
527         memset(temp, 0, drbg_statelen(drbg) + drbg_blocklen(drbg));
528         if (3 > reseed)
529                 memset(df_data, 0, drbg_statelen(drbg));
530
531         /* 10.2.1.3.2 step 2 and 10.2.1.4.2 step 2 */
532         if (seed) {
533                 ret = drbg_ctr_df(drbg, df_data, drbg_statelen(drbg), seed);
534                 if (ret)
535                         goto out;
536         }
537
538         drbg_string_fill(&cipherin, drbg->V, drbg_blocklen(drbg));
539         /*
540          * 10.2.1.3.2 steps 2 and 3 are already covered as the allocation
541          * zeroizes all memory during initialization
542          */
543         while (len < (drbg_statelen(drbg))) {
544                 /* 10.2.1.2 step 2.1 */
545                 crypto_inc(drbg->V, drbg_blocklen(drbg));
546                 /*
547                  * 10.2.1.2 step 2.2 */
548                 ret = drbg_kcapi_sym(drbg, drbg->C, temp + len, &cipherin);
549                 if (ret)
550                         goto out;
551                 /* 10.2.1.2 step 2.3 and 3 */
552                 len += drbg_blocklen(drbg);
553         }
554
555         /* 10.2.1.2 step 4 */
556         temp_p = temp;
557         df_data_p = df_data;
558         for (len = 0; len < drbg_statelen(drbg); len++) {
559                 *temp_p ^= *df_data_p;
560                 df_data_p++; temp_p++;
561         }
562
563         /* 10.2.1.2 step 5 */
564         memcpy(drbg->C, temp, drbg_keylen(drbg));
565         /* 10.2.1.2 step 6 */
566         memcpy(drbg->V, temp + drbg_keylen(drbg), drbg_blocklen(drbg));
567         ret = 0;
568
569 out:
570         memzero_explicit(temp, drbg_statelen(drbg) + drbg_blocklen(drbg));
571         if (2 != reseed)
572                 memzero_explicit(df_data, drbg_statelen(drbg));
573         return ret;
574 }
575
576 /*
577  * scratchpad use: drbg_ctr_update is called independently from
578  * drbg_ctr_extract_bytes. Therefore, the scratchpad is reused
579  */
580 /* Generate function of CTR DRBG as defined in 10.2.1.5.2 */
581 static int drbg_ctr_generate(struct drbg_state *drbg,
582                              unsigned char *buf, unsigned int buflen,
583                              struct list_head *addtl)
584 {
585         int len = 0;
586         int ret = 0;
587         struct drbg_string data;
588
589         memset(drbg->scratchpad, 0, drbg_blocklen(drbg));
590
591         /* 10.2.1.5.2 step 2 */
592         if (addtl && !list_empty(addtl)) {
593                 ret = drbg_ctr_update(drbg, addtl, 2);
594                 if (ret)
595                         return 0;
596         }
597
598         /* 10.2.1.5.2 step 4.1 */
599         crypto_inc(drbg->V, drbg_blocklen(drbg));
600         drbg_string_fill(&data, drbg->V, drbg_blocklen(drbg));
601         while (len < buflen) {
602                 int outlen = 0;
603                 /* 10.2.1.5.2 step 4.2 */
604                 ret = drbg_kcapi_sym(drbg, drbg->C, drbg->scratchpad, &data);
605                 if (ret) {
606                         len = ret;
607                         goto out;
608                 }
609                 outlen = (drbg_blocklen(drbg) < (buflen - len)) ?
610                           drbg_blocklen(drbg) : (buflen - len);
611                 if (!drbg_fips_continuous_test(drbg, drbg->scratchpad)) {
612                         /* 10.2.1.5.2 step 6 */
613                         crypto_inc(drbg->V, drbg_blocklen(drbg));
614                         continue;
615                 }
616                 /* 10.2.1.5.2 step 4.3 */
617                 memcpy(buf + len, drbg->scratchpad, outlen);
618                 len += outlen;
619                 /* 10.2.1.5.2 step 6 */
620                 if (len < buflen)
621                         crypto_inc(drbg->V, drbg_blocklen(drbg));
622         }
623
624         /* 10.2.1.5.2 step 6 */
625         ret = drbg_ctr_update(drbg, NULL, 3);
626         if (ret)
627                 len = ret;
628
629 out:
630         memzero_explicit(drbg->scratchpad, drbg_blocklen(drbg));
631         return len;
632 }
633
634 static struct drbg_state_ops drbg_ctr_ops = {
635         .update         = drbg_ctr_update,
636         .generate       = drbg_ctr_generate,
637         .crypto_init    = drbg_init_sym_kernel,
638         .crypto_fini    = drbg_fini_sym_kernel,
639 };
640 #endif /* CONFIG_CRYPTO_DRBG_CTR */
641
642 /******************************************************************
643  * HMAC DRBG callback functions
644  ******************************************************************/
645
646 #if defined(CONFIG_CRYPTO_DRBG_HASH) || defined(CONFIG_CRYPTO_DRBG_HMAC)
647 static int drbg_kcapi_hash(struct drbg_state *drbg, const unsigned char *key,
648                            unsigned char *outval, const struct list_head *in);
649 static int drbg_init_hash_kernel(struct drbg_state *drbg);
650 static int drbg_fini_hash_kernel(struct drbg_state *drbg);
651 #endif /* (CONFIG_CRYPTO_DRBG_HASH || CONFIG_CRYPTO_DRBG_HMAC) */
652
653 #ifdef CONFIG_CRYPTO_DRBG_HMAC
654 #define CRYPTO_DRBG_HMAC_STRING "HMAC "
655 MODULE_ALIAS_CRYPTO("drbg_pr_hmac_sha512");
656 MODULE_ALIAS_CRYPTO("drbg_nopr_hmac_sha512");
657 MODULE_ALIAS_CRYPTO("drbg_pr_hmac_sha384");
658 MODULE_ALIAS_CRYPTO("drbg_nopr_hmac_sha384");
659 MODULE_ALIAS_CRYPTO("drbg_pr_hmac_sha256");
660 MODULE_ALIAS_CRYPTO("drbg_nopr_hmac_sha256");
661 MODULE_ALIAS_CRYPTO("drbg_pr_hmac_sha1");
662 MODULE_ALIAS_CRYPTO("drbg_nopr_hmac_sha1");
663
664 /* update function of HMAC DRBG as defined in 10.1.2.2 */
665 static int drbg_hmac_update(struct drbg_state *drbg, struct list_head *seed,
666                             int reseed)
667 {
668         int ret = -EFAULT;
669         int i = 0;
670         struct drbg_string seed1, seed2, vdata;
671         LIST_HEAD(seedlist);
672         LIST_HEAD(vdatalist);
673
674         if (!reseed)
675                 /* 10.1.2.3 step 2 -- memset(0) of C is implicit with kzalloc */
676                 memset(drbg->V, 1, drbg_statelen(drbg));
677
678         drbg_string_fill(&seed1, drbg->V, drbg_statelen(drbg));
679         list_add_tail(&seed1.list, &seedlist);
680         /* buffer of seed2 will be filled in for loop below with one byte */
681         drbg_string_fill(&seed2, NULL, 1);
682         list_add_tail(&seed2.list, &seedlist);
683         /* input data of seed is allowed to be NULL at this point */
684         if (seed)
685                 list_splice_tail(seed, &seedlist);
686
687         drbg_string_fill(&vdata, drbg->V, drbg_statelen(drbg));
688         list_add_tail(&vdata.list, &vdatalist);
689         for (i = 2; 0 < i; i--) {
690                 /* first round uses 0x0, second 0x1 */
691                 unsigned char prefix = DRBG_PREFIX0;
692                 if (1 == i)
693                         prefix = DRBG_PREFIX1;
694                 /* 10.1.2.2 step 1 and 4 -- concatenation and HMAC for key */
695                 seed2.buf = &prefix;
696                 ret = drbg_kcapi_hash(drbg, drbg->C, drbg->C, &seedlist);
697                 if (ret)
698                         return ret;
699
700                 /* 10.1.2.2 step 2 and 5 -- HMAC for V */
701                 ret = drbg_kcapi_hash(drbg, drbg->C, drbg->V, &vdatalist);
702                 if (ret)
703                         return ret;
704
705                 /* 10.1.2.2 step 3 */
706                 if (!seed)
707                         return ret;
708         }
709
710         return 0;
711 }
712
713 /* generate function of HMAC DRBG as defined in 10.1.2.5 */
714 static int drbg_hmac_generate(struct drbg_state *drbg,
715                               unsigned char *buf,
716                               unsigned int buflen,
717                               struct list_head *addtl)
718 {
719         int len = 0;
720         int ret = 0;
721         struct drbg_string data;
722         LIST_HEAD(datalist);
723
724         /* 10.1.2.5 step 2 */
725         if (addtl && !list_empty(addtl)) {
726                 ret = drbg_hmac_update(drbg, addtl, 1);
727                 if (ret)
728                         return ret;
729         }
730
731         drbg_string_fill(&data, drbg->V, drbg_statelen(drbg));
732         list_add_tail(&data.list, &datalist);
733         while (len < buflen) {
734                 unsigned int outlen = 0;
735                 /* 10.1.2.5 step 4.1 */
736                 ret = drbg_kcapi_hash(drbg, drbg->C, drbg->V, &datalist);
737                 if (ret)
738                         return ret;
739                 outlen = (drbg_blocklen(drbg) < (buflen - len)) ?
740                           drbg_blocklen(drbg) : (buflen - len);
741                 if (!drbg_fips_continuous_test(drbg, drbg->V))
742                         continue;
743
744                 /* 10.1.2.5 step 4.2 */
745                 memcpy(buf + len, drbg->V, outlen);
746                 len += outlen;
747         }
748
749         /* 10.1.2.5 step 6 */
750         if (addtl && !list_empty(addtl))
751                 ret = drbg_hmac_update(drbg, addtl, 1);
752         else
753                 ret = drbg_hmac_update(drbg, NULL, 1);
754         if (ret)
755                 return ret;
756
757         return len;
758 }
759
760 static struct drbg_state_ops drbg_hmac_ops = {
761         .update         = drbg_hmac_update,
762         .generate       = drbg_hmac_generate,
763         .crypto_init    = drbg_init_hash_kernel,
764         .crypto_fini    = drbg_fini_hash_kernel,
765
766 };
767 #endif /* CONFIG_CRYPTO_DRBG_HMAC */
768
769 /******************************************************************
770  * Hash DRBG callback functions
771  ******************************************************************/
772
773 #ifdef CONFIG_CRYPTO_DRBG_HASH
774 #define CRYPTO_DRBG_HASH_STRING "HASH "
775 MODULE_ALIAS_CRYPTO("drbg_pr_sha512");
776 MODULE_ALIAS_CRYPTO("drbg_nopr_sha512");
777 MODULE_ALIAS_CRYPTO("drbg_pr_sha384");
778 MODULE_ALIAS_CRYPTO("drbg_nopr_sha384");
779 MODULE_ALIAS_CRYPTO("drbg_pr_sha256");
780 MODULE_ALIAS_CRYPTO("drbg_nopr_sha256");
781 MODULE_ALIAS_CRYPTO("drbg_pr_sha1");
782 MODULE_ALIAS_CRYPTO("drbg_nopr_sha1");
783
784 /*
785  * Increment buffer
786  *
787  * @dst buffer to increment
788  * @add value to add
789  */
790 static inline void drbg_add_buf(unsigned char *dst, size_t dstlen,
791                                 const unsigned char *add, size_t addlen)
792 {
793         /* implied: dstlen > addlen */
794         unsigned char *dstptr;
795         const unsigned char *addptr;
796         unsigned int remainder = 0;
797         size_t len = addlen;
798
799         dstptr = dst + (dstlen-1);
800         addptr = add + (addlen-1);
801         while (len) {
802                 remainder += *dstptr + *addptr;
803                 *dstptr = remainder & 0xff;
804                 remainder >>= 8;
805                 len--; dstptr--; addptr--;
806         }
807         len = dstlen - addlen;
808         while (len && remainder > 0) {
809                 remainder = *dstptr + 1;
810                 *dstptr = remainder & 0xff;
811                 remainder >>= 8;
812                 len--; dstptr--;
813         }
814 }
815
816 /*
817  * scratchpad usage: as drbg_hash_update and drbg_hash_df are used
818  * interlinked, the scratchpad is used as follows:
819  * drbg_hash_update
820  *      start: drbg->scratchpad
821  *      length: drbg_statelen(drbg)
822  * drbg_hash_df:
823  *      start: drbg->scratchpad + drbg_statelen(drbg)
824  *      length: drbg_blocklen(drbg)
825  *
826  * drbg_hash_process_addtl uses the scratchpad, but fully completes
827  * before either of the functions mentioned before are invoked. Therefore,
828  * drbg_hash_process_addtl does not need to be specifically considered.
829  */
830
831 /* Derivation Function for Hash DRBG as defined in 10.4.1 */
832 static int drbg_hash_df(struct drbg_state *drbg,
833                         unsigned char *outval, size_t outlen,
834                         struct list_head *entropylist)
835 {
836         int ret = 0;
837         size_t len = 0;
838         unsigned char input[5];
839         unsigned char *tmp = drbg->scratchpad + drbg_statelen(drbg);
840         struct drbg_string data;
841
842         memset(tmp, 0, drbg_blocklen(drbg));
843
844         /* 10.4.1 step 3 */
845         input[0] = 1;
846         drbg_cpu_to_be32((outlen * 8), &input[1]);
847
848         /* 10.4.1 step 4.1 -- concatenation of data for input into hash */
849         drbg_string_fill(&data, input, 5);
850         list_add(&data.list, entropylist);
851
852         /* 10.4.1 step 4 */
853         while (len < outlen) {
854                 short blocklen = 0;
855                 /* 10.4.1 step 4.1 */
856                 ret = drbg_kcapi_hash(drbg, NULL, tmp, entropylist);
857                 if (ret)
858                         goto out;
859                 /* 10.4.1 step 4.2 */
860                 input[0]++;
861                 blocklen = (drbg_blocklen(drbg) < (outlen - len)) ?
862                             drbg_blocklen(drbg) : (outlen - len);
863                 memcpy(outval + len, tmp, blocklen);
864                 len += blocklen;
865         }
866
867 out:
868         memzero_explicit(tmp, drbg_blocklen(drbg));
869         return ret;
870 }
871
872 /* update function for Hash DRBG as defined in 10.1.1.2 / 10.1.1.3 */
873 static int drbg_hash_update(struct drbg_state *drbg, struct list_head *seed,
874                             int reseed)
875 {
876         int ret = 0;
877         struct drbg_string data1, data2;
878         LIST_HEAD(datalist);
879         LIST_HEAD(datalist2);
880         unsigned char *V = drbg->scratchpad;
881         unsigned char prefix = DRBG_PREFIX1;
882
883         memset(drbg->scratchpad, 0, drbg_statelen(drbg));
884         if (!seed)
885                 return -EINVAL;
886
887         if (reseed) {
888                 /* 10.1.1.3 step 1 */
889                 memcpy(V, drbg->V, drbg_statelen(drbg));
890                 drbg_string_fill(&data1, &prefix, 1);
891                 list_add_tail(&data1.list, &datalist);
892                 drbg_string_fill(&data2, V, drbg_statelen(drbg));
893                 list_add_tail(&data2.list, &datalist);
894         }
895         list_splice_tail(seed, &datalist);
896
897         /* 10.1.1.2 / 10.1.1.3 step 2 and 3 */
898         ret = drbg_hash_df(drbg, drbg->V, drbg_statelen(drbg), &datalist);
899         if (ret)
900                 goto out;
901
902         /* 10.1.1.2 / 10.1.1.3 step 4  */
903         prefix = DRBG_PREFIX0;
904         drbg_string_fill(&data1, &prefix, 1);
905         list_add_tail(&data1.list, &datalist2);
906         drbg_string_fill(&data2, drbg->V, drbg_statelen(drbg));
907         list_add_tail(&data2.list, &datalist2);
908         /* 10.1.1.2 / 10.1.1.3 step 4 */
909         ret = drbg_hash_df(drbg, drbg->C, drbg_statelen(drbg), &datalist2);
910
911 out:
912         memzero_explicit(drbg->scratchpad, drbg_statelen(drbg));
913         return ret;
914 }
915
916 /* processing of additional information string for Hash DRBG */
917 static int drbg_hash_process_addtl(struct drbg_state *drbg,
918                                    struct list_head *addtl)
919 {
920         int ret = 0;
921         struct drbg_string data1, data2;
922         LIST_HEAD(datalist);
923         unsigned char prefix = DRBG_PREFIX2;
924
925         /* this is value w as per documentation */
926         memset(drbg->scratchpad, 0, drbg_blocklen(drbg));
927
928         /* 10.1.1.4 step 2 */
929         if (!addtl || list_empty(addtl))
930                 return 0;
931
932         /* 10.1.1.4 step 2a */
933         drbg_string_fill(&data1, &prefix, 1);
934         drbg_string_fill(&data2, drbg->V, drbg_statelen(drbg));
935         list_add_tail(&data1.list, &datalist);
936         list_add_tail(&data2.list, &datalist);
937         list_splice_tail(addtl, &datalist);
938         ret = drbg_kcapi_hash(drbg, NULL, drbg->scratchpad, &datalist);
939         if (ret)
940                 goto out;
941
942         /* 10.1.1.4 step 2b */
943         drbg_add_buf(drbg->V, drbg_statelen(drbg),
944                      drbg->scratchpad, drbg_blocklen(drbg));
945
946 out:
947         memzero_explicit(drbg->scratchpad, drbg_blocklen(drbg));
948         return ret;
949 }
950
951 /* Hashgen defined in 10.1.1.4 */
952 static int drbg_hash_hashgen(struct drbg_state *drbg,
953                              unsigned char *buf,
954                              unsigned int buflen)
955 {
956         int len = 0;
957         int ret = 0;
958         unsigned char *src = drbg->scratchpad;
959         unsigned char *dst = drbg->scratchpad + drbg_statelen(drbg);
960         struct drbg_string data;
961         LIST_HEAD(datalist);
962
963         memset(src, 0, drbg_statelen(drbg));
964         memset(dst, 0, drbg_blocklen(drbg));
965
966         /* 10.1.1.4 step hashgen 2 */
967         memcpy(src, drbg->V, drbg_statelen(drbg));
968
969         drbg_string_fill(&data, src, drbg_statelen(drbg));
970         list_add_tail(&data.list, &datalist);
971         while (len < buflen) {
972                 unsigned int outlen = 0;
973                 /* 10.1.1.4 step hashgen 4.1 */
974                 ret = drbg_kcapi_hash(drbg, NULL, dst, &datalist);
975                 if (ret) {
976                         len = ret;
977                         goto out;
978                 }
979                 outlen = (drbg_blocklen(drbg) < (buflen - len)) ?
980                           drbg_blocklen(drbg) : (buflen - len);
981                 if (!drbg_fips_continuous_test(drbg, dst)) {
982                         crypto_inc(src, drbg_statelen(drbg));
983                         continue;
984                 }
985                 /* 10.1.1.4 step hashgen 4.2 */
986                 memcpy(buf + len, dst, outlen);
987                 len += outlen;
988                 /* 10.1.1.4 hashgen step 4.3 */
989                 if (len < buflen)
990                         crypto_inc(src, drbg_statelen(drbg));
991         }
992
993 out:
994         memzero_explicit(drbg->scratchpad,
995                (drbg_statelen(drbg) + drbg_blocklen(drbg)));
996         return len;
997 }
998
999 /* generate function for Hash DRBG as defined in  10.1.1.4 */
1000 static int drbg_hash_generate(struct drbg_state *drbg,
1001                               unsigned char *buf, unsigned int buflen,
1002                               struct list_head *addtl)
1003 {
1004         int len = 0;
1005         int ret = 0;
1006         union {
1007                 unsigned char req[8];
1008                 __be64 req_int;
1009         } u;
1010         unsigned char prefix = DRBG_PREFIX3;
1011         struct drbg_string data1, data2;
1012         LIST_HEAD(datalist);
1013
1014         /* 10.1.1.4 step 2 */
1015         ret = drbg_hash_process_addtl(drbg, addtl);
1016         if (ret)
1017                 return ret;
1018         /* 10.1.1.4 step 3 */
1019         len = drbg_hash_hashgen(drbg, buf, buflen);
1020
1021         /* this is the value H as documented in 10.1.1.4 */
1022         memset(drbg->scratchpad, 0, drbg_blocklen(drbg));
1023         /* 10.1.1.4 step 4 */
1024         drbg_string_fill(&data1, &prefix, 1);
1025         list_add_tail(&data1.list, &datalist);
1026         drbg_string_fill(&data2, drbg->V, drbg_statelen(drbg));
1027         list_add_tail(&data2.list, &datalist);
1028         ret = drbg_kcapi_hash(drbg, NULL, drbg->scratchpad, &datalist);
1029         if (ret) {
1030                 len = ret;
1031                 goto out;
1032         }
1033
1034         /* 10.1.1.4 step 5 */
1035         drbg_add_buf(drbg->V, drbg_statelen(drbg),
1036                      drbg->scratchpad, drbg_blocklen(drbg));
1037         drbg_add_buf(drbg->V, drbg_statelen(drbg),
1038                      drbg->C, drbg_statelen(drbg));
1039         u.req_int = cpu_to_be64(drbg->reseed_ctr);
1040         drbg_add_buf(drbg->V, drbg_statelen(drbg), u.req, 8);
1041
1042 out:
1043         memzero_explicit(drbg->scratchpad, drbg_blocklen(drbg));
1044         return len;
1045 }
1046
1047 /*
1048  * scratchpad usage: as update and generate are used isolated, both
1049  * can use the scratchpad
1050  */
1051 static struct drbg_state_ops drbg_hash_ops = {
1052         .update         = drbg_hash_update,
1053         .generate       = drbg_hash_generate,
1054         .crypto_init    = drbg_init_hash_kernel,
1055         .crypto_fini    = drbg_fini_hash_kernel,
1056 };
1057 #endif /* CONFIG_CRYPTO_DRBG_HASH */
1058
1059 /******************************************************************
1060  * Functions common for DRBG implementations
1061  ******************************************************************/
1062
1063 /*
1064  * Seeding or reseeding of the DRBG
1065  *
1066  * @drbg: DRBG state struct
1067  * @pers: personalization / additional information buffer
1068  * @reseed: 0 for initial seed process, 1 for reseeding
1069  *
1070  * return:
1071  *      0 on success
1072  *      error value otherwise
1073  */
1074 static int drbg_seed(struct drbg_state *drbg, struct drbg_string *pers,
1075                      bool reseed)
1076 {
1077         int ret = 0;
1078         unsigned char *entropy = NULL;
1079         size_t entropylen = 0;
1080         struct drbg_string data1;
1081         LIST_HEAD(seedlist);
1082
1083         /* 9.1 / 9.2 / 9.3.1 step 3 */
1084         if (pers && pers->len > (drbg_max_addtl(drbg))) {
1085                 pr_devel("DRBG: personalization string too long %zu\n",
1086                          pers->len);
1087                 return -EINVAL;
1088         }
1089
1090         if (drbg->test_data && drbg->test_data->testentropy) {
1091                 drbg_string_fill(&data1, drbg->test_data->testentropy->buf,
1092                                  drbg->test_data->testentropy->len);
1093                 pr_devel("DRBG: using test entropy\n");
1094         } else {
1095                 /*
1096                  * Gather entropy equal to the security strength of the DRBG.
1097                  * With a derivation function, a nonce is required in addition
1098                  * to the entropy. A nonce must be at least 1/2 of the security
1099                  * strength of the DRBG in size. Thus, entropy * nonce is 3/2
1100                  * of the strength. The consideration of a nonce is only
1101                  * applicable during initial seeding.
1102                  */
1103                 entropylen = drbg_sec_strength(drbg->core->flags);
1104                 if (!entropylen)
1105                         return -EFAULT;
1106                 if (!reseed)
1107                         entropylen = ((entropylen + 1) / 2) * 3;
1108                 pr_devel("DRBG: (re)seeding with %zu bytes of entropy\n",
1109                          entropylen);
1110                 entropy = kzalloc(entropylen, GFP_KERNEL);
1111                 if (!entropy)
1112                         return -ENOMEM;
1113                 get_random_bytes(entropy, entropylen);
1114                 drbg_string_fill(&data1, entropy, entropylen);
1115         }
1116         list_add_tail(&data1.list, &seedlist);
1117
1118         /*
1119          * concatenation of entropy with personalization str / addtl input)
1120          * the variable pers is directly handed in by the caller, so check its
1121          * contents whether it is appropriate
1122          */
1123         if (pers && pers->buf && 0 < pers->len) {
1124                 list_add_tail(&pers->list, &seedlist);
1125                 pr_devel("DRBG: using personalization string\n");
1126         }
1127
1128         if (!reseed) {
1129                 memset(drbg->V, 0, drbg_statelen(drbg));
1130                 memset(drbg->C, 0, drbg_statelen(drbg));
1131         }
1132
1133         ret = drbg->d_ops->update(drbg, &seedlist, reseed);
1134         if (ret)
1135                 goto out;
1136
1137         drbg->seeded = true;
1138         /* 10.1.1.2 / 10.1.1.3 step 5 */
1139         drbg->reseed_ctr = 1;
1140
1141 out:
1142         kzfree(entropy);
1143         return ret;
1144 }
1145
1146 /* Free all substructures in a DRBG state without the DRBG state structure */
1147 static inline void drbg_dealloc_state(struct drbg_state *drbg)
1148 {
1149         if (!drbg)
1150                 return;
1151         kzfree(drbg->V);
1152         drbg->V = NULL;
1153         kzfree(drbg->C);
1154         drbg->C = NULL;
1155         kzfree(drbg->scratchpad);
1156         drbg->scratchpad = NULL;
1157         drbg->reseed_ctr = 0;
1158 #ifdef CONFIG_CRYPTO_FIPS
1159         kzfree(drbg->prev);
1160         drbg->prev = NULL;
1161         drbg->fips_primed = false;
1162 #endif
1163 }
1164
1165 /*
1166  * Allocate all sub-structures for a DRBG state.
1167  * The DRBG state structure must already be allocated.
1168  */
1169 static inline int drbg_alloc_state(struct drbg_state *drbg)
1170 {
1171         int ret = -ENOMEM;
1172         unsigned int sb_size = 0;
1173
1174         drbg->V = kmalloc(drbg_statelen(drbg), GFP_KERNEL);
1175         if (!drbg->V)
1176                 goto err;
1177         drbg->C = kmalloc(drbg_statelen(drbg), GFP_KERNEL);
1178         if (!drbg->C)
1179                 goto err;
1180 #ifdef CONFIG_CRYPTO_FIPS
1181         drbg->prev = kmalloc(drbg_blocklen(drbg), GFP_KERNEL);
1182         if (!drbg->prev)
1183                 goto err;
1184         drbg->fips_primed = false;
1185 #endif
1186         /* scratchpad is only generated for CTR and Hash */
1187         if (drbg->core->flags & DRBG_HMAC)
1188                 sb_size = 0;
1189         else if (drbg->core->flags & DRBG_CTR)
1190                 sb_size = drbg_statelen(drbg) + drbg_blocklen(drbg) + /* temp */
1191                           drbg_statelen(drbg) + /* df_data */
1192                           drbg_blocklen(drbg) + /* pad */
1193                           drbg_blocklen(drbg) + /* iv */
1194                           drbg_statelen(drbg) + drbg_blocklen(drbg); /* temp */
1195         else
1196                 sb_size = drbg_statelen(drbg) + drbg_blocklen(drbg);
1197
1198         if (0 < sb_size) {
1199                 drbg->scratchpad = kzalloc(sb_size, GFP_KERNEL);
1200                 if (!drbg->scratchpad)
1201                         goto err;
1202         }
1203         spin_lock_init(&drbg->drbg_lock);
1204         return 0;
1205
1206 err:
1207         drbg_dealloc_state(drbg);
1208         return ret;
1209 }
1210
1211 /*
1212  * Strategy to avoid holding long term locks: generate a shadow copy of DRBG
1213  * and perform all operations on this shadow copy. After finishing, restore
1214  * the updated state of the shadow copy into original drbg state. This way,
1215  * only the read and write operations of the original drbg state must be
1216  * locked
1217  */
1218 static inline void drbg_copy_drbg(struct drbg_state *src,
1219                                   struct drbg_state *dst)
1220 {
1221         if (!src || !dst)
1222                 return;
1223         memcpy(dst->V, src->V, drbg_statelen(src));
1224         memcpy(dst->C, src->C, drbg_statelen(src));
1225         dst->reseed_ctr = src->reseed_ctr;
1226         dst->seeded = src->seeded;
1227         dst->pr = src->pr;
1228 #ifdef CONFIG_CRYPTO_FIPS
1229         dst->fips_primed = src->fips_primed;
1230         memcpy(dst->prev, src->prev, drbg_blocklen(src));
1231 #endif
1232         /*
1233          * Not copied:
1234          * scratchpad is initialized drbg_alloc_state;
1235          * priv_data is initialized with call to crypto_init;
1236          * d_ops and core are set outside, as these parameters are const;
1237          * test_data is set outside to prevent it being copied back.
1238          */
1239 }
1240
1241 static int drbg_make_shadow(struct drbg_state *drbg, struct drbg_state **shadow)
1242 {
1243         int ret = -ENOMEM;
1244         struct drbg_state *tmp = NULL;
1245
1246         tmp = kzalloc(sizeof(struct drbg_state), GFP_KERNEL);
1247         if (!tmp)
1248                 return -ENOMEM;
1249
1250         /* read-only data as they are defined as const, no lock needed */
1251         tmp->core = drbg->core;
1252         tmp->d_ops = drbg->d_ops;
1253
1254         ret = drbg_alloc_state(tmp);
1255         if (ret)
1256                 goto err;
1257
1258         spin_lock_bh(&drbg->drbg_lock);
1259         drbg_copy_drbg(drbg, tmp);
1260         /* only make a link to the test buffer, as we only read that data */
1261         tmp->test_data = drbg->test_data;
1262         spin_unlock_bh(&drbg->drbg_lock);
1263         *shadow = tmp;
1264         return 0;
1265
1266 err:
1267         kzfree(tmp);
1268         return ret;
1269 }
1270
1271 static void drbg_restore_shadow(struct drbg_state *drbg,
1272                                 struct drbg_state **shadow)
1273 {
1274         struct drbg_state *tmp = *shadow;
1275
1276         spin_lock_bh(&drbg->drbg_lock);
1277         drbg_copy_drbg(tmp, drbg);
1278         spin_unlock_bh(&drbg->drbg_lock);
1279         drbg_dealloc_state(tmp);
1280         kzfree(tmp);
1281         *shadow = NULL;
1282 }
1283
1284 /*************************************************************************
1285  * DRBG interface functions
1286  *************************************************************************/
1287
1288 /*
1289  * DRBG generate function as required by SP800-90A - this function
1290  * generates random numbers
1291  *
1292  * @drbg DRBG state handle
1293  * @buf Buffer where to store the random numbers -- the buffer must already
1294  *      be pre-allocated by caller
1295  * @buflen Length of output buffer - this value defines the number of random
1296  *         bytes pulled from DRBG
1297  * @addtl Additional input that is mixed into state, may be NULL -- note
1298  *        the entropy is pulled by the DRBG internally unconditionally
1299  *        as defined in SP800-90A. The additional input is mixed into
1300  *        the state in addition to the pulled entropy.
1301  *
1302  * return: generated number of bytes
1303  */
1304 static int drbg_generate(struct drbg_state *drbg,
1305                          unsigned char *buf, unsigned int buflen,
1306                          struct drbg_string *addtl)
1307 {
1308         int len = 0;
1309         struct drbg_state *shadow = NULL;
1310         LIST_HEAD(addtllist);
1311         struct drbg_string timestamp;
1312         union {
1313                 cycles_t cycles;
1314                 unsigned char char_cycles[sizeof(cycles_t)];
1315         } now;
1316
1317         if (0 == buflen || !buf) {
1318                 pr_devel("DRBG: no output buffer provided\n");
1319                 return -EINVAL;
1320         }
1321         if (addtl && NULL == addtl->buf && 0 < addtl->len) {
1322                 pr_devel("DRBG: wrong format of additional information\n");
1323                 return -EINVAL;
1324         }
1325
1326         len = drbg_make_shadow(drbg, &shadow);
1327         if (len) {
1328                 pr_devel("DRBG: shadow copy cannot be generated\n");
1329                 return len;
1330         }
1331
1332         /* 9.3.1 step 2 */
1333         len = -EINVAL;
1334         if (buflen > (drbg_max_request_bytes(shadow))) {
1335                 pr_devel("DRBG: requested random numbers too large %u\n",
1336                          buflen);
1337                 goto err;
1338         }
1339
1340         /* 9.3.1 step 3 is implicit with the chosen DRBG */
1341
1342         /* 9.3.1 step 4 */
1343         if (addtl && addtl->len > (drbg_max_addtl(shadow))) {
1344                 pr_devel("DRBG: additional information string too long %zu\n",
1345                          addtl->len);
1346                 goto err;
1347         }
1348         /* 9.3.1 step 5 is implicit with the chosen DRBG */
1349
1350         /*
1351          * 9.3.1 step 6 and 9 supplemented by 9.3.2 step c is implemented
1352          * here. The spec is a bit convoluted here, we make it simpler.
1353          */
1354         if ((drbg_max_requests(shadow)) < shadow->reseed_ctr)
1355                 shadow->seeded = false;
1356
1357         /* allocate cipher handle */
1358         len = shadow->d_ops->crypto_init(shadow);
1359         if (len)
1360                 goto err;
1361
1362         if (shadow->pr || !shadow->seeded) {
1363                 pr_devel("DRBG: reseeding before generation (prediction "
1364                          "resistance: %s, state %s)\n",
1365                          drbg->pr ? "true" : "false",
1366                          drbg->seeded ? "seeded" : "unseeded");
1367                 /* 9.3.1 steps 7.1 through 7.3 */
1368                 len = drbg_seed(shadow, addtl, true);
1369                 if (len)
1370                         goto err;
1371                 /* 9.3.1 step 7.4 */
1372                 addtl = NULL;
1373         }
1374
1375         /*
1376          * Mix the time stamp into the DRBG state if the DRBG is not in
1377          * test mode. If there are two callers invoking the DRBG at the same
1378          * time, i.e. before the first caller merges its shadow state back,
1379          * both callers would obtain the same random number stream without
1380          * changing the state here.
1381          */
1382         if (!drbg->test_data) {
1383                 now.cycles = random_get_entropy();
1384                 drbg_string_fill(&timestamp, now.char_cycles, sizeof(cycles_t));
1385                 list_add_tail(&timestamp.list, &addtllist);
1386         }
1387         if (addtl && 0 < addtl->len)
1388                 list_add_tail(&addtl->list, &addtllist);
1389         /* 9.3.1 step 8 and 10 */
1390         len = shadow->d_ops->generate(shadow, buf, buflen, &addtllist);
1391
1392         /* 10.1.1.4 step 6, 10.1.2.5 step 7, 10.2.1.5.2 step 7 */
1393         shadow->reseed_ctr++;
1394         if (0 >= len)
1395                 goto err;
1396
1397         /*
1398          * Section 11.3.3 requires to re-perform self tests after some
1399          * generated random numbers. The chosen value after which self
1400          * test is performed is arbitrary, but it should be reasonable.
1401          * However, we do not perform the self tests because of the following
1402          * reasons: it is mathematically impossible that the initial self tests
1403          * were successfully and the following are not. If the initial would
1404          * pass and the following would not, the kernel integrity is violated.
1405          * In this case, the entire kernel operation is questionable and it
1406          * is unlikely that the integrity violation only affects the
1407          * correct operation of the DRBG.
1408          *
1409          * Albeit the following code is commented out, it is provided in
1410          * case somebody has a need to implement the test of 11.3.3.
1411          */
1412 #if 0
1413         if (shadow->reseed_ctr && !(shadow->reseed_ctr % 4096)) {
1414                 int err = 0;
1415                 pr_devel("DRBG: start to perform self test\n");
1416                 if (drbg->core->flags & DRBG_HMAC)
1417                         err = alg_test("drbg_pr_hmac_sha256",
1418                                        "drbg_pr_hmac_sha256", 0, 0);
1419                 else if (drbg->core->flags & DRBG_CTR)
1420                         err = alg_test("drbg_pr_ctr_aes128",
1421                                        "drbg_pr_ctr_aes128", 0, 0);
1422                 else
1423                         err = alg_test("drbg_pr_sha256",
1424                                        "drbg_pr_sha256", 0, 0);
1425                 if (err) {
1426                         pr_err("DRBG: periodical self test failed\n");
1427                         /*
1428                          * uninstantiate implies that from now on, only errors
1429                          * are returned when reusing this DRBG cipher handle
1430                          */
1431                         drbg_uninstantiate(drbg);
1432                         drbg_dealloc_state(shadow);
1433                         kzfree(shadow);
1434                         return 0;
1435                 } else {
1436                         pr_devel("DRBG: self test successful\n");
1437                 }
1438         }
1439 #endif
1440
1441 err:
1442         shadow->d_ops->crypto_fini(shadow);
1443         drbg_restore_shadow(drbg, &shadow);
1444         return len;
1445 }
1446
1447 /*
1448  * Wrapper around drbg_generate which can pull arbitrary long strings
1449  * from the DRBG without hitting the maximum request limitation.
1450  *
1451  * Parameters: see drbg_generate
1452  * Return codes: see drbg_generate -- if one drbg_generate request fails,
1453  *               the entire drbg_generate_long request fails
1454  */
1455 static int drbg_generate_long(struct drbg_state *drbg,
1456                               unsigned char *buf, unsigned int buflen,
1457                               struct drbg_string *addtl)
1458 {
1459         int len = 0;
1460         unsigned int slice = 0;
1461         do {
1462                 int tmplen = 0;
1463                 unsigned int chunk = 0;
1464                 slice = ((buflen - len) / drbg_max_request_bytes(drbg));
1465                 chunk = slice ? drbg_max_request_bytes(drbg) : (buflen - len);
1466                 tmplen = drbg_generate(drbg, buf + len, chunk, addtl);
1467                 if (0 >= tmplen)
1468                         return tmplen;
1469                 len += tmplen;
1470         } while (slice > 0 && (len < buflen));
1471         return len;
1472 }
1473
1474 /*
1475  * DRBG instantiation function as required by SP800-90A - this function
1476  * sets up the DRBG handle, performs the initial seeding and all sanity
1477  * checks required by SP800-90A
1478  *
1479  * @drbg memory of state -- if NULL, new memory is allocated
1480  * @pers Personalization string that is mixed into state, may be NULL -- note
1481  *       the entropy is pulled by the DRBG internally unconditionally
1482  *       as defined in SP800-90A. The additional input is mixed into
1483  *       the state in addition to the pulled entropy.
1484  * @coreref reference to core
1485  * @pr prediction resistance enabled
1486  *
1487  * return
1488  *      0 on success
1489  *      error value otherwise
1490  */
1491 static int drbg_instantiate(struct drbg_state *drbg, struct drbg_string *pers,
1492                             int coreref, bool pr)
1493 {
1494         int ret = -ENOMEM;
1495
1496         pr_devel("DRBG: Initializing DRBG core %d with prediction resistance "
1497                  "%s\n", coreref, pr ? "enabled" : "disabled");
1498         drbg->core = &drbg_cores[coreref];
1499         drbg->pr = pr;
1500         drbg->seeded = false;
1501         switch (drbg->core->flags & DRBG_TYPE_MASK) {
1502 #ifdef CONFIG_CRYPTO_DRBG_HMAC
1503         case DRBG_HMAC:
1504                 drbg->d_ops = &drbg_hmac_ops;
1505                 break;
1506 #endif /* CONFIG_CRYPTO_DRBG_HMAC */
1507 #ifdef CONFIG_CRYPTO_DRBG_HASH
1508         case DRBG_HASH:
1509                 drbg->d_ops = &drbg_hash_ops;
1510                 break;
1511 #endif /* CONFIG_CRYPTO_DRBG_HASH */
1512 #ifdef CONFIG_CRYPTO_DRBG_CTR
1513         case DRBG_CTR:
1514                 drbg->d_ops = &drbg_ctr_ops;
1515                 break;
1516 #endif /* CONFIG_CRYPTO_DRBG_CTR */
1517         default:
1518                 return -EOPNOTSUPP;
1519         }
1520
1521         /* 9.1 step 1 is implicit with the selected DRBG type */
1522
1523         /*
1524          * 9.1 step 2 is implicit as caller can select prediction resistance
1525          * and the flag is copied into drbg->flags --
1526          * all DRBG types support prediction resistance
1527          */
1528
1529         /* 9.1 step 4 is implicit in  drbg_sec_strength */
1530
1531         ret = drbg_alloc_state(drbg);
1532         if (ret)
1533                 return ret;
1534
1535         ret = -EFAULT;
1536         if (drbg->d_ops->crypto_init(drbg))
1537                 goto err;
1538         ret = drbg_seed(drbg, pers, false);
1539         drbg->d_ops->crypto_fini(drbg);
1540         if (ret)
1541                 goto err;
1542
1543         return 0;
1544
1545 err:
1546         drbg_dealloc_state(drbg);
1547         return ret;
1548 }
1549
1550 /*
1551  * DRBG uninstantiate function as required by SP800-90A - this function
1552  * frees all buffers and the DRBG handle
1553  *
1554  * @drbg DRBG state handle
1555  *
1556  * return
1557  *      0 on success
1558  */
1559 static int drbg_uninstantiate(struct drbg_state *drbg)
1560 {
1561         spin_lock_bh(&drbg->drbg_lock);
1562         drbg_dealloc_state(drbg);
1563         /* no scrubbing of test_data -- this shall survive an uninstantiate */
1564         spin_unlock_bh(&drbg->drbg_lock);
1565         return 0;
1566 }
1567
1568 /*
1569  * Helper function for setting the test data in the DRBG
1570  *
1571  * @drbg DRBG state handle
1572  * @test_data test data to sets
1573  */
1574 static inline void drbg_set_testdata(struct drbg_state *drbg,
1575                                      struct drbg_test_data *test_data)
1576 {
1577         if (!test_data || !test_data->testentropy)
1578                 return;
1579         spin_lock_bh(&drbg->drbg_lock);
1580         drbg->test_data = test_data;
1581         spin_unlock_bh(&drbg->drbg_lock);
1582 }
1583
1584 /***************************************************************
1585  * Kernel crypto API cipher invocations requested by DRBG
1586  ***************************************************************/
1587
1588 #if defined(CONFIG_CRYPTO_DRBG_HASH) || defined(CONFIG_CRYPTO_DRBG_HMAC)
1589 struct sdesc {
1590         struct shash_desc shash;
1591         char ctx[];
1592 };
1593
1594 static int drbg_init_hash_kernel(struct drbg_state *drbg)
1595 {
1596         struct sdesc *sdesc;
1597         struct crypto_shash *tfm;
1598
1599         tfm = crypto_alloc_shash(drbg->core->backend_cra_name, 0, 0);
1600         if (IS_ERR(tfm)) {
1601                 pr_info("DRBG: could not allocate digest TFM handle\n");
1602                 return PTR_ERR(tfm);
1603         }
1604         BUG_ON(drbg_blocklen(drbg) != crypto_shash_digestsize(tfm));
1605         sdesc = kzalloc(sizeof(struct shash_desc) + crypto_shash_descsize(tfm),
1606                         GFP_KERNEL);
1607         if (!sdesc) {
1608                 crypto_free_shash(tfm);
1609                 return -ENOMEM;
1610         }
1611
1612         sdesc->shash.tfm = tfm;
1613         sdesc->shash.flags = 0;
1614         drbg->priv_data = sdesc;
1615         return 0;
1616 }
1617
1618 static int drbg_fini_hash_kernel(struct drbg_state *drbg)
1619 {
1620         struct sdesc *sdesc = (struct sdesc *)drbg->priv_data;
1621         if (sdesc) {
1622                 crypto_free_shash(sdesc->shash.tfm);
1623                 kzfree(sdesc);
1624         }
1625         drbg->priv_data = NULL;
1626         return 0;
1627 }
1628
1629 static int drbg_kcapi_hash(struct drbg_state *drbg, const unsigned char *key,
1630                            unsigned char *outval, const struct list_head *in)
1631 {
1632         struct sdesc *sdesc = (struct sdesc *)drbg->priv_data;
1633         struct drbg_string *input = NULL;
1634
1635         if (key)
1636                 crypto_shash_setkey(sdesc->shash.tfm, key, drbg_statelen(drbg));
1637         crypto_shash_init(&sdesc->shash);
1638         list_for_each_entry(input, in, list)
1639                 crypto_shash_update(&sdesc->shash, input->buf, input->len);
1640         return crypto_shash_final(&sdesc->shash, outval);
1641 }
1642 #endif /* (CONFIG_CRYPTO_DRBG_HASH || CONFIG_CRYPTO_DRBG_HMAC) */
1643
1644 #ifdef CONFIG_CRYPTO_DRBG_CTR
1645 static int drbg_init_sym_kernel(struct drbg_state *drbg)
1646 {
1647         int ret = 0;
1648         struct crypto_blkcipher *tfm;
1649
1650         tfm = crypto_alloc_blkcipher(drbg->core->backend_cra_name, 0, 0);
1651         if (IS_ERR(tfm)) {
1652                 pr_info("DRBG: could not allocate cipher TFM handle\n");
1653                 return PTR_ERR(tfm);
1654         }
1655         BUG_ON(drbg_blocklen(drbg) != crypto_blkcipher_blocksize(tfm));
1656         drbg->priv_data = tfm;
1657         return ret;
1658 }
1659
1660 static int drbg_fini_sym_kernel(struct drbg_state *drbg)
1661 {
1662         struct crypto_blkcipher *tfm =
1663                 (struct crypto_blkcipher *)drbg->priv_data;
1664         if (tfm)
1665                 crypto_free_blkcipher(tfm);
1666         drbg->priv_data = NULL;
1667         return 0;
1668 }
1669
1670 static int drbg_kcapi_sym(struct drbg_state *drbg, const unsigned char *key,
1671                           unsigned char *outval, const struct drbg_string *in)
1672 {
1673         int ret = 0;
1674         struct scatterlist sg_in, sg_out;
1675         struct blkcipher_desc desc;
1676         struct crypto_blkcipher *tfm =
1677                 (struct crypto_blkcipher *)drbg->priv_data;
1678
1679         desc.tfm = tfm;
1680         desc.flags = 0;
1681         crypto_blkcipher_setkey(tfm, key, (drbg_keylen(drbg)));
1682         /* there is only component in *in */
1683         sg_init_one(&sg_in, in->buf, in->len);
1684         sg_init_one(&sg_out, outval, drbg_blocklen(drbg));
1685         ret = crypto_blkcipher_encrypt(&desc, &sg_out, &sg_in, in->len);
1686
1687         return ret;
1688 }
1689 #endif /* CONFIG_CRYPTO_DRBG_CTR */
1690
1691 /***************************************************************
1692  * Kernel crypto API interface to register DRBG
1693  ***************************************************************/
1694
1695 /*
1696  * Look up the DRBG flags by given kernel crypto API cra_name
1697  * The code uses the drbg_cores definition to do this
1698  *
1699  * @cra_name kernel crypto API cra_name
1700  * @coreref reference to integer which is filled with the pointer to
1701  *  the applicable core
1702  * @pr reference for setting prediction resistance
1703  *
1704  * return: flags
1705  */
1706 static inline void drbg_convert_tfm_core(const char *cra_driver_name,
1707                                          int *coreref, bool *pr)
1708 {
1709         int i = 0;
1710         size_t start = 0;
1711         int len = 0;
1712
1713         *pr = true;
1714         /* disassemble the names */
1715         if (!memcmp(cra_driver_name, "drbg_nopr_", 10)) {
1716                 start = 10;
1717                 *pr = false;
1718         } else if (!memcmp(cra_driver_name, "drbg_pr_", 8)) {
1719                 start = 8;
1720         } else {
1721                 return;
1722         }
1723
1724         /* remove the first part */
1725         len = strlen(cra_driver_name) - start;
1726         for (i = 0; ARRAY_SIZE(drbg_cores) > i; i++) {
1727                 if (!memcmp(cra_driver_name + start, drbg_cores[i].cra_name,
1728                             len)) {
1729                         *coreref = i;
1730                         return;
1731                 }
1732         }
1733 }
1734
1735 static int drbg_kcapi_init(struct crypto_tfm *tfm)
1736 {
1737         struct drbg_state *drbg = crypto_tfm_ctx(tfm);
1738         bool pr = false;
1739         int coreref = 0;
1740
1741         drbg_convert_tfm_core(crypto_tfm_alg_driver_name(tfm), &coreref, &pr);
1742         /*
1743          * when personalization string is needed, the caller must call reset
1744          * and provide the personalization string as seed information
1745          */
1746         return drbg_instantiate(drbg, NULL, coreref, pr);
1747 }
1748
1749 static void drbg_kcapi_cleanup(struct crypto_tfm *tfm)
1750 {
1751         drbg_uninstantiate(crypto_tfm_ctx(tfm));
1752 }
1753
1754 /*
1755  * Generate random numbers invoked by the kernel crypto API:
1756  * The API of the kernel crypto API is extended as follows:
1757  *
1758  * If dlen is larger than zero, rdata is interpreted as the output buffer
1759  * where random data is to be stored.
1760  *
1761  * If dlen is zero, rdata is interpreted as a pointer to a struct drbg_gen
1762  * which holds the additional information string that is used for the
1763  * DRBG generation process. The output buffer that is to be used to store
1764  * data is also pointed to by struct drbg_gen.
1765  */
1766 static int drbg_kcapi_random(struct crypto_rng *tfm, u8 *rdata,
1767                              unsigned int dlen)
1768 {
1769         struct drbg_state *drbg = crypto_rng_ctx(tfm);
1770         if (0 < dlen) {
1771                 return drbg_generate_long(drbg, rdata, dlen, NULL);
1772         } else {
1773                 struct drbg_gen *data = (struct drbg_gen *)rdata;
1774                 struct drbg_string addtl;
1775                 /* catch NULL pointer */
1776                 if (!data)
1777                         return 0;
1778                 drbg_set_testdata(drbg, data->test_data);
1779                 /* linked list variable is now local to allow modification */
1780                 drbg_string_fill(&addtl, data->addtl->buf, data->addtl->len);
1781                 return drbg_generate_long(drbg, data->outbuf, data->outlen,
1782                                           &addtl);
1783         }
1784 }
1785
1786 /*
1787  * Reset the DRBG invoked by the kernel crypto API
1788  * The reset implies a full re-initialization of the DRBG. Similar to the
1789  * generate function of drbg_kcapi_random, this function extends the
1790  * kernel crypto API interface with struct drbg_gen
1791  */
1792 static int drbg_kcapi_reset(struct crypto_rng *tfm, u8 *seed, unsigned int slen)
1793 {
1794         struct drbg_state *drbg = crypto_rng_ctx(tfm);
1795         struct crypto_tfm *tfm_base = crypto_rng_tfm(tfm);
1796         bool pr = false;
1797         struct drbg_string seed_string;
1798         int coreref = 0;
1799
1800         drbg_uninstantiate(drbg);
1801         drbg_convert_tfm_core(crypto_tfm_alg_driver_name(tfm_base), &coreref,
1802                               &pr);
1803         if (0 < slen) {
1804                 drbg_string_fill(&seed_string, seed, slen);
1805                 return drbg_instantiate(drbg, &seed_string, coreref, pr);
1806         } else {
1807                 struct drbg_gen *data = (struct drbg_gen *)seed;
1808                 /* allow invocation of API call with NULL, 0 */
1809                 if (!data)
1810                         return drbg_instantiate(drbg, NULL, coreref, pr);
1811                 drbg_set_testdata(drbg, data->test_data);
1812                 /* linked list variable is now local to allow modification */
1813                 drbg_string_fill(&seed_string, data->addtl->buf,
1814                                  data->addtl->len);
1815                 return drbg_instantiate(drbg, &seed_string, coreref, pr);
1816         }
1817 }
1818
1819 /***************************************************************
1820  * Kernel module: code to load the module
1821  ***************************************************************/
1822
1823 /*
1824  * Tests as defined in 11.3.2 in addition to the cipher tests: testing
1825  * of the error handling.
1826  *
1827  * Note: testing of failing seed source as defined in 11.3.2 is not applicable
1828  * as seed source of get_random_bytes does not fail.
1829  *
1830  * Note 2: There is no sensible way of testing the reseed counter
1831  * enforcement, so skip it.
1832  */
1833 static inline int __init drbg_healthcheck_sanity(void)
1834 {
1835 #ifdef CONFIG_CRYPTO_FIPS
1836         int len = 0;
1837 #define OUTBUFLEN 16
1838         unsigned char buf[OUTBUFLEN];
1839         struct drbg_state *drbg = NULL;
1840         int ret = -EFAULT;
1841         int rc = -EFAULT;
1842         bool pr = false;
1843         int coreref = 0;
1844         struct drbg_string addtl;
1845         size_t max_addtllen, max_request_bytes;
1846
1847         /* only perform test in FIPS mode */
1848         if (!fips_enabled)
1849                 return 0;
1850
1851 #ifdef CONFIG_CRYPTO_DRBG_CTR
1852         drbg_convert_tfm_core("drbg_nopr_ctr_aes128", &coreref, &pr);
1853 #elif defined CONFIG_CRYPTO_DRBG_HASH
1854         drbg_convert_tfm_core("drbg_nopr_sha256", &coreref, &pr);
1855 #else
1856         drbg_convert_tfm_core("drbg_nopr_hmac_sha256", &coreref, &pr);
1857 #endif
1858
1859         drbg = kzalloc(sizeof(struct drbg_state), GFP_KERNEL);
1860         if (!drbg)
1861                 return -ENOMEM;
1862
1863         /*
1864          * if the following tests fail, it is likely that there is a buffer
1865          * overflow as buf is much smaller than the requested or provided
1866          * string lengths -- in case the error handling does not succeed
1867          * we may get an OOPS. And we want to get an OOPS as this is a
1868          * grave bug.
1869          */
1870
1871         /* get a valid instance of DRBG for following tests */
1872         ret = drbg_instantiate(drbg, NULL, coreref, pr);
1873         if (ret) {
1874                 rc = ret;
1875                 goto outbuf;
1876         }
1877         max_addtllen = drbg_max_addtl(drbg);
1878         max_request_bytes = drbg_max_request_bytes(drbg);
1879         drbg_string_fill(&addtl, buf, max_addtllen + 1);
1880         /* overflow addtllen with additonal info string */
1881         len = drbg_generate(drbg, buf, OUTBUFLEN, &addtl);
1882         BUG_ON(0 < len);
1883         /* overflow max_bits */
1884         len = drbg_generate(drbg, buf, (max_request_bytes + 1), NULL);
1885         BUG_ON(0 < len);
1886         drbg_uninstantiate(drbg);
1887
1888         /* overflow max addtllen with personalization string */
1889         ret = drbg_instantiate(drbg, &addtl, coreref, pr);
1890         BUG_ON(0 == ret);
1891         /* all tests passed */
1892         rc = 0;
1893
1894         pr_devel("DRBG: Sanity tests for failure code paths successfully "
1895                  "completed\n");
1896
1897         drbg_uninstantiate(drbg);
1898 outbuf:
1899         kzfree(drbg);
1900         return rc;
1901 #else /* CONFIG_CRYPTO_FIPS */
1902         return 0;
1903 #endif /* CONFIG_CRYPTO_FIPS */
1904 }
1905
1906 static struct crypto_alg drbg_algs[22];
1907
1908 /*
1909  * Fill the array drbg_algs used to register the different DRBGs
1910  * with the kernel crypto API. To fill the array, the information
1911  * from drbg_cores[] is used.
1912  */
1913 static inline void __init drbg_fill_array(struct crypto_alg *alg,
1914                                           const struct drbg_core *core, int pr)
1915 {
1916         int pos = 0;
1917         static int priority = 100;
1918
1919         memset(alg, 0, sizeof(struct crypto_alg));
1920         memcpy(alg->cra_name, "stdrng", 6);
1921         if (pr) {
1922                 memcpy(alg->cra_driver_name, "drbg_pr_", 8);
1923                 pos = 8;
1924         } else {
1925                 memcpy(alg->cra_driver_name, "drbg_nopr_", 10);
1926                 pos = 10;
1927         }
1928         memcpy(alg->cra_driver_name + pos, core->cra_name,
1929                strlen(core->cra_name));
1930
1931         alg->cra_priority = priority;
1932         priority++;
1933         /*
1934          * If FIPS mode enabled, the selected DRBG shall have the
1935          * highest cra_priority over other stdrng instances to ensure
1936          * it is selected.
1937          */
1938         if (fips_enabled)
1939                 alg->cra_priority += 200;
1940
1941         alg->cra_flags          = CRYPTO_ALG_TYPE_RNG;
1942         alg->cra_ctxsize        = sizeof(struct drbg_state);
1943         alg->cra_type           = &crypto_rng_type;
1944         alg->cra_module         = THIS_MODULE;
1945         alg->cra_init           = drbg_kcapi_init;
1946         alg->cra_exit           = drbg_kcapi_cleanup;
1947         alg->cra_u.rng.rng_make_random  = drbg_kcapi_random;
1948         alg->cra_u.rng.rng_reset        = drbg_kcapi_reset;
1949         alg->cra_u.rng.seedsize = 0;
1950 }
1951
1952 static int __init drbg_init(void)
1953 {
1954         unsigned int i = 0; /* pointer to drbg_algs */
1955         unsigned int j = 0; /* pointer to drbg_cores */
1956         int ret = -EFAULT;
1957
1958         ret = drbg_healthcheck_sanity();
1959         if (ret)
1960                 return ret;
1961
1962         if (ARRAY_SIZE(drbg_cores) * 2 > ARRAY_SIZE(drbg_algs)) {
1963                 pr_info("DRBG: Cannot register all DRBG types"
1964                         "(slots needed: %zu, slots available: %zu)\n",
1965                         ARRAY_SIZE(drbg_cores) * 2, ARRAY_SIZE(drbg_algs));
1966                 return ret;
1967         }
1968
1969         /*
1970          * each DRBG definition can be used with PR and without PR, thus
1971          * we instantiate each DRBG in drbg_cores[] twice.
1972          *
1973          * As the order of placing them into the drbg_algs array matters
1974          * (the later DRBGs receive a higher cra_priority) we register the
1975          * prediction resistance DRBGs first as the should not be too
1976          * interesting.
1977          */
1978         for (j = 0; ARRAY_SIZE(drbg_cores) > j; j++, i++)
1979                 drbg_fill_array(&drbg_algs[i], &drbg_cores[j], 1);
1980         for (j = 0; ARRAY_SIZE(drbg_cores) > j; j++, i++)
1981                 drbg_fill_array(&drbg_algs[i], &drbg_cores[j], 0);
1982         return crypto_register_algs(drbg_algs, (ARRAY_SIZE(drbg_cores) * 2));
1983 }
1984
1985 static void __exit drbg_exit(void)
1986 {
1987         crypto_unregister_algs(drbg_algs, (ARRAY_SIZE(drbg_cores) * 2));
1988 }
1989
1990 module_init(drbg_init);
1991 module_exit(drbg_exit);
1992 #ifndef CRYPTO_DRBG_HASH_STRING
1993 #define CRYPTO_DRBG_HASH_STRING ""
1994 #endif
1995 #ifndef CRYPTO_DRBG_HMAC_STRING
1996 #define CRYPTO_DRBG_HMAC_STRING ""
1997 #endif
1998 #ifndef CRYPTO_DRBG_CTR_STRING
1999 #define CRYPTO_DRBG_CTR_STRING ""
2000 #endif
2001 MODULE_LICENSE("GPL");
2002 MODULE_AUTHOR("Stephan Mueller <smueller@chronox.de>");
2003 MODULE_DESCRIPTION("NIST SP800-90A Deterministic Random Bit Generator (DRBG) "
2004                    "using following cores: "
2005                    CRYPTO_DRBG_HASH_STRING
2006                    CRYPTO_DRBG_HMAC_STRING
2007                    CRYPTO_DRBG_CTR_STRING);