LoongArch: BPF: Don't sign extend memory load operand
[platform/kernel/linux-starfive.git] / crypto / testmgr.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Algorithm testing framework and tests.
4  *
5  * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
6  * Copyright (c) 2002 Jean-Francois Dive <jef@linuxbe.org>
7  * Copyright (c) 2007 Nokia Siemens Networks
8  * Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au>
9  * Copyright (c) 2019 Google LLC
10  *
11  * Updated RFC4106 AES-GCM testing.
12  *    Authors: Aidan O'Mahony (aidan.o.mahony@intel.com)
13  *             Adrian Hoban <adrian.hoban@intel.com>
14  *             Gabriele Paoloni <gabriele.paoloni@intel.com>
15  *             Tadeusz Struk (tadeusz.struk@intel.com)
16  *    Copyright (c) 2010, Intel Corporation.
17  */
18
19 #include <crypto/aead.h>
20 #include <crypto/hash.h>
21 #include <crypto/skcipher.h>
22 #include <linux/err.h>
23 #include <linux/fips.h>
24 #include <linux/module.h>
25 #include <linux/once.h>
26 #include <linux/random.h>
27 #include <linux/scatterlist.h>
28 #include <linux/slab.h>
29 #include <linux/string.h>
30 #include <linux/uio.h>
31 #include <crypto/rng.h>
32 #include <crypto/drbg.h>
33 #include <crypto/akcipher.h>
34 #include <crypto/kpp.h>
35 #include <crypto/acompress.h>
36 #include <crypto/internal/cipher.h>
37 #include <crypto/internal/simd.h>
38
39 #include "internal.h"
40
41 MODULE_IMPORT_NS(CRYPTO_INTERNAL);
42
43 static bool notests;
44 module_param(notests, bool, 0644);
45 MODULE_PARM_DESC(notests, "disable crypto self-tests");
46
47 static bool panic_on_fail;
48 module_param(panic_on_fail, bool, 0444);
49
50 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
51 static bool noextratests;
52 module_param(noextratests, bool, 0644);
53 MODULE_PARM_DESC(noextratests, "disable expensive crypto self-tests");
54
55 static unsigned int fuzz_iterations = 100;
56 module_param(fuzz_iterations, uint, 0644);
57 MODULE_PARM_DESC(fuzz_iterations, "number of fuzz test iterations");
58 #endif
59
60 #ifdef CONFIG_CRYPTO_MANAGER_DISABLE_TESTS
61
62 /* a perfect nop */
63 int alg_test(const char *driver, const char *alg, u32 type, u32 mask)
64 {
65         return 0;
66 }
67
68 #else
69
70 #include "testmgr.h"
71
72 /*
73  * Need slab memory for testing (size in number of pages).
74  */
75 #define XBUFSIZE        8
76
77 /*
78 * Used by test_cipher()
79 */
80 #define ENCRYPT 1
81 #define DECRYPT 0
82
83 struct aead_test_suite {
84         const struct aead_testvec *vecs;
85         unsigned int count;
86
87         /*
88          * Set if trying to decrypt an inauthentic ciphertext with this
89          * algorithm might result in EINVAL rather than EBADMSG, due to other
90          * validation the algorithm does on the inputs such as length checks.
91          */
92         unsigned int einval_allowed : 1;
93
94         /*
95          * Set if this algorithm requires that the IV be located at the end of
96          * the AAD buffer, in addition to being given in the normal way.  The
97          * behavior when the two IV copies differ is implementation-defined.
98          */
99         unsigned int aad_iv : 1;
100 };
101
102 struct cipher_test_suite {
103         const struct cipher_testvec *vecs;
104         unsigned int count;
105 };
106
107 struct comp_test_suite {
108         struct {
109                 const struct comp_testvec *vecs;
110                 unsigned int count;
111         } comp, decomp;
112 };
113
114 struct hash_test_suite {
115         const struct hash_testvec *vecs;
116         unsigned int count;
117 };
118
119 struct cprng_test_suite {
120         const struct cprng_testvec *vecs;
121         unsigned int count;
122 };
123
124 struct drbg_test_suite {
125         const struct drbg_testvec *vecs;
126         unsigned int count;
127 };
128
129 struct akcipher_test_suite {
130         const struct akcipher_testvec *vecs;
131         unsigned int count;
132 };
133
134 struct kpp_test_suite {
135         const struct kpp_testvec *vecs;
136         unsigned int count;
137 };
138
139 struct alg_test_desc {
140         const char *alg;
141         const char *generic_driver;
142         int (*test)(const struct alg_test_desc *desc, const char *driver,
143                     u32 type, u32 mask);
144         int fips_allowed;       /* set if alg is allowed in fips mode */
145
146         union {
147                 struct aead_test_suite aead;
148                 struct cipher_test_suite cipher;
149                 struct comp_test_suite comp;
150                 struct hash_test_suite hash;
151                 struct cprng_test_suite cprng;
152                 struct drbg_test_suite drbg;
153                 struct akcipher_test_suite akcipher;
154                 struct kpp_test_suite kpp;
155         } suite;
156 };
157
158 static void hexdump(unsigned char *buf, unsigned int len)
159 {
160         print_hex_dump(KERN_CONT, "", DUMP_PREFIX_OFFSET,
161                         16, 1,
162                         buf, len, false);
163 }
164
165 static int __testmgr_alloc_buf(char *buf[XBUFSIZE], int order)
166 {
167         int i;
168
169         for (i = 0; i < XBUFSIZE; i++) {
170                 buf[i] = (char *)__get_free_pages(GFP_KERNEL, order);
171                 if (!buf[i])
172                         goto err_free_buf;
173         }
174
175         return 0;
176
177 err_free_buf:
178         while (i-- > 0)
179                 free_pages((unsigned long)buf[i], order);
180
181         return -ENOMEM;
182 }
183
184 static int testmgr_alloc_buf(char *buf[XBUFSIZE])
185 {
186         return __testmgr_alloc_buf(buf, 0);
187 }
188
189 static void __testmgr_free_buf(char *buf[XBUFSIZE], int order)
190 {
191         int i;
192
193         for (i = 0; i < XBUFSIZE; i++)
194                 free_pages((unsigned long)buf[i], order);
195 }
196
197 static void testmgr_free_buf(char *buf[XBUFSIZE])
198 {
199         __testmgr_free_buf(buf, 0);
200 }
201
202 #define TESTMGR_POISON_BYTE     0xfe
203 #define TESTMGR_POISON_LEN      16
204
205 static inline void testmgr_poison(void *addr, size_t len)
206 {
207         memset(addr, TESTMGR_POISON_BYTE, len);
208 }
209
210 /* Is the memory region still fully poisoned? */
211 static inline bool testmgr_is_poison(const void *addr, size_t len)
212 {
213         return memchr_inv(addr, TESTMGR_POISON_BYTE, len) == NULL;
214 }
215
216 /* flush type for hash algorithms */
217 enum flush_type {
218         /* merge with update of previous buffer(s) */
219         FLUSH_TYPE_NONE = 0,
220
221         /* update with previous buffer(s) before doing this one */
222         FLUSH_TYPE_FLUSH,
223
224         /* likewise, but also export and re-import the intermediate state */
225         FLUSH_TYPE_REIMPORT,
226 };
227
228 /* finalization function for hash algorithms */
229 enum finalization_type {
230         FINALIZATION_TYPE_FINAL,        /* use final() */
231         FINALIZATION_TYPE_FINUP,        /* use finup() */
232         FINALIZATION_TYPE_DIGEST,       /* use digest() */
233 };
234
235 /*
236  * Whether the crypto operation will occur in-place, and if so whether the
237  * source and destination scatterlist pointers will coincide (req->src ==
238  * req->dst), or whether they'll merely point to two separate scatterlists
239  * (req->src != req->dst) that reference the same underlying memory.
240  *
241  * This is only relevant for algorithm types that support in-place operation.
242  */
243 enum inplace_mode {
244         OUT_OF_PLACE,
245         INPLACE_ONE_SGLIST,
246         INPLACE_TWO_SGLISTS,
247 };
248
249 #define TEST_SG_TOTAL   10000
250
251 /**
252  * struct test_sg_division - description of a scatterlist entry
253  *
254  * This struct describes one entry of a scatterlist being constructed to check a
255  * crypto test vector.
256  *
257  * @proportion_of_total: length of this chunk relative to the total length,
258  *                       given as a proportion out of TEST_SG_TOTAL so that it
259  *                       scales to fit any test vector
260  * @offset: byte offset into a 2-page buffer at which this chunk will start
261  * @offset_relative_to_alignmask: if true, add the algorithm's alignmask to the
262  *                                @offset
263  * @flush_type: for hashes, whether an update() should be done now vs.
264  *              continuing to accumulate data
265  * @nosimd: if doing the pending update(), do it with SIMD disabled?
266  */
267 struct test_sg_division {
268         unsigned int proportion_of_total;
269         unsigned int offset;
270         bool offset_relative_to_alignmask;
271         enum flush_type flush_type;
272         bool nosimd;
273 };
274
275 /**
276  * struct testvec_config - configuration for testing a crypto test vector
277  *
278  * This struct describes the data layout and other parameters with which each
279  * crypto test vector can be tested.
280  *
281  * @name: name of this config, logged for debugging purposes if a test fails
282  * @inplace_mode: whether and how to operate on the data in-place, if applicable
283  * @req_flags: extra request_flags, e.g. CRYPTO_TFM_REQ_MAY_SLEEP
284  * @src_divs: description of how to arrange the source scatterlist
285  * @dst_divs: description of how to arrange the dst scatterlist, if applicable
286  *            for the algorithm type.  Defaults to @src_divs if unset.
287  * @iv_offset: misalignment of the IV in the range [0..MAX_ALGAPI_ALIGNMASK+1],
288  *             where 0 is aligned to a 2*(MAX_ALGAPI_ALIGNMASK+1) byte boundary
289  * @iv_offset_relative_to_alignmask: if true, add the algorithm's alignmask to
290  *                                   the @iv_offset
291  * @key_offset: misalignment of the key, where 0 is default alignment
292  * @key_offset_relative_to_alignmask: if true, add the algorithm's alignmask to
293  *                                    the @key_offset
294  * @finalization_type: what finalization function to use for hashes
295  * @nosimd: execute with SIMD disabled?  Requires !CRYPTO_TFM_REQ_MAY_SLEEP.
296  */
297 struct testvec_config {
298         const char *name;
299         enum inplace_mode inplace_mode;
300         u32 req_flags;
301         struct test_sg_division src_divs[XBUFSIZE];
302         struct test_sg_division dst_divs[XBUFSIZE];
303         unsigned int iv_offset;
304         unsigned int key_offset;
305         bool iv_offset_relative_to_alignmask;
306         bool key_offset_relative_to_alignmask;
307         enum finalization_type finalization_type;
308         bool nosimd;
309 };
310
311 #define TESTVEC_CONFIG_NAMELEN  192
312
313 /*
314  * The following are the lists of testvec_configs to test for each algorithm
315  * type when the basic crypto self-tests are enabled, i.e. when
316  * CONFIG_CRYPTO_MANAGER_DISABLE_TESTS is unset.  They aim to provide good test
317  * coverage, while keeping the test time much shorter than the full fuzz tests
318  * so that the basic tests can be enabled in a wider range of circumstances.
319  */
320
321 /* Configs for skciphers and aeads */
322 static const struct testvec_config default_cipher_testvec_configs[] = {
323         {
324                 .name = "in-place (one sglist)",
325                 .inplace_mode = INPLACE_ONE_SGLIST,
326                 .src_divs = { { .proportion_of_total = 10000 } },
327         }, {
328                 .name = "in-place (two sglists)",
329                 .inplace_mode = INPLACE_TWO_SGLISTS,
330                 .src_divs = { { .proportion_of_total = 10000 } },
331         }, {
332                 .name = "out-of-place",
333                 .inplace_mode = OUT_OF_PLACE,
334                 .src_divs = { { .proportion_of_total = 10000 } },
335         }, {
336                 .name = "unaligned buffer, offset=1",
337                 .src_divs = { { .proportion_of_total = 10000, .offset = 1 } },
338                 .iv_offset = 1,
339                 .key_offset = 1,
340         }, {
341                 .name = "buffer aligned only to alignmask",
342                 .src_divs = {
343                         {
344                                 .proportion_of_total = 10000,
345                                 .offset = 1,
346                                 .offset_relative_to_alignmask = true,
347                         },
348                 },
349                 .iv_offset = 1,
350                 .iv_offset_relative_to_alignmask = true,
351                 .key_offset = 1,
352                 .key_offset_relative_to_alignmask = true,
353         }, {
354                 .name = "two even aligned splits",
355                 .src_divs = {
356                         { .proportion_of_total = 5000 },
357                         { .proportion_of_total = 5000 },
358                 },
359         }, {
360                 .name = "uneven misaligned splits, may sleep",
361                 .req_flags = CRYPTO_TFM_REQ_MAY_SLEEP,
362                 .src_divs = {
363                         { .proportion_of_total = 1900, .offset = 33 },
364                         { .proportion_of_total = 3300, .offset = 7  },
365                         { .proportion_of_total = 4800, .offset = 18 },
366                 },
367                 .iv_offset = 3,
368                 .key_offset = 3,
369         }, {
370                 .name = "misaligned splits crossing pages, inplace",
371                 .inplace_mode = INPLACE_ONE_SGLIST,
372                 .src_divs = {
373                         {
374                                 .proportion_of_total = 7500,
375                                 .offset = PAGE_SIZE - 32
376                         }, {
377                                 .proportion_of_total = 2500,
378                                 .offset = PAGE_SIZE - 7
379                         },
380                 },
381         }
382 };
383
384 static const struct testvec_config default_hash_testvec_configs[] = {
385         {
386                 .name = "init+update+final aligned buffer",
387                 .src_divs = { { .proportion_of_total = 10000 } },
388                 .finalization_type = FINALIZATION_TYPE_FINAL,
389         }, {
390                 .name = "init+finup aligned buffer",
391                 .src_divs = { { .proportion_of_total = 10000 } },
392                 .finalization_type = FINALIZATION_TYPE_FINUP,
393         }, {
394                 .name = "digest aligned buffer",
395                 .src_divs = { { .proportion_of_total = 10000 } },
396                 .finalization_type = FINALIZATION_TYPE_DIGEST,
397         }, {
398                 .name = "init+update+final misaligned buffer",
399                 .src_divs = { { .proportion_of_total = 10000, .offset = 1 } },
400                 .finalization_type = FINALIZATION_TYPE_FINAL,
401                 .key_offset = 1,
402         }, {
403                 .name = "digest buffer aligned only to alignmask",
404                 .src_divs = {
405                         {
406                                 .proportion_of_total = 10000,
407                                 .offset = 1,
408                                 .offset_relative_to_alignmask = true,
409                         },
410                 },
411                 .finalization_type = FINALIZATION_TYPE_DIGEST,
412                 .key_offset = 1,
413                 .key_offset_relative_to_alignmask = true,
414         }, {
415                 .name = "init+update+update+final two even splits",
416                 .src_divs = {
417                         { .proportion_of_total = 5000 },
418                         {
419                                 .proportion_of_total = 5000,
420                                 .flush_type = FLUSH_TYPE_FLUSH,
421                         },
422                 },
423                 .finalization_type = FINALIZATION_TYPE_FINAL,
424         }, {
425                 .name = "digest uneven misaligned splits, may sleep",
426                 .req_flags = CRYPTO_TFM_REQ_MAY_SLEEP,
427                 .src_divs = {
428                         { .proportion_of_total = 1900, .offset = 33 },
429                         { .proportion_of_total = 3300, .offset = 7  },
430                         { .proportion_of_total = 4800, .offset = 18 },
431                 },
432                 .finalization_type = FINALIZATION_TYPE_DIGEST,
433         }, {
434                 .name = "digest misaligned splits crossing pages",
435                 .src_divs = {
436                         {
437                                 .proportion_of_total = 7500,
438                                 .offset = PAGE_SIZE - 32,
439                         }, {
440                                 .proportion_of_total = 2500,
441                                 .offset = PAGE_SIZE - 7,
442                         },
443                 },
444                 .finalization_type = FINALIZATION_TYPE_DIGEST,
445         }, {
446                 .name = "import/export",
447                 .src_divs = {
448                         {
449                                 .proportion_of_total = 6500,
450                                 .flush_type = FLUSH_TYPE_REIMPORT,
451                         }, {
452                                 .proportion_of_total = 3500,
453                                 .flush_type = FLUSH_TYPE_REIMPORT,
454                         },
455                 },
456                 .finalization_type = FINALIZATION_TYPE_FINAL,
457         }
458 };
459
460 static unsigned int count_test_sg_divisions(const struct test_sg_division *divs)
461 {
462         unsigned int remaining = TEST_SG_TOTAL;
463         unsigned int ndivs = 0;
464
465         do {
466                 remaining -= divs[ndivs++].proportion_of_total;
467         } while (remaining);
468
469         return ndivs;
470 }
471
472 #define SGDIVS_HAVE_FLUSHES     BIT(0)
473 #define SGDIVS_HAVE_NOSIMD      BIT(1)
474
475 static bool valid_sg_divisions(const struct test_sg_division *divs,
476                                unsigned int count, int *flags_ret)
477 {
478         unsigned int total = 0;
479         unsigned int i;
480
481         for (i = 0; i < count && total != TEST_SG_TOTAL; i++) {
482                 if (divs[i].proportion_of_total <= 0 ||
483                     divs[i].proportion_of_total > TEST_SG_TOTAL - total)
484                         return false;
485                 total += divs[i].proportion_of_total;
486                 if (divs[i].flush_type != FLUSH_TYPE_NONE)
487                         *flags_ret |= SGDIVS_HAVE_FLUSHES;
488                 if (divs[i].nosimd)
489                         *flags_ret |= SGDIVS_HAVE_NOSIMD;
490         }
491         return total == TEST_SG_TOTAL &&
492                 memchr_inv(&divs[i], 0, (count - i) * sizeof(divs[0])) == NULL;
493 }
494
495 /*
496  * Check whether the given testvec_config is valid.  This isn't strictly needed
497  * since every testvec_config should be valid, but check anyway so that people
498  * don't unknowingly add broken configs that don't do what they wanted.
499  */
500 static bool valid_testvec_config(const struct testvec_config *cfg)
501 {
502         int flags = 0;
503
504         if (cfg->name == NULL)
505                 return false;
506
507         if (!valid_sg_divisions(cfg->src_divs, ARRAY_SIZE(cfg->src_divs),
508                                 &flags))
509                 return false;
510
511         if (cfg->dst_divs[0].proportion_of_total) {
512                 if (!valid_sg_divisions(cfg->dst_divs,
513                                         ARRAY_SIZE(cfg->dst_divs), &flags))
514                         return false;
515         } else {
516                 if (memchr_inv(cfg->dst_divs, 0, sizeof(cfg->dst_divs)))
517                         return false;
518                 /* defaults to dst_divs=src_divs */
519         }
520
521         if (cfg->iv_offset +
522             (cfg->iv_offset_relative_to_alignmask ? MAX_ALGAPI_ALIGNMASK : 0) >
523             MAX_ALGAPI_ALIGNMASK + 1)
524                 return false;
525
526         if ((flags & (SGDIVS_HAVE_FLUSHES | SGDIVS_HAVE_NOSIMD)) &&
527             cfg->finalization_type == FINALIZATION_TYPE_DIGEST)
528                 return false;
529
530         if ((cfg->nosimd || (flags & SGDIVS_HAVE_NOSIMD)) &&
531             (cfg->req_flags & CRYPTO_TFM_REQ_MAY_SLEEP))
532                 return false;
533
534         return true;
535 }
536
537 struct test_sglist {
538         char *bufs[XBUFSIZE];
539         struct scatterlist sgl[XBUFSIZE];
540         struct scatterlist sgl_saved[XBUFSIZE];
541         struct scatterlist *sgl_ptr;
542         unsigned int nents;
543 };
544
545 static int init_test_sglist(struct test_sglist *tsgl)
546 {
547         return __testmgr_alloc_buf(tsgl->bufs, 1 /* two pages per buffer */);
548 }
549
550 static void destroy_test_sglist(struct test_sglist *tsgl)
551 {
552         return __testmgr_free_buf(tsgl->bufs, 1 /* two pages per buffer */);
553 }
554
555 /**
556  * build_test_sglist() - build a scatterlist for a crypto test
557  *
558  * @tsgl: the scatterlist to build.  @tsgl->bufs[] contains an array of 2-page
559  *        buffers which the scatterlist @tsgl->sgl[] will be made to point into.
560  * @divs: the layout specification on which the scatterlist will be based
561  * @alignmask: the algorithm's alignmask
562  * @total_len: the total length of the scatterlist to build in bytes
563  * @data: if non-NULL, the buffers will be filled with this data until it ends.
564  *        Otherwise the buffers will be poisoned.  In both cases, some bytes
565  *        past the end of each buffer will be poisoned to help detect overruns.
566  * @out_divs: if non-NULL, the test_sg_division to which each scatterlist entry
567  *            corresponds will be returned here.  This will match @divs except
568  *            that divisions resolving to a length of 0 are omitted as they are
569  *            not included in the scatterlist.
570  *
571  * Return: 0 or a -errno value
572  */
573 static int build_test_sglist(struct test_sglist *tsgl,
574                              const struct test_sg_division *divs,
575                              const unsigned int alignmask,
576                              const unsigned int total_len,
577                              struct iov_iter *data,
578                              const struct test_sg_division *out_divs[XBUFSIZE])
579 {
580         struct {
581                 const struct test_sg_division *div;
582                 size_t length;
583         } partitions[XBUFSIZE];
584         const unsigned int ndivs = count_test_sg_divisions(divs);
585         unsigned int len_remaining = total_len;
586         unsigned int i;
587
588         BUILD_BUG_ON(ARRAY_SIZE(partitions) != ARRAY_SIZE(tsgl->sgl));
589         if (WARN_ON(ndivs > ARRAY_SIZE(partitions)))
590                 return -EINVAL;
591
592         /* Calculate the (div, length) pairs */
593         tsgl->nents = 0;
594         for (i = 0; i < ndivs; i++) {
595                 unsigned int len_this_sg =
596                         min(len_remaining,
597                             (total_len * divs[i].proportion_of_total +
598                              TEST_SG_TOTAL / 2) / TEST_SG_TOTAL);
599
600                 if (len_this_sg != 0) {
601                         partitions[tsgl->nents].div = &divs[i];
602                         partitions[tsgl->nents].length = len_this_sg;
603                         tsgl->nents++;
604                         len_remaining -= len_this_sg;
605                 }
606         }
607         if (tsgl->nents == 0) {
608                 partitions[tsgl->nents].div = &divs[0];
609                 partitions[tsgl->nents].length = 0;
610                 tsgl->nents++;
611         }
612         partitions[tsgl->nents - 1].length += len_remaining;
613
614         /* Set up the sgl entries and fill the data or poison */
615         sg_init_table(tsgl->sgl, tsgl->nents);
616         for (i = 0; i < tsgl->nents; i++) {
617                 unsigned int offset = partitions[i].div->offset;
618                 void *addr;
619
620                 if (partitions[i].div->offset_relative_to_alignmask)
621                         offset += alignmask;
622
623                 while (offset + partitions[i].length + TESTMGR_POISON_LEN >
624                        2 * PAGE_SIZE) {
625                         if (WARN_ON(offset <= 0))
626                                 return -EINVAL;
627                         offset /= 2;
628                 }
629
630                 addr = &tsgl->bufs[i][offset];
631                 sg_set_buf(&tsgl->sgl[i], addr, partitions[i].length);
632
633                 if (out_divs)
634                         out_divs[i] = partitions[i].div;
635
636                 if (data) {
637                         size_t copy_len, copied;
638
639                         copy_len = min(partitions[i].length, data->count);
640                         copied = copy_from_iter(addr, copy_len, data);
641                         if (WARN_ON(copied != copy_len))
642                                 return -EINVAL;
643                         testmgr_poison(addr + copy_len, partitions[i].length +
644                                        TESTMGR_POISON_LEN - copy_len);
645                 } else {
646                         testmgr_poison(addr, partitions[i].length +
647                                        TESTMGR_POISON_LEN);
648                 }
649         }
650
651         sg_mark_end(&tsgl->sgl[tsgl->nents - 1]);
652         tsgl->sgl_ptr = tsgl->sgl;
653         memcpy(tsgl->sgl_saved, tsgl->sgl, tsgl->nents * sizeof(tsgl->sgl[0]));
654         return 0;
655 }
656
657 /*
658  * Verify that a scatterlist crypto operation produced the correct output.
659  *
660  * @tsgl: scatterlist containing the actual output
661  * @expected_output: buffer containing the expected output
662  * @len_to_check: length of @expected_output in bytes
663  * @unchecked_prefix_len: number of ignored bytes in @tsgl prior to real result
664  * @check_poison: verify that the poison bytes after each chunk are intact?
665  *
666  * Return: 0 if correct, -EINVAL if incorrect, -EOVERFLOW if buffer overrun.
667  */
668 static int verify_correct_output(const struct test_sglist *tsgl,
669                                  const char *expected_output,
670                                  unsigned int len_to_check,
671                                  unsigned int unchecked_prefix_len,
672                                  bool check_poison)
673 {
674         unsigned int i;
675
676         for (i = 0; i < tsgl->nents; i++) {
677                 struct scatterlist *sg = &tsgl->sgl_ptr[i];
678                 unsigned int len = sg->length;
679                 unsigned int offset = sg->offset;
680                 const char *actual_output;
681
682                 if (unchecked_prefix_len) {
683                         if (unchecked_prefix_len >= len) {
684                                 unchecked_prefix_len -= len;
685                                 continue;
686                         }
687                         offset += unchecked_prefix_len;
688                         len -= unchecked_prefix_len;
689                         unchecked_prefix_len = 0;
690                 }
691                 len = min(len, len_to_check);
692                 actual_output = page_address(sg_page(sg)) + offset;
693                 if (memcmp(expected_output, actual_output, len) != 0)
694                         return -EINVAL;
695                 if (check_poison &&
696                     !testmgr_is_poison(actual_output + len, TESTMGR_POISON_LEN))
697                         return -EOVERFLOW;
698                 len_to_check -= len;
699                 expected_output += len;
700         }
701         if (WARN_ON(len_to_check != 0))
702                 return -EINVAL;
703         return 0;
704 }
705
706 static bool is_test_sglist_corrupted(const struct test_sglist *tsgl)
707 {
708         unsigned int i;
709
710         for (i = 0; i < tsgl->nents; i++) {
711                 if (tsgl->sgl[i].page_link != tsgl->sgl_saved[i].page_link)
712                         return true;
713                 if (tsgl->sgl[i].offset != tsgl->sgl_saved[i].offset)
714                         return true;
715                 if (tsgl->sgl[i].length != tsgl->sgl_saved[i].length)
716                         return true;
717         }
718         return false;
719 }
720
721 struct cipher_test_sglists {
722         struct test_sglist src;
723         struct test_sglist dst;
724 };
725
726 static struct cipher_test_sglists *alloc_cipher_test_sglists(void)
727 {
728         struct cipher_test_sglists *tsgls;
729
730         tsgls = kmalloc(sizeof(*tsgls), GFP_KERNEL);
731         if (!tsgls)
732                 return NULL;
733
734         if (init_test_sglist(&tsgls->src) != 0)
735                 goto fail_kfree;
736         if (init_test_sglist(&tsgls->dst) != 0)
737                 goto fail_destroy_src;
738
739         return tsgls;
740
741 fail_destroy_src:
742         destroy_test_sglist(&tsgls->src);
743 fail_kfree:
744         kfree(tsgls);
745         return NULL;
746 }
747
748 static void free_cipher_test_sglists(struct cipher_test_sglists *tsgls)
749 {
750         if (tsgls) {
751                 destroy_test_sglist(&tsgls->src);
752                 destroy_test_sglist(&tsgls->dst);
753                 kfree(tsgls);
754         }
755 }
756
757 /* Build the src and dst scatterlists for an skcipher or AEAD test */
758 static int build_cipher_test_sglists(struct cipher_test_sglists *tsgls,
759                                      const struct testvec_config *cfg,
760                                      unsigned int alignmask,
761                                      unsigned int src_total_len,
762                                      unsigned int dst_total_len,
763                                      const struct kvec *inputs,
764                                      unsigned int nr_inputs)
765 {
766         struct iov_iter input;
767         int err;
768
769         iov_iter_kvec(&input, ITER_SOURCE, inputs, nr_inputs, src_total_len);
770         err = build_test_sglist(&tsgls->src, cfg->src_divs, alignmask,
771                                 cfg->inplace_mode != OUT_OF_PLACE ?
772                                         max(dst_total_len, src_total_len) :
773                                         src_total_len,
774                                 &input, NULL);
775         if (err)
776                 return err;
777
778         /*
779          * In-place crypto operations can use the same scatterlist for both the
780          * source and destination (req->src == req->dst), or can use separate
781          * scatterlists (req->src != req->dst) which point to the same
782          * underlying memory.  Make sure to test both cases.
783          */
784         if (cfg->inplace_mode == INPLACE_ONE_SGLIST) {
785                 tsgls->dst.sgl_ptr = tsgls->src.sgl;
786                 tsgls->dst.nents = tsgls->src.nents;
787                 return 0;
788         }
789         if (cfg->inplace_mode == INPLACE_TWO_SGLISTS) {
790                 /*
791                  * For now we keep it simple and only test the case where the
792                  * two scatterlists have identical entries, rather than
793                  * different entries that split up the same memory differently.
794                  */
795                 memcpy(tsgls->dst.sgl, tsgls->src.sgl,
796                        tsgls->src.nents * sizeof(tsgls->src.sgl[0]));
797                 memcpy(tsgls->dst.sgl_saved, tsgls->src.sgl,
798                        tsgls->src.nents * sizeof(tsgls->src.sgl[0]));
799                 tsgls->dst.sgl_ptr = tsgls->dst.sgl;
800                 tsgls->dst.nents = tsgls->src.nents;
801                 return 0;
802         }
803         /* Out of place */
804         return build_test_sglist(&tsgls->dst,
805                                  cfg->dst_divs[0].proportion_of_total ?
806                                         cfg->dst_divs : cfg->src_divs,
807                                  alignmask, dst_total_len, NULL, NULL);
808 }
809
810 /*
811  * Support for testing passing a misaligned key to setkey():
812  *
813  * If cfg->key_offset is set, copy the key into a new buffer at that offset,
814  * optionally adding alignmask.  Else, just use the key directly.
815  */
816 static int prepare_keybuf(const u8 *key, unsigned int ksize,
817                           const struct testvec_config *cfg,
818                           unsigned int alignmask,
819                           const u8 **keybuf_ret, const u8 **keyptr_ret)
820 {
821         unsigned int key_offset = cfg->key_offset;
822         u8 *keybuf = NULL, *keyptr = (u8 *)key;
823
824         if (key_offset != 0) {
825                 if (cfg->key_offset_relative_to_alignmask)
826                         key_offset += alignmask;
827                 keybuf = kmalloc(key_offset + ksize, GFP_KERNEL);
828                 if (!keybuf)
829                         return -ENOMEM;
830                 keyptr = keybuf + key_offset;
831                 memcpy(keyptr, key, ksize);
832         }
833         *keybuf_ret = keybuf;
834         *keyptr_ret = keyptr;
835         return 0;
836 }
837
838 /* Like setkey_f(tfm, key, ksize), but sometimes misalign the key */
839 #define do_setkey(setkey_f, tfm, key, ksize, cfg, alignmask)            \
840 ({                                                                      \
841         const u8 *keybuf, *keyptr;                                      \
842         int err;                                                        \
843                                                                         \
844         err = prepare_keybuf((key), (ksize), (cfg), (alignmask),        \
845                              &keybuf, &keyptr);                         \
846         if (err == 0) {                                                 \
847                 err = setkey_f((tfm), keyptr, (ksize));                 \
848                 kfree(keybuf);                                          \
849         }                                                               \
850         err;                                                            \
851 })
852
853 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
854
855 /*
856  * The fuzz tests use prandom instead of the normal Linux RNG since they don't
857  * need cryptographically secure random numbers.  This greatly improves the
858  * performance of these tests, especially if they are run before the Linux RNG
859  * has been initialized or if they are run on a lockdep-enabled kernel.
860  */
861
862 static inline void init_rnd_state(struct rnd_state *rng)
863 {
864         prandom_seed_state(rng, get_random_u64());
865 }
866
867 static inline u8 prandom_u8(struct rnd_state *rng)
868 {
869         return prandom_u32_state(rng);
870 }
871
872 static inline u32 prandom_u32_below(struct rnd_state *rng, u32 ceil)
873 {
874         /*
875          * This is slightly biased for non-power-of-2 values of 'ceil', but this
876          * isn't important here.
877          */
878         return prandom_u32_state(rng) % ceil;
879 }
880
881 static inline bool prandom_bool(struct rnd_state *rng)
882 {
883         return prandom_u32_below(rng, 2);
884 }
885
886 static inline u32 prandom_u32_inclusive(struct rnd_state *rng,
887                                         u32 floor, u32 ceil)
888 {
889         return floor + prandom_u32_below(rng, ceil - floor + 1);
890 }
891
892 /* Generate a random length in range [0, max_len], but prefer smaller values */
893 static unsigned int generate_random_length(struct rnd_state *rng,
894                                            unsigned int max_len)
895 {
896         unsigned int len = prandom_u32_below(rng, max_len + 1);
897
898         switch (prandom_u32_below(rng, 4)) {
899         case 0:
900                 return len % 64;
901         case 1:
902                 return len % 256;
903         case 2:
904                 return len % 1024;
905         default:
906                 return len;
907         }
908 }
909
910 /* Flip a random bit in the given nonempty data buffer */
911 static void flip_random_bit(struct rnd_state *rng, u8 *buf, size_t size)
912 {
913         size_t bitpos;
914
915         bitpos = prandom_u32_below(rng, size * 8);
916         buf[bitpos / 8] ^= 1 << (bitpos % 8);
917 }
918
919 /* Flip a random byte in the given nonempty data buffer */
920 static void flip_random_byte(struct rnd_state *rng, u8 *buf, size_t size)
921 {
922         buf[prandom_u32_below(rng, size)] ^= 0xff;
923 }
924
925 /* Sometimes make some random changes to the given nonempty data buffer */
926 static void mutate_buffer(struct rnd_state *rng, u8 *buf, size_t size)
927 {
928         size_t num_flips;
929         size_t i;
930
931         /* Sometimes flip some bits */
932         if (prandom_u32_below(rng, 4) == 0) {
933                 num_flips = min_t(size_t, 1 << prandom_u32_below(rng, 8),
934                                   size * 8);
935                 for (i = 0; i < num_flips; i++)
936                         flip_random_bit(rng, buf, size);
937         }
938
939         /* Sometimes flip some bytes */
940         if (prandom_u32_below(rng, 4) == 0) {
941                 num_flips = min_t(size_t, 1 << prandom_u32_below(rng, 8), size);
942                 for (i = 0; i < num_flips; i++)
943                         flip_random_byte(rng, buf, size);
944         }
945 }
946
947 /* Randomly generate 'count' bytes, but sometimes make them "interesting" */
948 static void generate_random_bytes(struct rnd_state *rng, u8 *buf, size_t count)
949 {
950         u8 b;
951         u8 increment;
952         size_t i;
953
954         if (count == 0)
955                 return;
956
957         switch (prandom_u32_below(rng, 8)) { /* Choose a generation strategy */
958         case 0:
959         case 1:
960                 /* All the same byte, plus optional mutations */
961                 switch (prandom_u32_below(rng, 4)) {
962                 case 0:
963                         b = 0x00;
964                         break;
965                 case 1:
966                         b = 0xff;
967                         break;
968                 default:
969                         b = prandom_u8(rng);
970                         break;
971                 }
972                 memset(buf, b, count);
973                 mutate_buffer(rng, buf, count);
974                 break;
975         case 2:
976                 /* Ascending or descending bytes, plus optional mutations */
977                 increment = prandom_u8(rng);
978                 b = prandom_u8(rng);
979                 for (i = 0; i < count; i++, b += increment)
980                         buf[i] = b;
981                 mutate_buffer(rng, buf, count);
982                 break;
983         default:
984                 /* Fully random bytes */
985                 prandom_bytes_state(rng, buf, count);
986         }
987 }
988
989 static char *generate_random_sgl_divisions(struct rnd_state *rng,
990                                            struct test_sg_division *divs,
991                                            size_t max_divs, char *p, char *end,
992                                            bool gen_flushes, u32 req_flags)
993 {
994         struct test_sg_division *div = divs;
995         unsigned int remaining = TEST_SG_TOTAL;
996
997         do {
998                 unsigned int this_len;
999                 const char *flushtype_str;
1000
1001                 if (div == &divs[max_divs - 1] || prandom_bool(rng))
1002                         this_len = remaining;
1003                 else
1004                         this_len = prandom_u32_inclusive(rng, 1, remaining);
1005                 div->proportion_of_total = this_len;
1006
1007                 if (prandom_u32_below(rng, 4) == 0)
1008                         div->offset = prandom_u32_inclusive(rng,
1009                                                             PAGE_SIZE - 128,
1010                                                             PAGE_SIZE - 1);
1011                 else if (prandom_bool(rng))
1012                         div->offset = prandom_u32_below(rng, 32);
1013                 else
1014                         div->offset = prandom_u32_below(rng, PAGE_SIZE);
1015                 if (prandom_u32_below(rng, 8) == 0)
1016                         div->offset_relative_to_alignmask = true;
1017
1018                 div->flush_type = FLUSH_TYPE_NONE;
1019                 if (gen_flushes) {
1020                         switch (prandom_u32_below(rng, 4)) {
1021                         case 0:
1022                                 div->flush_type = FLUSH_TYPE_REIMPORT;
1023                                 break;
1024                         case 1:
1025                                 div->flush_type = FLUSH_TYPE_FLUSH;
1026                                 break;
1027                         }
1028                 }
1029
1030                 if (div->flush_type != FLUSH_TYPE_NONE &&
1031                     !(req_flags & CRYPTO_TFM_REQ_MAY_SLEEP) &&
1032                     prandom_bool(rng))
1033                         div->nosimd = true;
1034
1035                 switch (div->flush_type) {
1036                 case FLUSH_TYPE_FLUSH:
1037                         if (div->nosimd)
1038                                 flushtype_str = "<flush,nosimd>";
1039                         else
1040                                 flushtype_str = "<flush>";
1041                         break;
1042                 case FLUSH_TYPE_REIMPORT:
1043                         if (div->nosimd)
1044                                 flushtype_str = "<reimport,nosimd>";
1045                         else
1046                                 flushtype_str = "<reimport>";
1047                         break;
1048                 default:
1049                         flushtype_str = "";
1050                         break;
1051                 }
1052
1053                 BUILD_BUG_ON(TEST_SG_TOTAL != 10000); /* for "%u.%u%%" */
1054                 p += scnprintf(p, end - p, "%s%u.%u%%@%s+%u%s", flushtype_str,
1055                                this_len / 100, this_len % 100,
1056                                div->offset_relative_to_alignmask ?
1057                                         "alignmask" : "",
1058                                div->offset, this_len == remaining ? "" : ", ");
1059                 remaining -= this_len;
1060                 div++;
1061         } while (remaining);
1062
1063         return p;
1064 }
1065
1066 /* Generate a random testvec_config for fuzz testing */
1067 static void generate_random_testvec_config(struct rnd_state *rng,
1068                                            struct testvec_config *cfg,
1069                                            char *name, size_t max_namelen)
1070 {
1071         char *p = name;
1072         char * const end = name + max_namelen;
1073
1074         memset(cfg, 0, sizeof(*cfg));
1075
1076         cfg->name = name;
1077
1078         p += scnprintf(p, end - p, "random:");
1079
1080         switch (prandom_u32_below(rng, 4)) {
1081         case 0:
1082         case 1:
1083                 cfg->inplace_mode = OUT_OF_PLACE;
1084                 break;
1085         case 2:
1086                 cfg->inplace_mode = INPLACE_ONE_SGLIST;
1087                 p += scnprintf(p, end - p, " inplace_one_sglist");
1088                 break;
1089         default:
1090                 cfg->inplace_mode = INPLACE_TWO_SGLISTS;
1091                 p += scnprintf(p, end - p, " inplace_two_sglists");
1092                 break;
1093         }
1094
1095         if (prandom_bool(rng)) {
1096                 cfg->req_flags |= CRYPTO_TFM_REQ_MAY_SLEEP;
1097                 p += scnprintf(p, end - p, " may_sleep");
1098         }
1099
1100         switch (prandom_u32_below(rng, 4)) {
1101         case 0:
1102                 cfg->finalization_type = FINALIZATION_TYPE_FINAL;
1103                 p += scnprintf(p, end - p, " use_final");
1104                 break;
1105         case 1:
1106                 cfg->finalization_type = FINALIZATION_TYPE_FINUP;
1107                 p += scnprintf(p, end - p, " use_finup");
1108                 break;
1109         default:
1110                 cfg->finalization_type = FINALIZATION_TYPE_DIGEST;
1111                 p += scnprintf(p, end - p, " use_digest");
1112                 break;
1113         }
1114
1115         if (!(cfg->req_flags & CRYPTO_TFM_REQ_MAY_SLEEP) && prandom_bool(rng)) {
1116                 cfg->nosimd = true;
1117                 p += scnprintf(p, end - p, " nosimd");
1118         }
1119
1120         p += scnprintf(p, end - p, " src_divs=[");
1121         p = generate_random_sgl_divisions(rng, cfg->src_divs,
1122                                           ARRAY_SIZE(cfg->src_divs), p, end,
1123                                           (cfg->finalization_type !=
1124                                            FINALIZATION_TYPE_DIGEST),
1125                                           cfg->req_flags);
1126         p += scnprintf(p, end - p, "]");
1127
1128         if (cfg->inplace_mode == OUT_OF_PLACE && prandom_bool(rng)) {
1129                 p += scnprintf(p, end - p, " dst_divs=[");
1130                 p = generate_random_sgl_divisions(rng, cfg->dst_divs,
1131                                                   ARRAY_SIZE(cfg->dst_divs),
1132                                                   p, end, false,
1133                                                   cfg->req_flags);
1134                 p += scnprintf(p, end - p, "]");
1135         }
1136
1137         if (prandom_bool(rng)) {
1138                 cfg->iv_offset = prandom_u32_inclusive(rng, 1,
1139                                                        MAX_ALGAPI_ALIGNMASK);
1140                 p += scnprintf(p, end - p, " iv_offset=%u", cfg->iv_offset);
1141         }
1142
1143         if (prandom_bool(rng)) {
1144                 cfg->key_offset = prandom_u32_inclusive(rng, 1,
1145                                                         MAX_ALGAPI_ALIGNMASK);
1146                 p += scnprintf(p, end - p, " key_offset=%u", cfg->key_offset);
1147         }
1148
1149         WARN_ON_ONCE(!valid_testvec_config(cfg));
1150 }
1151
1152 static void crypto_disable_simd_for_test(void)
1153 {
1154         migrate_disable();
1155         __this_cpu_write(crypto_simd_disabled_for_test, true);
1156 }
1157
1158 static void crypto_reenable_simd_for_test(void)
1159 {
1160         __this_cpu_write(crypto_simd_disabled_for_test, false);
1161         migrate_enable();
1162 }
1163
1164 /*
1165  * Given an algorithm name, build the name of the generic implementation of that
1166  * algorithm, assuming the usual naming convention.  Specifically, this appends
1167  * "-generic" to every part of the name that is not a template name.  Examples:
1168  *
1169  *      aes => aes-generic
1170  *      cbc(aes) => cbc(aes-generic)
1171  *      cts(cbc(aes)) => cts(cbc(aes-generic))
1172  *      rfc7539(chacha20,poly1305) => rfc7539(chacha20-generic,poly1305-generic)
1173  *
1174  * Return: 0 on success, or -ENAMETOOLONG if the generic name would be too long
1175  */
1176 static int build_generic_driver_name(const char *algname,
1177                                      char driver_name[CRYPTO_MAX_ALG_NAME])
1178 {
1179         const char *in = algname;
1180         char *out = driver_name;
1181         size_t len = strlen(algname);
1182
1183         if (len >= CRYPTO_MAX_ALG_NAME)
1184                 goto too_long;
1185         do {
1186                 const char *in_saved = in;
1187
1188                 while (*in && *in != '(' && *in != ')' && *in != ',')
1189                         *out++ = *in++;
1190                 if (*in != '(' && in > in_saved) {
1191                         len += 8;
1192                         if (len >= CRYPTO_MAX_ALG_NAME)
1193                                 goto too_long;
1194                         memcpy(out, "-generic", 8);
1195                         out += 8;
1196                 }
1197         } while ((*out++ = *in++) != '\0');
1198         return 0;
1199
1200 too_long:
1201         pr_err("alg: generic driver name for \"%s\" would be too long\n",
1202                algname);
1203         return -ENAMETOOLONG;
1204 }
1205 #else /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
1206 static void crypto_disable_simd_for_test(void)
1207 {
1208 }
1209
1210 static void crypto_reenable_simd_for_test(void)
1211 {
1212 }
1213 #endif /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
1214
1215 static int build_hash_sglist(struct test_sglist *tsgl,
1216                              const struct hash_testvec *vec,
1217                              const struct testvec_config *cfg,
1218                              unsigned int alignmask,
1219                              const struct test_sg_division *divs[XBUFSIZE])
1220 {
1221         struct kvec kv;
1222         struct iov_iter input;
1223
1224         kv.iov_base = (void *)vec->plaintext;
1225         kv.iov_len = vec->psize;
1226         iov_iter_kvec(&input, ITER_SOURCE, &kv, 1, vec->psize);
1227         return build_test_sglist(tsgl, cfg->src_divs, alignmask, vec->psize,
1228                                  &input, divs);
1229 }
1230
1231 static int check_hash_result(const char *type,
1232                              const u8 *result, unsigned int digestsize,
1233                              const struct hash_testvec *vec,
1234                              const char *vec_name,
1235                              const char *driver,
1236                              const struct testvec_config *cfg)
1237 {
1238         if (memcmp(result, vec->digest, digestsize) != 0) {
1239                 pr_err("alg: %s: %s test failed (wrong result) on test vector %s, cfg=\"%s\"\n",
1240                        type, driver, vec_name, cfg->name);
1241                 return -EINVAL;
1242         }
1243         if (!testmgr_is_poison(&result[digestsize], TESTMGR_POISON_LEN)) {
1244                 pr_err("alg: %s: %s overran result buffer on test vector %s, cfg=\"%s\"\n",
1245                        type, driver, vec_name, cfg->name);
1246                 return -EOVERFLOW;
1247         }
1248         return 0;
1249 }
1250
1251 static inline int check_shash_op(const char *op, int err,
1252                                  const char *driver, const char *vec_name,
1253                                  const struct testvec_config *cfg)
1254 {
1255         if (err)
1256                 pr_err("alg: shash: %s %s() failed with err %d on test vector %s, cfg=\"%s\"\n",
1257                        driver, op, err, vec_name, cfg->name);
1258         return err;
1259 }
1260
1261 /* Test one hash test vector in one configuration, using the shash API */
1262 static int test_shash_vec_cfg(const struct hash_testvec *vec,
1263                               const char *vec_name,
1264                               const struct testvec_config *cfg,
1265                               struct shash_desc *desc,
1266                               struct test_sglist *tsgl,
1267                               u8 *hashstate)
1268 {
1269         struct crypto_shash *tfm = desc->tfm;
1270         const unsigned int alignmask = crypto_shash_alignmask(tfm);
1271         const unsigned int digestsize = crypto_shash_digestsize(tfm);
1272         const unsigned int statesize = crypto_shash_statesize(tfm);
1273         const char *driver = crypto_shash_driver_name(tfm);
1274         const struct test_sg_division *divs[XBUFSIZE];
1275         unsigned int i;
1276         u8 result[HASH_MAX_DIGESTSIZE + TESTMGR_POISON_LEN];
1277         int err;
1278
1279         /* Set the key, if specified */
1280         if (vec->ksize) {
1281                 err = do_setkey(crypto_shash_setkey, tfm, vec->key, vec->ksize,
1282                                 cfg, alignmask);
1283                 if (err) {
1284                         if (err == vec->setkey_error)
1285                                 return 0;
1286                         pr_err("alg: shash: %s setkey failed on test vector %s; expected_error=%d, actual_error=%d, flags=%#x\n",
1287                                driver, vec_name, vec->setkey_error, err,
1288                                crypto_shash_get_flags(tfm));
1289                         return err;
1290                 }
1291                 if (vec->setkey_error) {
1292                         pr_err("alg: shash: %s setkey unexpectedly succeeded on test vector %s; expected_error=%d\n",
1293                                driver, vec_name, vec->setkey_error);
1294                         return -EINVAL;
1295                 }
1296         }
1297
1298         /* Build the scatterlist for the source data */
1299         err = build_hash_sglist(tsgl, vec, cfg, alignmask, divs);
1300         if (err) {
1301                 pr_err("alg: shash: %s: error preparing scatterlist for test vector %s, cfg=\"%s\"\n",
1302                        driver, vec_name, cfg->name);
1303                 return err;
1304         }
1305
1306         /* Do the actual hashing */
1307
1308         testmgr_poison(desc->__ctx, crypto_shash_descsize(tfm));
1309         testmgr_poison(result, digestsize + TESTMGR_POISON_LEN);
1310
1311         if (cfg->finalization_type == FINALIZATION_TYPE_DIGEST ||
1312             vec->digest_error) {
1313                 /* Just using digest() */
1314                 if (tsgl->nents != 1)
1315                         return 0;
1316                 if (cfg->nosimd)
1317                         crypto_disable_simd_for_test();
1318                 err = crypto_shash_digest(desc, sg_virt(&tsgl->sgl[0]),
1319                                           tsgl->sgl[0].length, result);
1320                 if (cfg->nosimd)
1321                         crypto_reenable_simd_for_test();
1322                 if (err) {
1323                         if (err == vec->digest_error)
1324                                 return 0;
1325                         pr_err("alg: shash: %s digest() failed on test vector %s; expected_error=%d, actual_error=%d, cfg=\"%s\"\n",
1326                                driver, vec_name, vec->digest_error, err,
1327                                cfg->name);
1328                         return err;
1329                 }
1330                 if (vec->digest_error) {
1331                         pr_err("alg: shash: %s digest() unexpectedly succeeded on test vector %s; expected_error=%d, cfg=\"%s\"\n",
1332                                driver, vec_name, vec->digest_error, cfg->name);
1333                         return -EINVAL;
1334                 }
1335                 goto result_ready;
1336         }
1337
1338         /* Using init(), zero or more update(), then final() or finup() */
1339
1340         if (cfg->nosimd)
1341                 crypto_disable_simd_for_test();
1342         err = crypto_shash_init(desc);
1343         if (cfg->nosimd)
1344                 crypto_reenable_simd_for_test();
1345         err = check_shash_op("init", err, driver, vec_name, cfg);
1346         if (err)
1347                 return err;
1348
1349         for (i = 0; i < tsgl->nents; i++) {
1350                 if (i + 1 == tsgl->nents &&
1351                     cfg->finalization_type == FINALIZATION_TYPE_FINUP) {
1352                         if (divs[i]->nosimd)
1353                                 crypto_disable_simd_for_test();
1354                         err = crypto_shash_finup(desc, sg_virt(&tsgl->sgl[i]),
1355                                                  tsgl->sgl[i].length, result);
1356                         if (divs[i]->nosimd)
1357                                 crypto_reenable_simd_for_test();
1358                         err = check_shash_op("finup", err, driver, vec_name,
1359                                              cfg);
1360                         if (err)
1361                                 return err;
1362                         goto result_ready;
1363                 }
1364                 if (divs[i]->nosimd)
1365                         crypto_disable_simd_for_test();
1366                 err = crypto_shash_update(desc, sg_virt(&tsgl->sgl[i]),
1367                                           tsgl->sgl[i].length);
1368                 if (divs[i]->nosimd)
1369                         crypto_reenable_simd_for_test();
1370                 err = check_shash_op("update", err, driver, vec_name, cfg);
1371                 if (err)
1372                         return err;
1373                 if (divs[i]->flush_type == FLUSH_TYPE_REIMPORT) {
1374                         /* Test ->export() and ->import() */
1375                         testmgr_poison(hashstate + statesize,
1376                                        TESTMGR_POISON_LEN);
1377                         err = crypto_shash_export(desc, hashstate);
1378                         err = check_shash_op("export", err, driver, vec_name,
1379                                              cfg);
1380                         if (err)
1381                                 return err;
1382                         if (!testmgr_is_poison(hashstate + statesize,
1383                                                TESTMGR_POISON_LEN)) {
1384                                 pr_err("alg: shash: %s export() overran state buffer on test vector %s, cfg=\"%s\"\n",
1385                                        driver, vec_name, cfg->name);
1386                                 return -EOVERFLOW;
1387                         }
1388                         testmgr_poison(desc->__ctx, crypto_shash_descsize(tfm));
1389                         err = crypto_shash_import(desc, hashstate);
1390                         err = check_shash_op("import", err, driver, vec_name,
1391                                              cfg);
1392                         if (err)
1393                                 return err;
1394                 }
1395         }
1396
1397         if (cfg->nosimd)
1398                 crypto_disable_simd_for_test();
1399         err = crypto_shash_final(desc, result);
1400         if (cfg->nosimd)
1401                 crypto_reenable_simd_for_test();
1402         err = check_shash_op("final", err, driver, vec_name, cfg);
1403         if (err)
1404                 return err;
1405 result_ready:
1406         return check_hash_result("shash", result, digestsize, vec, vec_name,
1407                                  driver, cfg);
1408 }
1409
1410 static int do_ahash_op(int (*op)(struct ahash_request *req),
1411                        struct ahash_request *req,
1412                        struct crypto_wait *wait, bool nosimd)
1413 {
1414         int err;
1415
1416         if (nosimd)
1417                 crypto_disable_simd_for_test();
1418
1419         err = op(req);
1420
1421         if (nosimd)
1422                 crypto_reenable_simd_for_test();
1423
1424         return crypto_wait_req(err, wait);
1425 }
1426
1427 static int check_nonfinal_ahash_op(const char *op, int err,
1428                                    u8 *result, unsigned int digestsize,
1429                                    const char *driver, const char *vec_name,
1430                                    const struct testvec_config *cfg)
1431 {
1432         if (err) {
1433                 pr_err("alg: ahash: %s %s() failed with err %d on test vector %s, cfg=\"%s\"\n",
1434                        driver, op, err, vec_name, cfg->name);
1435                 return err;
1436         }
1437         if (!testmgr_is_poison(result, digestsize)) {
1438                 pr_err("alg: ahash: %s %s() used result buffer on test vector %s, cfg=\"%s\"\n",
1439                        driver, op, vec_name, cfg->name);
1440                 return -EINVAL;
1441         }
1442         return 0;
1443 }
1444
1445 /* Test one hash test vector in one configuration, using the ahash API */
1446 static int test_ahash_vec_cfg(const struct hash_testvec *vec,
1447                               const char *vec_name,
1448                               const struct testvec_config *cfg,
1449                               struct ahash_request *req,
1450                               struct test_sglist *tsgl,
1451                               u8 *hashstate)
1452 {
1453         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1454         const unsigned int alignmask = crypto_ahash_alignmask(tfm);
1455         const unsigned int digestsize = crypto_ahash_digestsize(tfm);
1456         const unsigned int statesize = crypto_ahash_statesize(tfm);
1457         const char *driver = crypto_ahash_driver_name(tfm);
1458         const u32 req_flags = CRYPTO_TFM_REQ_MAY_BACKLOG | cfg->req_flags;
1459         const struct test_sg_division *divs[XBUFSIZE];
1460         DECLARE_CRYPTO_WAIT(wait);
1461         unsigned int i;
1462         struct scatterlist *pending_sgl;
1463         unsigned int pending_len;
1464         u8 result[HASH_MAX_DIGESTSIZE + TESTMGR_POISON_LEN];
1465         int err;
1466
1467         /* Set the key, if specified */
1468         if (vec->ksize) {
1469                 err = do_setkey(crypto_ahash_setkey, tfm, vec->key, vec->ksize,
1470                                 cfg, alignmask);
1471                 if (err) {
1472                         if (err == vec->setkey_error)
1473                                 return 0;
1474                         pr_err("alg: ahash: %s setkey failed on test vector %s; expected_error=%d, actual_error=%d, flags=%#x\n",
1475                                driver, vec_name, vec->setkey_error, err,
1476                                crypto_ahash_get_flags(tfm));
1477                         return err;
1478                 }
1479                 if (vec->setkey_error) {
1480                         pr_err("alg: ahash: %s setkey unexpectedly succeeded on test vector %s; expected_error=%d\n",
1481                                driver, vec_name, vec->setkey_error);
1482                         return -EINVAL;
1483                 }
1484         }
1485
1486         /* Build the scatterlist for the source data */
1487         err = build_hash_sglist(tsgl, vec, cfg, alignmask, divs);
1488         if (err) {
1489                 pr_err("alg: ahash: %s: error preparing scatterlist for test vector %s, cfg=\"%s\"\n",
1490                        driver, vec_name, cfg->name);
1491                 return err;
1492         }
1493
1494         /* Do the actual hashing */
1495
1496         testmgr_poison(req->__ctx, crypto_ahash_reqsize(tfm));
1497         testmgr_poison(result, digestsize + TESTMGR_POISON_LEN);
1498
1499         if (cfg->finalization_type == FINALIZATION_TYPE_DIGEST ||
1500             vec->digest_error) {
1501                 /* Just using digest() */
1502                 ahash_request_set_callback(req, req_flags, crypto_req_done,
1503                                            &wait);
1504                 ahash_request_set_crypt(req, tsgl->sgl, result, vec->psize);
1505                 err = do_ahash_op(crypto_ahash_digest, req, &wait, cfg->nosimd);
1506                 if (err) {
1507                         if (err == vec->digest_error)
1508                                 return 0;
1509                         pr_err("alg: ahash: %s digest() failed on test vector %s; expected_error=%d, actual_error=%d, cfg=\"%s\"\n",
1510                                driver, vec_name, vec->digest_error, err,
1511                                cfg->name);
1512                         return err;
1513                 }
1514                 if (vec->digest_error) {
1515                         pr_err("alg: ahash: %s digest() unexpectedly succeeded on test vector %s; expected_error=%d, cfg=\"%s\"\n",
1516                                driver, vec_name, vec->digest_error, cfg->name);
1517                         return -EINVAL;
1518                 }
1519                 goto result_ready;
1520         }
1521
1522         /* Using init(), zero or more update(), then final() or finup() */
1523
1524         ahash_request_set_callback(req, req_flags, crypto_req_done, &wait);
1525         ahash_request_set_crypt(req, NULL, result, 0);
1526         err = do_ahash_op(crypto_ahash_init, req, &wait, cfg->nosimd);
1527         err = check_nonfinal_ahash_op("init", err, result, digestsize,
1528                                       driver, vec_name, cfg);
1529         if (err)
1530                 return err;
1531
1532         pending_sgl = NULL;
1533         pending_len = 0;
1534         for (i = 0; i < tsgl->nents; i++) {
1535                 if (divs[i]->flush_type != FLUSH_TYPE_NONE &&
1536                     pending_sgl != NULL) {
1537                         /* update() with the pending data */
1538                         ahash_request_set_callback(req, req_flags,
1539                                                    crypto_req_done, &wait);
1540                         ahash_request_set_crypt(req, pending_sgl, result,
1541                                                 pending_len);
1542                         err = do_ahash_op(crypto_ahash_update, req, &wait,
1543                                           divs[i]->nosimd);
1544                         err = check_nonfinal_ahash_op("update", err,
1545                                                       result, digestsize,
1546                                                       driver, vec_name, cfg);
1547                         if (err)
1548                                 return err;
1549                         pending_sgl = NULL;
1550                         pending_len = 0;
1551                 }
1552                 if (divs[i]->flush_type == FLUSH_TYPE_REIMPORT) {
1553                         /* Test ->export() and ->import() */
1554                         testmgr_poison(hashstate + statesize,
1555                                        TESTMGR_POISON_LEN);
1556                         err = crypto_ahash_export(req, hashstate);
1557                         err = check_nonfinal_ahash_op("export", err,
1558                                                       result, digestsize,
1559                                                       driver, vec_name, cfg);
1560                         if (err)
1561                                 return err;
1562                         if (!testmgr_is_poison(hashstate + statesize,
1563                                                TESTMGR_POISON_LEN)) {
1564                                 pr_err("alg: ahash: %s export() overran state buffer on test vector %s, cfg=\"%s\"\n",
1565                                        driver, vec_name, cfg->name);
1566                                 return -EOVERFLOW;
1567                         }
1568
1569                         testmgr_poison(req->__ctx, crypto_ahash_reqsize(tfm));
1570                         err = crypto_ahash_import(req, hashstate);
1571                         err = check_nonfinal_ahash_op("import", err,
1572                                                       result, digestsize,
1573                                                       driver, vec_name, cfg);
1574                         if (err)
1575                                 return err;
1576                 }
1577                 if (pending_sgl == NULL)
1578                         pending_sgl = &tsgl->sgl[i];
1579                 pending_len += tsgl->sgl[i].length;
1580         }
1581
1582         ahash_request_set_callback(req, req_flags, crypto_req_done, &wait);
1583         ahash_request_set_crypt(req, pending_sgl, result, pending_len);
1584         if (cfg->finalization_type == FINALIZATION_TYPE_FINAL) {
1585                 /* finish with update() and final() */
1586                 err = do_ahash_op(crypto_ahash_update, req, &wait, cfg->nosimd);
1587                 err = check_nonfinal_ahash_op("update", err, result, digestsize,
1588                                               driver, vec_name, cfg);
1589                 if (err)
1590                         return err;
1591                 err = do_ahash_op(crypto_ahash_final, req, &wait, cfg->nosimd);
1592                 if (err) {
1593                         pr_err("alg: ahash: %s final() failed with err %d on test vector %s, cfg=\"%s\"\n",
1594                                driver, err, vec_name, cfg->name);
1595                         return err;
1596                 }
1597         } else {
1598                 /* finish with finup() */
1599                 err = do_ahash_op(crypto_ahash_finup, req, &wait, cfg->nosimd);
1600                 if (err) {
1601                         pr_err("alg: ahash: %s finup() failed with err %d on test vector %s, cfg=\"%s\"\n",
1602                                driver, err, vec_name, cfg->name);
1603                         return err;
1604                 }
1605         }
1606
1607 result_ready:
1608         return check_hash_result("ahash", result, digestsize, vec, vec_name,
1609                                  driver, cfg);
1610 }
1611
1612 static int test_hash_vec_cfg(const struct hash_testvec *vec,
1613                              const char *vec_name,
1614                              const struct testvec_config *cfg,
1615                              struct ahash_request *req,
1616                              struct shash_desc *desc,
1617                              struct test_sglist *tsgl,
1618                              u8 *hashstate)
1619 {
1620         int err;
1621
1622         /*
1623          * For algorithms implemented as "shash", most bugs will be detected by
1624          * both the shash and ahash tests.  Test the shash API first so that the
1625          * failures involve less indirection, so are easier to debug.
1626          */
1627
1628         if (desc) {
1629                 err = test_shash_vec_cfg(vec, vec_name, cfg, desc, tsgl,
1630                                          hashstate);
1631                 if (err)
1632                         return err;
1633         }
1634
1635         return test_ahash_vec_cfg(vec, vec_name, cfg, req, tsgl, hashstate);
1636 }
1637
1638 static int test_hash_vec(const struct hash_testvec *vec, unsigned int vec_num,
1639                          struct ahash_request *req, struct shash_desc *desc,
1640                          struct test_sglist *tsgl, u8 *hashstate)
1641 {
1642         char vec_name[16];
1643         unsigned int i;
1644         int err;
1645
1646         sprintf(vec_name, "%u", vec_num);
1647
1648         for (i = 0; i < ARRAY_SIZE(default_hash_testvec_configs); i++) {
1649                 err = test_hash_vec_cfg(vec, vec_name,
1650                                         &default_hash_testvec_configs[i],
1651                                         req, desc, tsgl, hashstate);
1652                 if (err)
1653                         return err;
1654         }
1655
1656 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
1657         if (!noextratests) {
1658                 struct rnd_state rng;
1659                 struct testvec_config cfg;
1660                 char cfgname[TESTVEC_CONFIG_NAMELEN];
1661
1662                 init_rnd_state(&rng);
1663
1664                 for (i = 0; i < fuzz_iterations; i++) {
1665                         generate_random_testvec_config(&rng, &cfg, cfgname,
1666                                                        sizeof(cfgname));
1667                         err = test_hash_vec_cfg(vec, vec_name, &cfg,
1668                                                 req, desc, tsgl, hashstate);
1669                         if (err)
1670                                 return err;
1671                         cond_resched();
1672                 }
1673         }
1674 #endif
1675         return 0;
1676 }
1677
1678 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
1679 /*
1680  * Generate a hash test vector from the given implementation.
1681  * Assumes the buffers in 'vec' were already allocated.
1682  */
1683 static void generate_random_hash_testvec(struct rnd_state *rng,
1684                                          struct shash_desc *desc,
1685                                          struct hash_testvec *vec,
1686                                          unsigned int maxkeysize,
1687                                          unsigned int maxdatasize,
1688                                          char *name, size_t max_namelen)
1689 {
1690         /* Data */
1691         vec->psize = generate_random_length(rng, maxdatasize);
1692         generate_random_bytes(rng, (u8 *)vec->plaintext, vec->psize);
1693
1694         /*
1695          * Key: length in range [1, maxkeysize], but usually choose maxkeysize.
1696          * If algorithm is unkeyed, then maxkeysize == 0 and set ksize = 0.
1697          */
1698         vec->setkey_error = 0;
1699         vec->ksize = 0;
1700         if (maxkeysize) {
1701                 vec->ksize = maxkeysize;
1702                 if (prandom_u32_below(rng, 4) == 0)
1703                         vec->ksize = prandom_u32_inclusive(rng, 1, maxkeysize);
1704                 generate_random_bytes(rng, (u8 *)vec->key, vec->ksize);
1705
1706                 vec->setkey_error = crypto_shash_setkey(desc->tfm, vec->key,
1707                                                         vec->ksize);
1708                 /* If the key couldn't be set, no need to continue to digest. */
1709                 if (vec->setkey_error)
1710                         goto done;
1711         }
1712
1713         /* Digest */
1714         vec->digest_error = crypto_shash_digest(desc, vec->plaintext,
1715                                                 vec->psize, (u8 *)vec->digest);
1716 done:
1717         snprintf(name, max_namelen, "\"random: psize=%u ksize=%u\"",
1718                  vec->psize, vec->ksize);
1719 }
1720
1721 /*
1722  * Test the hash algorithm represented by @req against the corresponding generic
1723  * implementation, if one is available.
1724  */
1725 static int test_hash_vs_generic_impl(const char *generic_driver,
1726                                      unsigned int maxkeysize,
1727                                      struct ahash_request *req,
1728                                      struct shash_desc *desc,
1729                                      struct test_sglist *tsgl,
1730                                      u8 *hashstate)
1731 {
1732         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1733         const unsigned int digestsize = crypto_ahash_digestsize(tfm);
1734         const unsigned int blocksize = crypto_ahash_blocksize(tfm);
1735         const unsigned int maxdatasize = (2 * PAGE_SIZE) - TESTMGR_POISON_LEN;
1736         const char *algname = crypto_hash_alg_common(tfm)->base.cra_name;
1737         const char *driver = crypto_ahash_driver_name(tfm);
1738         struct rnd_state rng;
1739         char _generic_driver[CRYPTO_MAX_ALG_NAME];
1740         struct crypto_shash *generic_tfm = NULL;
1741         struct shash_desc *generic_desc = NULL;
1742         unsigned int i;
1743         struct hash_testvec vec = { 0 };
1744         char vec_name[64];
1745         struct testvec_config *cfg;
1746         char cfgname[TESTVEC_CONFIG_NAMELEN];
1747         int err;
1748
1749         if (noextratests)
1750                 return 0;
1751
1752         init_rnd_state(&rng);
1753
1754         if (!generic_driver) { /* Use default naming convention? */
1755                 err = build_generic_driver_name(algname, _generic_driver);
1756                 if (err)
1757                         return err;
1758                 generic_driver = _generic_driver;
1759         }
1760
1761         if (strcmp(generic_driver, driver) == 0) /* Already the generic impl? */
1762                 return 0;
1763
1764         generic_tfm = crypto_alloc_shash(generic_driver, 0, 0);
1765         if (IS_ERR(generic_tfm)) {
1766                 err = PTR_ERR(generic_tfm);
1767                 if (err == -ENOENT) {
1768                         pr_warn("alg: hash: skipping comparison tests for %s because %s is unavailable\n",
1769                                 driver, generic_driver);
1770                         return 0;
1771                 }
1772                 pr_err("alg: hash: error allocating %s (generic impl of %s): %d\n",
1773                        generic_driver, algname, err);
1774                 return err;
1775         }
1776
1777         cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
1778         if (!cfg) {
1779                 err = -ENOMEM;
1780                 goto out;
1781         }
1782
1783         generic_desc = kzalloc(sizeof(*desc) +
1784                                crypto_shash_descsize(generic_tfm), GFP_KERNEL);
1785         if (!generic_desc) {
1786                 err = -ENOMEM;
1787                 goto out;
1788         }
1789         generic_desc->tfm = generic_tfm;
1790
1791         /* Check the algorithm properties for consistency. */
1792
1793         if (digestsize != crypto_shash_digestsize(generic_tfm)) {
1794                 pr_err("alg: hash: digestsize for %s (%u) doesn't match generic impl (%u)\n",
1795                        driver, digestsize,
1796                        crypto_shash_digestsize(generic_tfm));
1797                 err = -EINVAL;
1798                 goto out;
1799         }
1800
1801         if (blocksize != crypto_shash_blocksize(generic_tfm)) {
1802                 pr_err("alg: hash: blocksize for %s (%u) doesn't match generic impl (%u)\n",
1803                        driver, blocksize, crypto_shash_blocksize(generic_tfm));
1804                 err = -EINVAL;
1805                 goto out;
1806         }
1807
1808         /*
1809          * Now generate test vectors using the generic implementation, and test
1810          * the other implementation against them.
1811          */
1812
1813         vec.key = kmalloc(maxkeysize, GFP_KERNEL);
1814         vec.plaintext = kmalloc(maxdatasize, GFP_KERNEL);
1815         vec.digest = kmalloc(digestsize, GFP_KERNEL);
1816         if (!vec.key || !vec.plaintext || !vec.digest) {
1817                 err = -ENOMEM;
1818                 goto out;
1819         }
1820
1821         for (i = 0; i < fuzz_iterations * 8; i++) {
1822                 generate_random_hash_testvec(&rng, generic_desc, &vec,
1823                                              maxkeysize, maxdatasize,
1824                                              vec_name, sizeof(vec_name));
1825                 generate_random_testvec_config(&rng, cfg, cfgname,
1826                                                sizeof(cfgname));
1827
1828                 err = test_hash_vec_cfg(&vec, vec_name, cfg,
1829                                         req, desc, tsgl, hashstate);
1830                 if (err)
1831                         goto out;
1832                 cond_resched();
1833         }
1834         err = 0;
1835 out:
1836         kfree(cfg);
1837         kfree(vec.key);
1838         kfree(vec.plaintext);
1839         kfree(vec.digest);
1840         crypto_free_shash(generic_tfm);
1841         kfree_sensitive(generic_desc);
1842         return err;
1843 }
1844 #else /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
1845 static int test_hash_vs_generic_impl(const char *generic_driver,
1846                                      unsigned int maxkeysize,
1847                                      struct ahash_request *req,
1848                                      struct shash_desc *desc,
1849                                      struct test_sglist *tsgl,
1850                                      u8 *hashstate)
1851 {
1852         return 0;
1853 }
1854 #endif /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
1855
1856 static int alloc_shash(const char *driver, u32 type, u32 mask,
1857                        struct crypto_shash **tfm_ret,
1858                        struct shash_desc **desc_ret)
1859 {
1860         struct crypto_shash *tfm;
1861         struct shash_desc *desc;
1862
1863         tfm = crypto_alloc_shash(driver, type, mask);
1864         if (IS_ERR(tfm)) {
1865                 if (PTR_ERR(tfm) == -ENOENT) {
1866                         /*
1867                          * This algorithm is only available through the ahash
1868                          * API, not the shash API, so skip the shash tests.
1869                          */
1870                         return 0;
1871                 }
1872                 pr_err("alg: hash: failed to allocate shash transform for %s: %ld\n",
1873                        driver, PTR_ERR(tfm));
1874                 return PTR_ERR(tfm);
1875         }
1876
1877         desc = kmalloc(sizeof(*desc) + crypto_shash_descsize(tfm), GFP_KERNEL);
1878         if (!desc) {
1879                 crypto_free_shash(tfm);
1880                 return -ENOMEM;
1881         }
1882         desc->tfm = tfm;
1883
1884         *tfm_ret = tfm;
1885         *desc_ret = desc;
1886         return 0;
1887 }
1888
1889 static int __alg_test_hash(const struct hash_testvec *vecs,
1890                            unsigned int num_vecs, const char *driver,
1891                            u32 type, u32 mask,
1892                            const char *generic_driver, unsigned int maxkeysize)
1893 {
1894         struct crypto_ahash *atfm = NULL;
1895         struct ahash_request *req = NULL;
1896         struct crypto_shash *stfm = NULL;
1897         struct shash_desc *desc = NULL;
1898         struct test_sglist *tsgl = NULL;
1899         u8 *hashstate = NULL;
1900         unsigned int statesize;
1901         unsigned int i;
1902         int err;
1903
1904         /*
1905          * Always test the ahash API.  This works regardless of whether the
1906          * algorithm is implemented as ahash or shash.
1907          */
1908
1909         atfm = crypto_alloc_ahash(driver, type, mask);
1910         if (IS_ERR(atfm)) {
1911                 pr_err("alg: hash: failed to allocate transform for %s: %ld\n",
1912                        driver, PTR_ERR(atfm));
1913                 return PTR_ERR(atfm);
1914         }
1915         driver = crypto_ahash_driver_name(atfm);
1916
1917         req = ahash_request_alloc(atfm, GFP_KERNEL);
1918         if (!req) {
1919                 pr_err("alg: hash: failed to allocate request for %s\n",
1920                        driver);
1921                 err = -ENOMEM;
1922                 goto out;
1923         }
1924
1925         /*
1926          * If available also test the shash API, to cover corner cases that may
1927          * be missed by testing the ahash API only.
1928          */
1929         err = alloc_shash(driver, type, mask, &stfm, &desc);
1930         if (err)
1931                 goto out;
1932
1933         tsgl = kmalloc(sizeof(*tsgl), GFP_KERNEL);
1934         if (!tsgl || init_test_sglist(tsgl) != 0) {
1935                 pr_err("alg: hash: failed to allocate test buffers for %s\n",
1936                        driver);
1937                 kfree(tsgl);
1938                 tsgl = NULL;
1939                 err = -ENOMEM;
1940                 goto out;
1941         }
1942
1943         statesize = crypto_ahash_statesize(atfm);
1944         if (stfm)
1945                 statesize = max(statesize, crypto_shash_statesize(stfm));
1946         hashstate = kmalloc(statesize + TESTMGR_POISON_LEN, GFP_KERNEL);
1947         if (!hashstate) {
1948                 pr_err("alg: hash: failed to allocate hash state buffer for %s\n",
1949                        driver);
1950                 err = -ENOMEM;
1951                 goto out;
1952         }
1953
1954         for (i = 0; i < num_vecs; i++) {
1955                 if (fips_enabled && vecs[i].fips_skip)
1956                         continue;
1957
1958                 err = test_hash_vec(&vecs[i], i, req, desc, tsgl, hashstate);
1959                 if (err)
1960                         goto out;
1961                 cond_resched();
1962         }
1963         err = test_hash_vs_generic_impl(generic_driver, maxkeysize, req,
1964                                         desc, tsgl, hashstate);
1965 out:
1966         kfree(hashstate);
1967         if (tsgl) {
1968                 destroy_test_sglist(tsgl);
1969                 kfree(tsgl);
1970         }
1971         kfree(desc);
1972         crypto_free_shash(stfm);
1973         ahash_request_free(req);
1974         crypto_free_ahash(atfm);
1975         return err;
1976 }
1977
1978 static int alg_test_hash(const struct alg_test_desc *desc, const char *driver,
1979                          u32 type, u32 mask)
1980 {
1981         const struct hash_testvec *template = desc->suite.hash.vecs;
1982         unsigned int tcount = desc->suite.hash.count;
1983         unsigned int nr_unkeyed, nr_keyed;
1984         unsigned int maxkeysize = 0;
1985         int err;
1986
1987         /*
1988          * For OPTIONAL_KEY algorithms, we have to do all the unkeyed tests
1989          * first, before setting a key on the tfm.  To make this easier, we
1990          * require that the unkeyed test vectors (if any) are listed first.
1991          */
1992
1993         for (nr_unkeyed = 0; nr_unkeyed < tcount; nr_unkeyed++) {
1994                 if (template[nr_unkeyed].ksize)
1995                         break;
1996         }
1997         for (nr_keyed = 0; nr_unkeyed + nr_keyed < tcount; nr_keyed++) {
1998                 if (!template[nr_unkeyed + nr_keyed].ksize) {
1999                         pr_err("alg: hash: test vectors for %s out of order, "
2000                                "unkeyed ones must come first\n", desc->alg);
2001                         return -EINVAL;
2002                 }
2003                 maxkeysize = max_t(unsigned int, maxkeysize,
2004                                    template[nr_unkeyed + nr_keyed].ksize);
2005         }
2006
2007         err = 0;
2008         if (nr_unkeyed) {
2009                 err = __alg_test_hash(template, nr_unkeyed, driver, type, mask,
2010                                       desc->generic_driver, maxkeysize);
2011                 template += nr_unkeyed;
2012         }
2013
2014         if (!err && nr_keyed)
2015                 err = __alg_test_hash(template, nr_keyed, driver, type, mask,
2016                                       desc->generic_driver, maxkeysize);
2017
2018         return err;
2019 }
2020
2021 static int test_aead_vec_cfg(int enc, const struct aead_testvec *vec,
2022                              const char *vec_name,
2023                              const struct testvec_config *cfg,
2024                              struct aead_request *req,
2025                              struct cipher_test_sglists *tsgls)
2026 {
2027         struct crypto_aead *tfm = crypto_aead_reqtfm(req);
2028         const unsigned int alignmask = crypto_aead_alignmask(tfm);
2029         const unsigned int ivsize = crypto_aead_ivsize(tfm);
2030         const unsigned int authsize = vec->clen - vec->plen;
2031         const char *driver = crypto_aead_driver_name(tfm);
2032         const u32 req_flags = CRYPTO_TFM_REQ_MAY_BACKLOG | cfg->req_flags;
2033         const char *op = enc ? "encryption" : "decryption";
2034         DECLARE_CRYPTO_WAIT(wait);
2035         u8 _iv[3 * (MAX_ALGAPI_ALIGNMASK + 1) + MAX_IVLEN];
2036         u8 *iv = PTR_ALIGN(&_iv[0], 2 * (MAX_ALGAPI_ALIGNMASK + 1)) +
2037                  cfg->iv_offset +
2038                  (cfg->iv_offset_relative_to_alignmask ? alignmask : 0);
2039         struct kvec input[2];
2040         int err;
2041
2042         /* Set the key */
2043         if (vec->wk)
2044                 crypto_aead_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2045         else
2046                 crypto_aead_clear_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2047
2048         err = do_setkey(crypto_aead_setkey, tfm, vec->key, vec->klen,
2049                         cfg, alignmask);
2050         if (err && err != vec->setkey_error) {
2051                 pr_err("alg: aead: %s setkey failed on test vector %s; expected_error=%d, actual_error=%d, flags=%#x\n",
2052                        driver, vec_name, vec->setkey_error, err,
2053                        crypto_aead_get_flags(tfm));
2054                 return err;
2055         }
2056         if (!err && vec->setkey_error) {
2057                 pr_err("alg: aead: %s setkey unexpectedly succeeded on test vector %s; expected_error=%d\n",
2058                        driver, vec_name, vec->setkey_error);
2059                 return -EINVAL;
2060         }
2061
2062         /* Set the authentication tag size */
2063         err = crypto_aead_setauthsize(tfm, authsize);
2064         if (err && err != vec->setauthsize_error) {
2065                 pr_err("alg: aead: %s setauthsize failed on test vector %s; expected_error=%d, actual_error=%d\n",
2066                        driver, vec_name, vec->setauthsize_error, err);
2067                 return err;
2068         }
2069         if (!err && vec->setauthsize_error) {
2070                 pr_err("alg: aead: %s setauthsize unexpectedly succeeded on test vector %s; expected_error=%d\n",
2071                        driver, vec_name, vec->setauthsize_error);
2072                 return -EINVAL;
2073         }
2074
2075         if (vec->setkey_error || vec->setauthsize_error)
2076                 return 0;
2077
2078         /* The IV must be copied to a buffer, as the algorithm may modify it */
2079         if (WARN_ON(ivsize > MAX_IVLEN))
2080                 return -EINVAL;
2081         if (vec->iv)
2082                 memcpy(iv, vec->iv, ivsize);
2083         else
2084                 memset(iv, 0, ivsize);
2085
2086         /* Build the src/dst scatterlists */
2087         input[0].iov_base = (void *)vec->assoc;
2088         input[0].iov_len = vec->alen;
2089         input[1].iov_base = enc ? (void *)vec->ptext : (void *)vec->ctext;
2090         input[1].iov_len = enc ? vec->plen : vec->clen;
2091         err = build_cipher_test_sglists(tsgls, cfg, alignmask,
2092                                         vec->alen + (enc ? vec->plen :
2093                                                      vec->clen),
2094                                         vec->alen + (enc ? vec->clen :
2095                                                      vec->plen),
2096                                         input, 2);
2097         if (err) {
2098                 pr_err("alg: aead: %s %s: error preparing scatterlists for test vector %s, cfg=\"%s\"\n",
2099                        driver, op, vec_name, cfg->name);
2100                 return err;
2101         }
2102
2103         /* Do the actual encryption or decryption */
2104         testmgr_poison(req->__ctx, crypto_aead_reqsize(tfm));
2105         aead_request_set_callback(req, req_flags, crypto_req_done, &wait);
2106         aead_request_set_crypt(req, tsgls->src.sgl_ptr, tsgls->dst.sgl_ptr,
2107                                enc ? vec->plen : vec->clen, iv);
2108         aead_request_set_ad(req, vec->alen);
2109         if (cfg->nosimd)
2110                 crypto_disable_simd_for_test();
2111         err = enc ? crypto_aead_encrypt(req) : crypto_aead_decrypt(req);
2112         if (cfg->nosimd)
2113                 crypto_reenable_simd_for_test();
2114         err = crypto_wait_req(err, &wait);
2115
2116         /* Check that the algorithm didn't overwrite things it shouldn't have */
2117         if (req->cryptlen != (enc ? vec->plen : vec->clen) ||
2118             req->assoclen != vec->alen ||
2119             req->iv != iv ||
2120             req->src != tsgls->src.sgl_ptr ||
2121             req->dst != tsgls->dst.sgl_ptr ||
2122             crypto_aead_reqtfm(req) != tfm ||
2123             req->base.complete != crypto_req_done ||
2124             req->base.flags != req_flags ||
2125             req->base.data != &wait) {
2126                 pr_err("alg: aead: %s %s corrupted request struct on test vector %s, cfg=\"%s\"\n",
2127                        driver, op, vec_name, cfg->name);
2128                 if (req->cryptlen != (enc ? vec->plen : vec->clen))
2129                         pr_err("alg: aead: changed 'req->cryptlen'\n");
2130                 if (req->assoclen != vec->alen)
2131                         pr_err("alg: aead: changed 'req->assoclen'\n");
2132                 if (req->iv != iv)
2133                         pr_err("alg: aead: changed 'req->iv'\n");
2134                 if (req->src != tsgls->src.sgl_ptr)
2135                         pr_err("alg: aead: changed 'req->src'\n");
2136                 if (req->dst != tsgls->dst.sgl_ptr)
2137                         pr_err("alg: aead: changed 'req->dst'\n");
2138                 if (crypto_aead_reqtfm(req) != tfm)
2139                         pr_err("alg: aead: changed 'req->base.tfm'\n");
2140                 if (req->base.complete != crypto_req_done)
2141                         pr_err("alg: aead: changed 'req->base.complete'\n");
2142                 if (req->base.flags != req_flags)
2143                         pr_err("alg: aead: changed 'req->base.flags'\n");
2144                 if (req->base.data != &wait)
2145                         pr_err("alg: aead: changed 'req->base.data'\n");
2146                 return -EINVAL;
2147         }
2148         if (is_test_sglist_corrupted(&tsgls->src)) {
2149                 pr_err("alg: aead: %s %s corrupted src sgl on test vector %s, cfg=\"%s\"\n",
2150                        driver, op, vec_name, cfg->name);
2151                 return -EINVAL;
2152         }
2153         if (tsgls->dst.sgl_ptr != tsgls->src.sgl &&
2154             is_test_sglist_corrupted(&tsgls->dst)) {
2155                 pr_err("alg: aead: %s %s corrupted dst sgl on test vector %s, cfg=\"%s\"\n",
2156                        driver, op, vec_name, cfg->name);
2157                 return -EINVAL;
2158         }
2159
2160         /* Check for unexpected success or failure, or wrong error code */
2161         if ((err == 0 && vec->novrfy) ||
2162             (err != vec->crypt_error && !(err == -EBADMSG && vec->novrfy))) {
2163                 char expected_error[32];
2164
2165                 if (vec->novrfy &&
2166                     vec->crypt_error != 0 && vec->crypt_error != -EBADMSG)
2167                         sprintf(expected_error, "-EBADMSG or %d",
2168                                 vec->crypt_error);
2169                 else if (vec->novrfy)
2170                         sprintf(expected_error, "-EBADMSG");
2171                 else
2172                         sprintf(expected_error, "%d", vec->crypt_error);
2173                 if (err) {
2174                         pr_err("alg: aead: %s %s failed on test vector %s; expected_error=%s, actual_error=%d, cfg=\"%s\"\n",
2175                                driver, op, vec_name, expected_error, err,
2176                                cfg->name);
2177                         return err;
2178                 }
2179                 pr_err("alg: aead: %s %s unexpectedly succeeded on test vector %s; expected_error=%s, cfg=\"%s\"\n",
2180                        driver, op, vec_name, expected_error, cfg->name);
2181                 return -EINVAL;
2182         }
2183         if (err) /* Expectedly failed. */
2184                 return 0;
2185
2186         /* Check for the correct output (ciphertext or plaintext) */
2187         err = verify_correct_output(&tsgls->dst, enc ? vec->ctext : vec->ptext,
2188                                     enc ? vec->clen : vec->plen,
2189                                     vec->alen,
2190                                     enc || cfg->inplace_mode == OUT_OF_PLACE);
2191         if (err == -EOVERFLOW) {
2192                 pr_err("alg: aead: %s %s overran dst buffer on test vector %s, cfg=\"%s\"\n",
2193                        driver, op, vec_name, cfg->name);
2194                 return err;
2195         }
2196         if (err) {
2197                 pr_err("alg: aead: %s %s test failed (wrong result) on test vector %s, cfg=\"%s\"\n",
2198                        driver, op, vec_name, cfg->name);
2199                 return err;
2200         }
2201
2202         return 0;
2203 }
2204
2205 static int test_aead_vec(int enc, const struct aead_testvec *vec,
2206                          unsigned int vec_num, struct aead_request *req,
2207                          struct cipher_test_sglists *tsgls)
2208 {
2209         char vec_name[16];
2210         unsigned int i;
2211         int err;
2212
2213         if (enc && vec->novrfy)
2214                 return 0;
2215
2216         sprintf(vec_name, "%u", vec_num);
2217
2218         for (i = 0; i < ARRAY_SIZE(default_cipher_testvec_configs); i++) {
2219                 err = test_aead_vec_cfg(enc, vec, vec_name,
2220                                         &default_cipher_testvec_configs[i],
2221                                         req, tsgls);
2222                 if (err)
2223                         return err;
2224         }
2225
2226 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
2227         if (!noextratests) {
2228                 struct rnd_state rng;
2229                 struct testvec_config cfg;
2230                 char cfgname[TESTVEC_CONFIG_NAMELEN];
2231
2232                 init_rnd_state(&rng);
2233
2234                 for (i = 0; i < fuzz_iterations; i++) {
2235                         generate_random_testvec_config(&rng, &cfg, cfgname,
2236                                                        sizeof(cfgname));
2237                         err = test_aead_vec_cfg(enc, vec, vec_name,
2238                                                 &cfg, req, tsgls);
2239                         if (err)
2240                                 return err;
2241                         cond_resched();
2242                 }
2243         }
2244 #endif
2245         return 0;
2246 }
2247
2248 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
2249
2250 struct aead_extra_tests_ctx {
2251         struct rnd_state rng;
2252         struct aead_request *req;
2253         struct crypto_aead *tfm;
2254         const struct alg_test_desc *test_desc;
2255         struct cipher_test_sglists *tsgls;
2256         unsigned int maxdatasize;
2257         unsigned int maxkeysize;
2258
2259         struct aead_testvec vec;
2260         char vec_name[64];
2261         char cfgname[TESTVEC_CONFIG_NAMELEN];
2262         struct testvec_config cfg;
2263 };
2264
2265 /*
2266  * Make at least one random change to a (ciphertext, AAD) pair.  "Ciphertext"
2267  * here means the full ciphertext including the authentication tag.  The
2268  * authentication tag (and hence also the ciphertext) is assumed to be nonempty.
2269  */
2270 static void mutate_aead_message(struct rnd_state *rng,
2271                                 struct aead_testvec *vec, bool aad_iv,
2272                                 unsigned int ivsize)
2273 {
2274         const unsigned int aad_tail_size = aad_iv ? ivsize : 0;
2275         const unsigned int authsize = vec->clen - vec->plen;
2276
2277         if (prandom_bool(rng) && vec->alen > aad_tail_size) {
2278                  /* Mutate the AAD */
2279                 flip_random_bit(rng, (u8 *)vec->assoc,
2280                                 vec->alen - aad_tail_size);
2281                 if (prandom_bool(rng))
2282                         return;
2283         }
2284         if (prandom_bool(rng)) {
2285                 /* Mutate auth tag (assuming it's at the end of ciphertext) */
2286                 flip_random_bit(rng, (u8 *)vec->ctext + vec->plen, authsize);
2287         } else {
2288                 /* Mutate any part of the ciphertext */
2289                 flip_random_bit(rng, (u8 *)vec->ctext, vec->clen);
2290         }
2291 }
2292
2293 /*
2294  * Minimum authentication tag size in bytes at which we assume that we can
2295  * reliably generate inauthentic messages, i.e. not generate an authentic
2296  * message by chance.
2297  */
2298 #define MIN_COLLISION_FREE_AUTHSIZE 8
2299
2300 static void generate_aead_message(struct rnd_state *rng,
2301                                   struct aead_request *req,
2302                                   const struct aead_test_suite *suite,
2303                                   struct aead_testvec *vec,
2304                                   bool prefer_inauthentic)
2305 {
2306         struct crypto_aead *tfm = crypto_aead_reqtfm(req);
2307         const unsigned int ivsize = crypto_aead_ivsize(tfm);
2308         const unsigned int authsize = vec->clen - vec->plen;
2309         const bool inauthentic = (authsize >= MIN_COLLISION_FREE_AUTHSIZE) &&
2310                                  (prefer_inauthentic ||
2311                                   prandom_u32_below(rng, 4) == 0);
2312
2313         /* Generate the AAD. */
2314         generate_random_bytes(rng, (u8 *)vec->assoc, vec->alen);
2315         if (suite->aad_iv && vec->alen >= ivsize)
2316                 /* Avoid implementation-defined behavior. */
2317                 memcpy((u8 *)vec->assoc + vec->alen - ivsize, vec->iv, ivsize);
2318
2319         if (inauthentic && prandom_bool(rng)) {
2320                 /* Generate a random ciphertext. */
2321                 generate_random_bytes(rng, (u8 *)vec->ctext, vec->clen);
2322         } else {
2323                 int i = 0;
2324                 struct scatterlist src[2], dst;
2325                 u8 iv[MAX_IVLEN];
2326                 DECLARE_CRYPTO_WAIT(wait);
2327
2328                 /* Generate a random plaintext and encrypt it. */
2329                 sg_init_table(src, 2);
2330                 if (vec->alen)
2331                         sg_set_buf(&src[i++], vec->assoc, vec->alen);
2332                 if (vec->plen) {
2333                         generate_random_bytes(rng, (u8 *)vec->ptext, vec->plen);
2334                         sg_set_buf(&src[i++], vec->ptext, vec->plen);
2335                 }
2336                 sg_init_one(&dst, vec->ctext, vec->alen + vec->clen);
2337                 memcpy(iv, vec->iv, ivsize);
2338                 aead_request_set_callback(req, 0, crypto_req_done, &wait);
2339                 aead_request_set_crypt(req, src, &dst, vec->plen, iv);
2340                 aead_request_set_ad(req, vec->alen);
2341                 vec->crypt_error = crypto_wait_req(crypto_aead_encrypt(req),
2342                                                    &wait);
2343                 /* If encryption failed, we're done. */
2344                 if (vec->crypt_error != 0)
2345                         return;
2346                 memmove((u8 *)vec->ctext, vec->ctext + vec->alen, vec->clen);
2347                 if (!inauthentic)
2348                         return;
2349                 /*
2350                  * Mutate the authentic (ciphertext, AAD) pair to get an
2351                  * inauthentic one.
2352                  */
2353                 mutate_aead_message(rng, vec, suite->aad_iv, ivsize);
2354         }
2355         vec->novrfy = 1;
2356         if (suite->einval_allowed)
2357                 vec->crypt_error = -EINVAL;
2358 }
2359
2360 /*
2361  * Generate an AEAD test vector 'vec' using the implementation specified by
2362  * 'req'.  The buffers in 'vec' must already be allocated.
2363  *
2364  * If 'prefer_inauthentic' is true, then this function will generate inauthentic
2365  * test vectors (i.e. vectors with 'vec->novrfy=1') more often.
2366  */
2367 static void generate_random_aead_testvec(struct rnd_state *rng,
2368                                          struct aead_request *req,
2369                                          struct aead_testvec *vec,
2370                                          const struct aead_test_suite *suite,
2371                                          unsigned int maxkeysize,
2372                                          unsigned int maxdatasize,
2373                                          char *name, size_t max_namelen,
2374                                          bool prefer_inauthentic)
2375 {
2376         struct crypto_aead *tfm = crypto_aead_reqtfm(req);
2377         const unsigned int ivsize = crypto_aead_ivsize(tfm);
2378         const unsigned int maxauthsize = crypto_aead_maxauthsize(tfm);
2379         unsigned int authsize;
2380         unsigned int total_len;
2381
2382         /* Key: length in [0, maxkeysize], but usually choose maxkeysize */
2383         vec->klen = maxkeysize;
2384         if (prandom_u32_below(rng, 4) == 0)
2385                 vec->klen = prandom_u32_below(rng, maxkeysize + 1);
2386         generate_random_bytes(rng, (u8 *)vec->key, vec->klen);
2387         vec->setkey_error = crypto_aead_setkey(tfm, vec->key, vec->klen);
2388
2389         /* IV */
2390         generate_random_bytes(rng, (u8 *)vec->iv, ivsize);
2391
2392         /* Tag length: in [0, maxauthsize], but usually choose maxauthsize */
2393         authsize = maxauthsize;
2394         if (prandom_u32_below(rng, 4) == 0)
2395                 authsize = prandom_u32_below(rng, maxauthsize + 1);
2396         if (prefer_inauthentic && authsize < MIN_COLLISION_FREE_AUTHSIZE)
2397                 authsize = MIN_COLLISION_FREE_AUTHSIZE;
2398         if (WARN_ON(authsize > maxdatasize))
2399                 authsize = maxdatasize;
2400         maxdatasize -= authsize;
2401         vec->setauthsize_error = crypto_aead_setauthsize(tfm, authsize);
2402
2403         /* AAD, plaintext, and ciphertext lengths */
2404         total_len = generate_random_length(rng, maxdatasize);
2405         if (prandom_u32_below(rng, 4) == 0)
2406                 vec->alen = 0;
2407         else
2408                 vec->alen = generate_random_length(rng, total_len);
2409         vec->plen = total_len - vec->alen;
2410         vec->clen = vec->plen + authsize;
2411
2412         /*
2413          * Generate the AAD, plaintext, and ciphertext.  Not applicable if the
2414          * key or the authentication tag size couldn't be set.
2415          */
2416         vec->novrfy = 0;
2417         vec->crypt_error = 0;
2418         if (vec->setkey_error == 0 && vec->setauthsize_error == 0)
2419                 generate_aead_message(rng, req, suite, vec, prefer_inauthentic);
2420         snprintf(name, max_namelen,
2421                  "\"random: alen=%u plen=%u authsize=%u klen=%u novrfy=%d\"",
2422                  vec->alen, vec->plen, authsize, vec->klen, vec->novrfy);
2423 }
2424
2425 static void try_to_generate_inauthentic_testvec(
2426                                         struct aead_extra_tests_ctx *ctx)
2427 {
2428         int i;
2429
2430         for (i = 0; i < 10; i++) {
2431                 generate_random_aead_testvec(&ctx->rng, ctx->req, &ctx->vec,
2432                                              &ctx->test_desc->suite.aead,
2433                                              ctx->maxkeysize, ctx->maxdatasize,
2434                                              ctx->vec_name,
2435                                              sizeof(ctx->vec_name), true);
2436                 if (ctx->vec.novrfy)
2437                         return;
2438         }
2439 }
2440
2441 /*
2442  * Generate inauthentic test vectors (i.e. ciphertext, AAD pairs that aren't the
2443  * result of an encryption with the key) and verify that decryption fails.
2444  */
2445 static int test_aead_inauthentic_inputs(struct aead_extra_tests_ctx *ctx)
2446 {
2447         unsigned int i;
2448         int err;
2449
2450         for (i = 0; i < fuzz_iterations * 8; i++) {
2451                 /*
2452                  * Since this part of the tests isn't comparing the
2453                  * implementation to another, there's no point in testing any
2454                  * test vectors other than inauthentic ones (vec.novrfy=1) here.
2455                  *
2456                  * If we're having trouble generating such a test vector, e.g.
2457                  * if the algorithm keeps rejecting the generated keys, don't
2458                  * retry forever; just continue on.
2459                  */
2460                 try_to_generate_inauthentic_testvec(ctx);
2461                 if (ctx->vec.novrfy) {
2462                         generate_random_testvec_config(&ctx->rng, &ctx->cfg,
2463                                                        ctx->cfgname,
2464                                                        sizeof(ctx->cfgname));
2465                         err = test_aead_vec_cfg(DECRYPT, &ctx->vec,
2466                                                 ctx->vec_name, &ctx->cfg,
2467                                                 ctx->req, ctx->tsgls);
2468                         if (err)
2469                                 return err;
2470                 }
2471                 cond_resched();
2472         }
2473         return 0;
2474 }
2475
2476 /*
2477  * Test the AEAD algorithm against the corresponding generic implementation, if
2478  * one is available.
2479  */
2480 static int test_aead_vs_generic_impl(struct aead_extra_tests_ctx *ctx)
2481 {
2482         struct crypto_aead *tfm = ctx->tfm;
2483         const char *algname = crypto_aead_alg(tfm)->base.cra_name;
2484         const char *driver = crypto_aead_driver_name(tfm);
2485         const char *generic_driver = ctx->test_desc->generic_driver;
2486         char _generic_driver[CRYPTO_MAX_ALG_NAME];
2487         struct crypto_aead *generic_tfm = NULL;
2488         struct aead_request *generic_req = NULL;
2489         unsigned int i;
2490         int err;
2491
2492         if (!generic_driver) { /* Use default naming convention? */
2493                 err = build_generic_driver_name(algname, _generic_driver);
2494                 if (err)
2495                         return err;
2496                 generic_driver = _generic_driver;
2497         }
2498
2499         if (strcmp(generic_driver, driver) == 0) /* Already the generic impl? */
2500                 return 0;
2501
2502         generic_tfm = crypto_alloc_aead(generic_driver, 0, 0);
2503         if (IS_ERR(generic_tfm)) {
2504                 err = PTR_ERR(generic_tfm);
2505                 if (err == -ENOENT) {
2506                         pr_warn("alg: aead: skipping comparison tests for %s because %s is unavailable\n",
2507                                 driver, generic_driver);
2508                         return 0;
2509                 }
2510                 pr_err("alg: aead: error allocating %s (generic impl of %s): %d\n",
2511                        generic_driver, algname, err);
2512                 return err;
2513         }
2514
2515         generic_req = aead_request_alloc(generic_tfm, GFP_KERNEL);
2516         if (!generic_req) {
2517                 err = -ENOMEM;
2518                 goto out;
2519         }
2520
2521         /* Check the algorithm properties for consistency. */
2522
2523         if (crypto_aead_maxauthsize(tfm) !=
2524             crypto_aead_maxauthsize(generic_tfm)) {
2525                 pr_err("alg: aead: maxauthsize for %s (%u) doesn't match generic impl (%u)\n",
2526                        driver, crypto_aead_maxauthsize(tfm),
2527                        crypto_aead_maxauthsize(generic_tfm));
2528                 err = -EINVAL;
2529                 goto out;
2530         }
2531
2532         if (crypto_aead_ivsize(tfm) != crypto_aead_ivsize(generic_tfm)) {
2533                 pr_err("alg: aead: ivsize for %s (%u) doesn't match generic impl (%u)\n",
2534                        driver, crypto_aead_ivsize(tfm),
2535                        crypto_aead_ivsize(generic_tfm));
2536                 err = -EINVAL;
2537                 goto out;
2538         }
2539
2540         if (crypto_aead_blocksize(tfm) != crypto_aead_blocksize(generic_tfm)) {
2541                 pr_err("alg: aead: blocksize for %s (%u) doesn't match generic impl (%u)\n",
2542                        driver, crypto_aead_blocksize(tfm),
2543                        crypto_aead_blocksize(generic_tfm));
2544                 err = -EINVAL;
2545                 goto out;
2546         }
2547
2548         /*
2549          * Now generate test vectors using the generic implementation, and test
2550          * the other implementation against them.
2551          */
2552         for (i = 0; i < fuzz_iterations * 8; i++) {
2553                 generate_random_aead_testvec(&ctx->rng, generic_req, &ctx->vec,
2554                                              &ctx->test_desc->suite.aead,
2555                                              ctx->maxkeysize, ctx->maxdatasize,
2556                                              ctx->vec_name,
2557                                              sizeof(ctx->vec_name), false);
2558                 generate_random_testvec_config(&ctx->rng, &ctx->cfg,
2559                                                ctx->cfgname,
2560                                                sizeof(ctx->cfgname));
2561                 if (!ctx->vec.novrfy) {
2562                         err = test_aead_vec_cfg(ENCRYPT, &ctx->vec,
2563                                                 ctx->vec_name, &ctx->cfg,
2564                                                 ctx->req, ctx->tsgls);
2565                         if (err)
2566                                 goto out;
2567                 }
2568                 if (ctx->vec.crypt_error == 0 || ctx->vec.novrfy) {
2569                         err = test_aead_vec_cfg(DECRYPT, &ctx->vec,
2570                                                 ctx->vec_name, &ctx->cfg,
2571                                                 ctx->req, ctx->tsgls);
2572                         if (err)
2573                                 goto out;
2574                 }
2575                 cond_resched();
2576         }
2577         err = 0;
2578 out:
2579         crypto_free_aead(generic_tfm);
2580         aead_request_free(generic_req);
2581         return err;
2582 }
2583
2584 static int test_aead_extra(const struct alg_test_desc *test_desc,
2585                            struct aead_request *req,
2586                            struct cipher_test_sglists *tsgls)
2587 {
2588         struct aead_extra_tests_ctx *ctx;
2589         unsigned int i;
2590         int err;
2591
2592         if (noextratests)
2593                 return 0;
2594
2595         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
2596         if (!ctx)
2597                 return -ENOMEM;
2598         init_rnd_state(&ctx->rng);
2599         ctx->req = req;
2600         ctx->tfm = crypto_aead_reqtfm(req);
2601         ctx->test_desc = test_desc;
2602         ctx->tsgls = tsgls;
2603         ctx->maxdatasize = (2 * PAGE_SIZE) - TESTMGR_POISON_LEN;
2604         ctx->maxkeysize = 0;
2605         for (i = 0; i < test_desc->suite.aead.count; i++)
2606                 ctx->maxkeysize = max_t(unsigned int, ctx->maxkeysize,
2607                                         test_desc->suite.aead.vecs[i].klen);
2608
2609         ctx->vec.key = kmalloc(ctx->maxkeysize, GFP_KERNEL);
2610         ctx->vec.iv = kmalloc(crypto_aead_ivsize(ctx->tfm), GFP_KERNEL);
2611         ctx->vec.assoc = kmalloc(ctx->maxdatasize, GFP_KERNEL);
2612         ctx->vec.ptext = kmalloc(ctx->maxdatasize, GFP_KERNEL);
2613         ctx->vec.ctext = kmalloc(ctx->maxdatasize, GFP_KERNEL);
2614         if (!ctx->vec.key || !ctx->vec.iv || !ctx->vec.assoc ||
2615             !ctx->vec.ptext || !ctx->vec.ctext) {
2616                 err = -ENOMEM;
2617                 goto out;
2618         }
2619
2620         err = test_aead_vs_generic_impl(ctx);
2621         if (err)
2622                 goto out;
2623
2624         err = test_aead_inauthentic_inputs(ctx);
2625 out:
2626         kfree(ctx->vec.key);
2627         kfree(ctx->vec.iv);
2628         kfree(ctx->vec.assoc);
2629         kfree(ctx->vec.ptext);
2630         kfree(ctx->vec.ctext);
2631         kfree(ctx);
2632         return err;
2633 }
2634 #else /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
2635 static int test_aead_extra(const struct alg_test_desc *test_desc,
2636                            struct aead_request *req,
2637                            struct cipher_test_sglists *tsgls)
2638 {
2639         return 0;
2640 }
2641 #endif /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
2642
2643 static int test_aead(int enc, const struct aead_test_suite *suite,
2644                      struct aead_request *req,
2645                      struct cipher_test_sglists *tsgls)
2646 {
2647         unsigned int i;
2648         int err;
2649
2650         for (i = 0; i < suite->count; i++) {
2651                 err = test_aead_vec(enc, &suite->vecs[i], i, req, tsgls);
2652                 if (err)
2653                         return err;
2654                 cond_resched();
2655         }
2656         return 0;
2657 }
2658
2659 static int alg_test_aead(const struct alg_test_desc *desc, const char *driver,
2660                          u32 type, u32 mask)
2661 {
2662         const struct aead_test_suite *suite = &desc->suite.aead;
2663         struct crypto_aead *tfm;
2664         struct aead_request *req = NULL;
2665         struct cipher_test_sglists *tsgls = NULL;
2666         int err;
2667
2668         if (suite->count <= 0) {
2669                 pr_err("alg: aead: empty test suite for %s\n", driver);
2670                 return -EINVAL;
2671         }
2672
2673         tfm = crypto_alloc_aead(driver, type, mask);
2674         if (IS_ERR(tfm)) {
2675                 pr_err("alg: aead: failed to allocate transform for %s: %ld\n",
2676                        driver, PTR_ERR(tfm));
2677                 return PTR_ERR(tfm);
2678         }
2679         driver = crypto_aead_driver_name(tfm);
2680
2681         req = aead_request_alloc(tfm, GFP_KERNEL);
2682         if (!req) {
2683                 pr_err("alg: aead: failed to allocate request for %s\n",
2684                        driver);
2685                 err = -ENOMEM;
2686                 goto out;
2687         }
2688
2689         tsgls = alloc_cipher_test_sglists();
2690         if (!tsgls) {
2691                 pr_err("alg: aead: failed to allocate test buffers for %s\n",
2692                        driver);
2693                 err = -ENOMEM;
2694                 goto out;
2695         }
2696
2697         err = test_aead(ENCRYPT, suite, req, tsgls);
2698         if (err)
2699                 goto out;
2700
2701         err = test_aead(DECRYPT, suite, req, tsgls);
2702         if (err)
2703                 goto out;
2704
2705         err = test_aead_extra(desc, req, tsgls);
2706 out:
2707         free_cipher_test_sglists(tsgls);
2708         aead_request_free(req);
2709         crypto_free_aead(tfm);
2710         return err;
2711 }
2712
2713 static int test_cipher(struct crypto_cipher *tfm, int enc,
2714                        const struct cipher_testvec *template,
2715                        unsigned int tcount)
2716 {
2717         const char *algo = crypto_tfm_alg_driver_name(crypto_cipher_tfm(tfm));
2718         unsigned int i, j, k;
2719         char *q;
2720         const char *e;
2721         const char *input, *result;
2722         void *data;
2723         char *xbuf[XBUFSIZE];
2724         int ret = -ENOMEM;
2725
2726         if (testmgr_alloc_buf(xbuf))
2727                 goto out_nobuf;
2728
2729         if (enc == ENCRYPT)
2730                 e = "encryption";
2731         else
2732                 e = "decryption";
2733
2734         j = 0;
2735         for (i = 0; i < tcount; i++) {
2736
2737                 if (fips_enabled && template[i].fips_skip)
2738                         continue;
2739
2740                 input  = enc ? template[i].ptext : template[i].ctext;
2741                 result = enc ? template[i].ctext : template[i].ptext;
2742                 j++;
2743
2744                 ret = -EINVAL;
2745                 if (WARN_ON(template[i].len > PAGE_SIZE))
2746                         goto out;
2747
2748                 data = xbuf[0];
2749                 memcpy(data, input, template[i].len);
2750
2751                 crypto_cipher_clear_flags(tfm, ~0);
2752                 if (template[i].wk)
2753                         crypto_cipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2754
2755                 ret = crypto_cipher_setkey(tfm, template[i].key,
2756                                            template[i].klen);
2757                 if (ret) {
2758                         if (ret == template[i].setkey_error)
2759                                 continue;
2760                         pr_err("alg: cipher: %s setkey failed on test vector %u; expected_error=%d, actual_error=%d, flags=%#x\n",
2761                                algo, j, template[i].setkey_error, ret,
2762                                crypto_cipher_get_flags(tfm));
2763                         goto out;
2764                 }
2765                 if (template[i].setkey_error) {
2766                         pr_err("alg: cipher: %s setkey unexpectedly succeeded on test vector %u; expected_error=%d\n",
2767                                algo, j, template[i].setkey_error);
2768                         ret = -EINVAL;
2769                         goto out;
2770                 }
2771
2772                 for (k = 0; k < template[i].len;
2773                      k += crypto_cipher_blocksize(tfm)) {
2774                         if (enc)
2775                                 crypto_cipher_encrypt_one(tfm, data + k,
2776                                                           data + k);
2777                         else
2778                                 crypto_cipher_decrypt_one(tfm, data + k,
2779                                                           data + k);
2780                 }
2781
2782                 q = data;
2783                 if (memcmp(q, result, template[i].len)) {
2784                         printk(KERN_ERR "alg: cipher: Test %d failed "
2785                                "on %s for %s\n", j, e, algo);
2786                         hexdump(q, template[i].len);
2787                         ret = -EINVAL;
2788                         goto out;
2789                 }
2790         }
2791
2792         ret = 0;
2793
2794 out:
2795         testmgr_free_buf(xbuf);
2796 out_nobuf:
2797         return ret;
2798 }
2799
2800 static int test_skcipher_vec_cfg(int enc, const struct cipher_testvec *vec,
2801                                  const char *vec_name,
2802                                  const struct testvec_config *cfg,
2803                                  struct skcipher_request *req,
2804                                  struct cipher_test_sglists *tsgls)
2805 {
2806         struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
2807         const unsigned int alignmask = crypto_skcipher_alignmask(tfm);
2808         const unsigned int ivsize = crypto_skcipher_ivsize(tfm);
2809         const char *driver = crypto_skcipher_driver_name(tfm);
2810         const u32 req_flags = CRYPTO_TFM_REQ_MAY_BACKLOG | cfg->req_flags;
2811         const char *op = enc ? "encryption" : "decryption";
2812         DECLARE_CRYPTO_WAIT(wait);
2813         u8 _iv[3 * (MAX_ALGAPI_ALIGNMASK + 1) + MAX_IVLEN];
2814         u8 *iv = PTR_ALIGN(&_iv[0], 2 * (MAX_ALGAPI_ALIGNMASK + 1)) +
2815                  cfg->iv_offset +
2816                  (cfg->iv_offset_relative_to_alignmask ? alignmask : 0);
2817         struct kvec input;
2818         int err;
2819
2820         /* Set the key */
2821         if (vec->wk)
2822                 crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2823         else
2824                 crypto_skcipher_clear_flags(tfm,
2825                                             CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
2826         err = do_setkey(crypto_skcipher_setkey, tfm, vec->key, vec->klen,
2827                         cfg, alignmask);
2828         if (err) {
2829                 if (err == vec->setkey_error)
2830                         return 0;
2831                 pr_err("alg: skcipher: %s setkey failed on test vector %s; expected_error=%d, actual_error=%d, flags=%#x\n",
2832                        driver, vec_name, vec->setkey_error, err,
2833                        crypto_skcipher_get_flags(tfm));
2834                 return err;
2835         }
2836         if (vec->setkey_error) {
2837                 pr_err("alg: skcipher: %s setkey unexpectedly succeeded on test vector %s; expected_error=%d\n",
2838                        driver, vec_name, vec->setkey_error);
2839                 return -EINVAL;
2840         }
2841
2842         /* The IV must be copied to a buffer, as the algorithm may modify it */
2843         if (ivsize) {
2844                 if (WARN_ON(ivsize > MAX_IVLEN))
2845                         return -EINVAL;
2846                 if (vec->generates_iv && !enc)
2847                         memcpy(iv, vec->iv_out, ivsize);
2848                 else if (vec->iv)
2849                         memcpy(iv, vec->iv, ivsize);
2850                 else
2851                         memset(iv, 0, ivsize);
2852         } else {
2853                 if (vec->generates_iv) {
2854                         pr_err("alg: skcipher: %s has ivsize=0 but test vector %s generates IV!\n",
2855                                driver, vec_name);
2856                         return -EINVAL;
2857                 }
2858                 iv = NULL;
2859         }
2860
2861         /* Build the src/dst scatterlists */
2862         input.iov_base = enc ? (void *)vec->ptext : (void *)vec->ctext;
2863         input.iov_len = vec->len;
2864         err = build_cipher_test_sglists(tsgls, cfg, alignmask,
2865                                         vec->len, vec->len, &input, 1);
2866         if (err) {
2867                 pr_err("alg: skcipher: %s %s: error preparing scatterlists for test vector %s, cfg=\"%s\"\n",
2868                        driver, op, vec_name, cfg->name);
2869                 return err;
2870         }
2871
2872         /* Do the actual encryption or decryption */
2873         testmgr_poison(req->__ctx, crypto_skcipher_reqsize(tfm));
2874         skcipher_request_set_callback(req, req_flags, crypto_req_done, &wait);
2875         skcipher_request_set_crypt(req, tsgls->src.sgl_ptr, tsgls->dst.sgl_ptr,
2876                                    vec->len, iv);
2877         if (cfg->nosimd)
2878                 crypto_disable_simd_for_test();
2879         err = enc ? crypto_skcipher_encrypt(req) : crypto_skcipher_decrypt(req);
2880         if (cfg->nosimd)
2881                 crypto_reenable_simd_for_test();
2882         err = crypto_wait_req(err, &wait);
2883
2884         /* Check that the algorithm didn't overwrite things it shouldn't have */
2885         if (req->cryptlen != vec->len ||
2886             req->iv != iv ||
2887             req->src != tsgls->src.sgl_ptr ||
2888             req->dst != tsgls->dst.sgl_ptr ||
2889             crypto_skcipher_reqtfm(req) != tfm ||
2890             req->base.complete != crypto_req_done ||
2891             req->base.flags != req_flags ||
2892             req->base.data != &wait) {
2893                 pr_err("alg: skcipher: %s %s corrupted request struct on test vector %s, cfg=\"%s\"\n",
2894                        driver, op, vec_name, cfg->name);
2895                 if (req->cryptlen != vec->len)
2896                         pr_err("alg: skcipher: changed 'req->cryptlen'\n");
2897                 if (req->iv != iv)
2898                         pr_err("alg: skcipher: changed 'req->iv'\n");
2899                 if (req->src != tsgls->src.sgl_ptr)
2900                         pr_err("alg: skcipher: changed 'req->src'\n");
2901                 if (req->dst != tsgls->dst.sgl_ptr)
2902                         pr_err("alg: skcipher: changed 'req->dst'\n");
2903                 if (crypto_skcipher_reqtfm(req) != tfm)
2904                         pr_err("alg: skcipher: changed 'req->base.tfm'\n");
2905                 if (req->base.complete != crypto_req_done)
2906                         pr_err("alg: skcipher: changed 'req->base.complete'\n");
2907                 if (req->base.flags != req_flags)
2908                         pr_err("alg: skcipher: changed 'req->base.flags'\n");
2909                 if (req->base.data != &wait)
2910                         pr_err("alg: skcipher: changed 'req->base.data'\n");
2911                 return -EINVAL;
2912         }
2913         if (is_test_sglist_corrupted(&tsgls->src)) {
2914                 pr_err("alg: skcipher: %s %s corrupted src sgl on test vector %s, cfg=\"%s\"\n",
2915                        driver, op, vec_name, cfg->name);
2916                 return -EINVAL;
2917         }
2918         if (tsgls->dst.sgl_ptr != tsgls->src.sgl &&
2919             is_test_sglist_corrupted(&tsgls->dst)) {
2920                 pr_err("alg: skcipher: %s %s corrupted dst sgl on test vector %s, cfg=\"%s\"\n",
2921                        driver, op, vec_name, cfg->name);
2922                 return -EINVAL;
2923         }
2924
2925         /* Check for success or failure */
2926         if (err) {
2927                 if (err == vec->crypt_error)
2928                         return 0;
2929                 pr_err("alg: skcipher: %s %s failed on test vector %s; expected_error=%d, actual_error=%d, cfg=\"%s\"\n",
2930                        driver, op, vec_name, vec->crypt_error, err, cfg->name);
2931                 return err;
2932         }
2933         if (vec->crypt_error) {
2934                 pr_err("alg: skcipher: %s %s unexpectedly succeeded on test vector %s; expected_error=%d, cfg=\"%s\"\n",
2935                        driver, op, vec_name, vec->crypt_error, cfg->name);
2936                 return -EINVAL;
2937         }
2938
2939         /* Check for the correct output (ciphertext or plaintext) */
2940         err = verify_correct_output(&tsgls->dst, enc ? vec->ctext : vec->ptext,
2941                                     vec->len, 0, true);
2942         if (err == -EOVERFLOW) {
2943                 pr_err("alg: skcipher: %s %s overran dst buffer on test vector %s, cfg=\"%s\"\n",
2944                        driver, op, vec_name, cfg->name);
2945                 return err;
2946         }
2947         if (err) {
2948                 pr_err("alg: skcipher: %s %s test failed (wrong result) on test vector %s, cfg=\"%s\"\n",
2949                        driver, op, vec_name, cfg->name);
2950                 return err;
2951         }
2952
2953         /* If applicable, check that the algorithm generated the correct IV */
2954         if (vec->iv_out && memcmp(iv, vec->iv_out, ivsize) != 0) {
2955                 pr_err("alg: skcipher: %s %s test failed (wrong output IV) on test vector %s, cfg=\"%s\"\n",
2956                        driver, op, vec_name, cfg->name);
2957                 hexdump(iv, ivsize);
2958                 return -EINVAL;
2959         }
2960
2961         return 0;
2962 }
2963
2964 static int test_skcipher_vec(int enc, const struct cipher_testvec *vec,
2965                              unsigned int vec_num,
2966                              struct skcipher_request *req,
2967                              struct cipher_test_sglists *tsgls)
2968 {
2969         char vec_name[16];
2970         unsigned int i;
2971         int err;
2972
2973         if (fips_enabled && vec->fips_skip)
2974                 return 0;
2975
2976         sprintf(vec_name, "%u", vec_num);
2977
2978         for (i = 0; i < ARRAY_SIZE(default_cipher_testvec_configs); i++) {
2979                 err = test_skcipher_vec_cfg(enc, vec, vec_name,
2980                                             &default_cipher_testvec_configs[i],
2981                                             req, tsgls);
2982                 if (err)
2983                         return err;
2984         }
2985
2986 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
2987         if (!noextratests) {
2988                 struct rnd_state rng;
2989                 struct testvec_config cfg;
2990                 char cfgname[TESTVEC_CONFIG_NAMELEN];
2991
2992                 init_rnd_state(&rng);
2993
2994                 for (i = 0; i < fuzz_iterations; i++) {
2995                         generate_random_testvec_config(&rng, &cfg, cfgname,
2996                                                        sizeof(cfgname));
2997                         err = test_skcipher_vec_cfg(enc, vec, vec_name,
2998                                                     &cfg, req, tsgls);
2999                         if (err)
3000                                 return err;
3001                         cond_resched();
3002                 }
3003         }
3004 #endif
3005         return 0;
3006 }
3007
3008 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
3009 /*
3010  * Generate a symmetric cipher test vector from the given implementation.
3011  * Assumes the buffers in 'vec' were already allocated.
3012  */
3013 static void generate_random_cipher_testvec(struct rnd_state *rng,
3014                                            struct skcipher_request *req,
3015                                            struct cipher_testvec *vec,
3016                                            unsigned int maxdatasize,
3017                                            char *name, size_t max_namelen)
3018 {
3019         struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
3020         const unsigned int maxkeysize = crypto_skcipher_max_keysize(tfm);
3021         const unsigned int ivsize = crypto_skcipher_ivsize(tfm);
3022         struct scatterlist src, dst;
3023         u8 iv[MAX_IVLEN];
3024         DECLARE_CRYPTO_WAIT(wait);
3025
3026         /* Key: length in [0, maxkeysize], but usually choose maxkeysize */
3027         vec->klen = maxkeysize;
3028         if (prandom_u32_below(rng, 4) == 0)
3029                 vec->klen = prandom_u32_below(rng, maxkeysize + 1);
3030         generate_random_bytes(rng, (u8 *)vec->key, vec->klen);
3031         vec->setkey_error = crypto_skcipher_setkey(tfm, vec->key, vec->klen);
3032
3033         /* IV */
3034         generate_random_bytes(rng, (u8 *)vec->iv, ivsize);
3035
3036         /* Plaintext */
3037         vec->len = generate_random_length(rng, maxdatasize);
3038         generate_random_bytes(rng, (u8 *)vec->ptext, vec->len);
3039
3040         /* If the key couldn't be set, no need to continue to encrypt. */
3041         if (vec->setkey_error)
3042                 goto done;
3043
3044         /* Ciphertext */
3045         sg_init_one(&src, vec->ptext, vec->len);
3046         sg_init_one(&dst, vec->ctext, vec->len);
3047         memcpy(iv, vec->iv, ivsize);
3048         skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
3049         skcipher_request_set_crypt(req, &src, &dst, vec->len, iv);
3050         vec->crypt_error = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
3051         if (vec->crypt_error != 0) {
3052                 /*
3053                  * The only acceptable error here is for an invalid length, so
3054                  * skcipher decryption should fail with the same error too.
3055                  * We'll test for this.  But to keep the API usage well-defined,
3056                  * explicitly initialize the ciphertext buffer too.
3057                  */
3058                 memset((u8 *)vec->ctext, 0, vec->len);
3059         }
3060 done:
3061         snprintf(name, max_namelen, "\"random: len=%u klen=%u\"",
3062                  vec->len, vec->klen);
3063 }
3064
3065 /*
3066  * Test the skcipher algorithm represented by @req against the corresponding
3067  * generic implementation, if one is available.
3068  */
3069 static int test_skcipher_vs_generic_impl(const char *generic_driver,
3070                                          struct skcipher_request *req,
3071                                          struct cipher_test_sglists *tsgls)
3072 {
3073         struct crypto_skcipher *tfm = crypto_skcipher_reqtfm(req);
3074         const unsigned int maxkeysize = crypto_skcipher_max_keysize(tfm);
3075         const unsigned int ivsize = crypto_skcipher_ivsize(tfm);
3076         const unsigned int blocksize = crypto_skcipher_blocksize(tfm);
3077         const unsigned int maxdatasize = (2 * PAGE_SIZE) - TESTMGR_POISON_LEN;
3078         const char *algname = crypto_skcipher_alg(tfm)->base.cra_name;
3079         const char *driver = crypto_skcipher_driver_name(tfm);
3080         struct rnd_state rng;
3081         char _generic_driver[CRYPTO_MAX_ALG_NAME];
3082         struct crypto_skcipher *generic_tfm = NULL;
3083         struct skcipher_request *generic_req = NULL;
3084         unsigned int i;
3085         struct cipher_testvec vec = { 0 };
3086         char vec_name[64];
3087         struct testvec_config *cfg;
3088         char cfgname[TESTVEC_CONFIG_NAMELEN];
3089         int err;
3090
3091         if (noextratests)
3092                 return 0;
3093
3094         /* Keywrap isn't supported here yet as it handles its IV differently. */
3095         if (strncmp(algname, "kw(", 3) == 0)
3096                 return 0;
3097
3098         init_rnd_state(&rng);
3099
3100         if (!generic_driver) { /* Use default naming convention? */
3101                 err = build_generic_driver_name(algname, _generic_driver);
3102                 if (err)
3103                         return err;
3104                 generic_driver = _generic_driver;
3105         }
3106
3107         if (strcmp(generic_driver, driver) == 0) /* Already the generic impl? */
3108                 return 0;
3109
3110         generic_tfm = crypto_alloc_skcipher(generic_driver, 0, 0);
3111         if (IS_ERR(generic_tfm)) {
3112                 err = PTR_ERR(generic_tfm);
3113                 if (err == -ENOENT) {
3114                         pr_warn("alg: skcipher: skipping comparison tests for %s because %s is unavailable\n",
3115                                 driver, generic_driver);
3116                         return 0;
3117                 }
3118                 pr_err("alg: skcipher: error allocating %s (generic impl of %s): %d\n",
3119                        generic_driver, algname, err);
3120                 return err;
3121         }
3122
3123         cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
3124         if (!cfg) {
3125                 err = -ENOMEM;
3126                 goto out;
3127         }
3128
3129         generic_req = skcipher_request_alloc(generic_tfm, GFP_KERNEL);
3130         if (!generic_req) {
3131                 err = -ENOMEM;
3132                 goto out;
3133         }
3134
3135         /* Check the algorithm properties for consistency. */
3136
3137         if (crypto_skcipher_min_keysize(tfm) !=
3138             crypto_skcipher_min_keysize(generic_tfm)) {
3139                 pr_err("alg: skcipher: min keysize for %s (%u) doesn't match generic impl (%u)\n",
3140                        driver, crypto_skcipher_min_keysize(tfm),
3141                        crypto_skcipher_min_keysize(generic_tfm));
3142                 err = -EINVAL;
3143                 goto out;
3144         }
3145
3146         if (maxkeysize != crypto_skcipher_max_keysize(generic_tfm)) {
3147                 pr_err("alg: skcipher: max keysize for %s (%u) doesn't match generic impl (%u)\n",
3148                        driver, maxkeysize,
3149                        crypto_skcipher_max_keysize(generic_tfm));
3150                 err = -EINVAL;
3151                 goto out;
3152         }
3153
3154         if (ivsize != crypto_skcipher_ivsize(generic_tfm)) {
3155                 pr_err("alg: skcipher: ivsize for %s (%u) doesn't match generic impl (%u)\n",
3156                        driver, ivsize, crypto_skcipher_ivsize(generic_tfm));
3157                 err = -EINVAL;
3158                 goto out;
3159         }
3160
3161         if (blocksize != crypto_skcipher_blocksize(generic_tfm)) {
3162                 pr_err("alg: skcipher: blocksize for %s (%u) doesn't match generic impl (%u)\n",
3163                        driver, blocksize,
3164                        crypto_skcipher_blocksize(generic_tfm));
3165                 err = -EINVAL;
3166                 goto out;
3167         }
3168
3169         /*
3170          * Now generate test vectors using the generic implementation, and test
3171          * the other implementation against them.
3172          */
3173
3174         vec.key = kmalloc(maxkeysize, GFP_KERNEL);
3175         vec.iv = kmalloc(ivsize, GFP_KERNEL);
3176         vec.ptext = kmalloc(maxdatasize, GFP_KERNEL);
3177         vec.ctext = kmalloc(maxdatasize, GFP_KERNEL);
3178         if (!vec.key || !vec.iv || !vec.ptext || !vec.ctext) {
3179                 err = -ENOMEM;
3180                 goto out;
3181         }
3182
3183         for (i = 0; i < fuzz_iterations * 8; i++) {
3184                 generate_random_cipher_testvec(&rng, generic_req, &vec,
3185                                                maxdatasize,
3186                                                vec_name, sizeof(vec_name));
3187                 generate_random_testvec_config(&rng, cfg, cfgname,
3188                                                sizeof(cfgname));
3189
3190                 err = test_skcipher_vec_cfg(ENCRYPT, &vec, vec_name,
3191                                             cfg, req, tsgls);
3192                 if (err)
3193                         goto out;
3194                 err = test_skcipher_vec_cfg(DECRYPT, &vec, vec_name,
3195                                             cfg, req, tsgls);
3196                 if (err)
3197                         goto out;
3198                 cond_resched();
3199         }
3200         err = 0;
3201 out:
3202         kfree(cfg);
3203         kfree(vec.key);
3204         kfree(vec.iv);
3205         kfree(vec.ptext);
3206         kfree(vec.ctext);
3207         crypto_free_skcipher(generic_tfm);
3208         skcipher_request_free(generic_req);
3209         return err;
3210 }
3211 #else /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
3212 static int test_skcipher_vs_generic_impl(const char *generic_driver,
3213                                          struct skcipher_request *req,
3214                                          struct cipher_test_sglists *tsgls)
3215 {
3216         return 0;
3217 }
3218 #endif /* !CONFIG_CRYPTO_MANAGER_EXTRA_TESTS */
3219
3220 static int test_skcipher(int enc, const struct cipher_test_suite *suite,
3221                          struct skcipher_request *req,
3222                          struct cipher_test_sglists *tsgls)
3223 {
3224         unsigned int i;
3225         int err;
3226
3227         for (i = 0; i < suite->count; i++) {
3228                 err = test_skcipher_vec(enc, &suite->vecs[i], i, req, tsgls);
3229                 if (err)
3230                         return err;
3231                 cond_resched();
3232         }
3233         return 0;
3234 }
3235
3236 static int alg_test_skcipher(const struct alg_test_desc *desc,
3237                              const char *driver, u32 type, u32 mask)
3238 {
3239         const struct cipher_test_suite *suite = &desc->suite.cipher;
3240         struct crypto_skcipher *tfm;
3241         struct skcipher_request *req = NULL;
3242         struct cipher_test_sglists *tsgls = NULL;
3243         int err;
3244
3245         if (suite->count <= 0) {
3246                 pr_err("alg: skcipher: empty test suite for %s\n", driver);
3247                 return -EINVAL;
3248         }
3249
3250         tfm = crypto_alloc_skcipher(driver, type, mask);
3251         if (IS_ERR(tfm)) {
3252                 pr_err("alg: skcipher: failed to allocate transform for %s: %ld\n",
3253                        driver, PTR_ERR(tfm));
3254                 return PTR_ERR(tfm);
3255         }
3256         driver = crypto_skcipher_driver_name(tfm);
3257
3258         req = skcipher_request_alloc(tfm, GFP_KERNEL);
3259         if (!req) {
3260                 pr_err("alg: skcipher: failed to allocate request for %s\n",
3261                        driver);
3262                 err = -ENOMEM;
3263                 goto out;
3264         }
3265
3266         tsgls = alloc_cipher_test_sglists();
3267         if (!tsgls) {
3268                 pr_err("alg: skcipher: failed to allocate test buffers for %s\n",
3269                        driver);
3270                 err = -ENOMEM;
3271                 goto out;
3272         }
3273
3274         err = test_skcipher(ENCRYPT, suite, req, tsgls);
3275         if (err)
3276                 goto out;
3277
3278         err = test_skcipher(DECRYPT, suite, req, tsgls);
3279         if (err)
3280                 goto out;
3281
3282         err = test_skcipher_vs_generic_impl(desc->generic_driver, req, tsgls);
3283 out:
3284         free_cipher_test_sglists(tsgls);
3285         skcipher_request_free(req);
3286         crypto_free_skcipher(tfm);
3287         return err;
3288 }
3289
3290 static int test_comp(struct crypto_comp *tfm,
3291                      const struct comp_testvec *ctemplate,
3292                      const struct comp_testvec *dtemplate,
3293                      int ctcount, int dtcount)
3294 {
3295         const char *algo = crypto_tfm_alg_driver_name(crypto_comp_tfm(tfm));
3296         char *output, *decomp_output;
3297         unsigned int i;
3298         int ret;
3299
3300         output = kmalloc(COMP_BUF_SIZE, GFP_KERNEL);
3301         if (!output)
3302                 return -ENOMEM;
3303
3304         decomp_output = kmalloc(COMP_BUF_SIZE, GFP_KERNEL);
3305         if (!decomp_output) {
3306                 kfree(output);
3307                 return -ENOMEM;
3308         }
3309
3310         for (i = 0; i < ctcount; i++) {
3311                 int ilen;
3312                 unsigned int dlen = COMP_BUF_SIZE;
3313
3314                 memset(output, 0, COMP_BUF_SIZE);
3315                 memset(decomp_output, 0, COMP_BUF_SIZE);
3316
3317                 ilen = ctemplate[i].inlen;
3318                 ret = crypto_comp_compress(tfm, ctemplate[i].input,
3319                                            ilen, output, &dlen);
3320                 if (ret) {
3321                         printk(KERN_ERR "alg: comp: compression failed "
3322                                "on test %d for %s: ret=%d\n", i + 1, algo,
3323                                -ret);
3324                         goto out;
3325                 }
3326
3327                 ilen = dlen;
3328                 dlen = COMP_BUF_SIZE;
3329                 ret = crypto_comp_decompress(tfm, output,
3330                                              ilen, decomp_output, &dlen);
3331                 if (ret) {
3332                         pr_err("alg: comp: compression failed: decompress: on test %d for %s failed: ret=%d\n",
3333                                i + 1, algo, -ret);
3334                         goto out;
3335                 }
3336
3337                 if (dlen != ctemplate[i].inlen) {
3338                         printk(KERN_ERR "alg: comp: Compression test %d "
3339                                "failed for %s: output len = %d\n", i + 1, algo,
3340                                dlen);
3341                         ret = -EINVAL;
3342                         goto out;
3343                 }
3344
3345                 if (memcmp(decomp_output, ctemplate[i].input,
3346                            ctemplate[i].inlen)) {
3347                         pr_err("alg: comp: compression failed: output differs: on test %d for %s\n",
3348                                i + 1, algo);
3349                         hexdump(decomp_output, dlen);
3350                         ret = -EINVAL;
3351                         goto out;
3352                 }
3353         }
3354
3355         for (i = 0; i < dtcount; i++) {
3356                 int ilen;
3357                 unsigned int dlen = COMP_BUF_SIZE;
3358
3359                 memset(decomp_output, 0, COMP_BUF_SIZE);
3360
3361                 ilen = dtemplate[i].inlen;
3362                 ret = crypto_comp_decompress(tfm, dtemplate[i].input,
3363                                              ilen, decomp_output, &dlen);
3364                 if (ret) {
3365                         printk(KERN_ERR "alg: comp: decompression failed "
3366                                "on test %d for %s: ret=%d\n", i + 1, algo,
3367                                -ret);
3368                         goto out;
3369                 }
3370
3371                 if (dlen != dtemplate[i].outlen) {
3372                         printk(KERN_ERR "alg: comp: Decompression test %d "
3373                                "failed for %s: output len = %d\n", i + 1, algo,
3374                                dlen);
3375                         ret = -EINVAL;
3376                         goto out;
3377                 }
3378
3379                 if (memcmp(decomp_output, dtemplate[i].output, dlen)) {
3380                         printk(KERN_ERR "alg: comp: Decompression test %d "
3381                                "failed for %s\n", i + 1, algo);
3382                         hexdump(decomp_output, dlen);
3383                         ret = -EINVAL;
3384                         goto out;
3385                 }
3386         }
3387
3388         ret = 0;
3389
3390 out:
3391         kfree(decomp_output);
3392         kfree(output);
3393         return ret;
3394 }
3395
3396 static int test_acomp(struct crypto_acomp *tfm,
3397                       const struct comp_testvec *ctemplate,
3398                       const struct comp_testvec *dtemplate,
3399                       int ctcount, int dtcount)
3400 {
3401         const char *algo = crypto_tfm_alg_driver_name(crypto_acomp_tfm(tfm));
3402         unsigned int i;
3403         char *output, *decomp_out;
3404         int ret;
3405         struct scatterlist src, dst;
3406         struct acomp_req *req;
3407         struct crypto_wait wait;
3408
3409         output = kmalloc(COMP_BUF_SIZE, GFP_KERNEL);
3410         if (!output)
3411                 return -ENOMEM;
3412
3413         decomp_out = kmalloc(COMP_BUF_SIZE, GFP_KERNEL);
3414         if (!decomp_out) {
3415                 kfree(output);
3416                 return -ENOMEM;
3417         }
3418
3419         for (i = 0; i < ctcount; i++) {
3420                 unsigned int dlen = COMP_BUF_SIZE;
3421                 int ilen = ctemplate[i].inlen;
3422                 void *input_vec;
3423
3424                 input_vec = kmemdup(ctemplate[i].input, ilen, GFP_KERNEL);
3425                 if (!input_vec) {
3426                         ret = -ENOMEM;
3427                         goto out;
3428                 }
3429
3430                 memset(output, 0, dlen);
3431                 crypto_init_wait(&wait);
3432                 sg_init_one(&src, input_vec, ilen);
3433                 sg_init_one(&dst, output, dlen);
3434
3435                 req = acomp_request_alloc(tfm);
3436                 if (!req) {
3437                         pr_err("alg: acomp: request alloc failed for %s\n",
3438                                algo);
3439                         kfree(input_vec);
3440                         ret = -ENOMEM;
3441                         goto out;
3442                 }
3443
3444                 acomp_request_set_params(req, &src, &dst, ilen, dlen);
3445                 acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3446                                            crypto_req_done, &wait);
3447
3448                 ret = crypto_wait_req(crypto_acomp_compress(req), &wait);
3449                 if (ret) {
3450                         pr_err("alg: acomp: compression failed on test %d for %s: ret=%d\n",
3451                                i + 1, algo, -ret);
3452                         kfree(input_vec);
3453                         acomp_request_free(req);
3454                         goto out;
3455                 }
3456
3457                 ilen = req->dlen;
3458                 dlen = COMP_BUF_SIZE;
3459                 sg_init_one(&src, output, ilen);
3460                 sg_init_one(&dst, decomp_out, dlen);
3461                 crypto_init_wait(&wait);
3462                 acomp_request_set_params(req, &src, &dst, ilen, dlen);
3463
3464                 ret = crypto_wait_req(crypto_acomp_decompress(req), &wait);
3465                 if (ret) {
3466                         pr_err("alg: acomp: compression failed on test %d for %s: ret=%d\n",
3467                                i + 1, algo, -ret);
3468                         kfree(input_vec);
3469                         acomp_request_free(req);
3470                         goto out;
3471                 }
3472
3473                 if (req->dlen != ctemplate[i].inlen) {
3474                         pr_err("alg: acomp: Compression test %d failed for %s: output len = %d\n",
3475                                i + 1, algo, req->dlen);
3476                         ret = -EINVAL;
3477                         kfree(input_vec);
3478                         acomp_request_free(req);
3479                         goto out;
3480                 }
3481
3482                 if (memcmp(input_vec, decomp_out, req->dlen)) {
3483                         pr_err("alg: acomp: Compression test %d failed for %s\n",
3484                                i + 1, algo);
3485                         hexdump(output, req->dlen);
3486                         ret = -EINVAL;
3487                         kfree(input_vec);
3488                         acomp_request_free(req);
3489                         goto out;
3490                 }
3491
3492 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
3493                 crypto_init_wait(&wait);
3494                 sg_init_one(&src, input_vec, ilen);
3495                 acomp_request_set_params(req, &src, NULL, ilen, 0);
3496
3497                 ret = crypto_wait_req(crypto_acomp_compress(req), &wait);
3498                 if (ret) {
3499                         pr_err("alg: acomp: compression failed on NULL dst buffer test %d for %s: ret=%d\n",
3500                                i + 1, algo, -ret);
3501                         kfree(input_vec);
3502                         acomp_request_free(req);
3503                         goto out;
3504                 }
3505 #endif
3506
3507                 kfree(input_vec);
3508                 acomp_request_free(req);
3509         }
3510
3511         for (i = 0; i < dtcount; i++) {
3512                 unsigned int dlen = COMP_BUF_SIZE;
3513                 int ilen = dtemplate[i].inlen;
3514                 void *input_vec;
3515
3516                 input_vec = kmemdup(dtemplate[i].input, ilen, GFP_KERNEL);
3517                 if (!input_vec) {
3518                         ret = -ENOMEM;
3519                         goto out;
3520                 }
3521
3522                 memset(output, 0, dlen);
3523                 crypto_init_wait(&wait);
3524                 sg_init_one(&src, input_vec, ilen);
3525                 sg_init_one(&dst, output, dlen);
3526
3527                 req = acomp_request_alloc(tfm);
3528                 if (!req) {
3529                         pr_err("alg: acomp: request alloc failed for %s\n",
3530                                algo);
3531                         kfree(input_vec);
3532                         ret = -ENOMEM;
3533                         goto out;
3534                 }
3535
3536                 acomp_request_set_params(req, &src, &dst, ilen, dlen);
3537                 acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3538                                            crypto_req_done, &wait);
3539
3540                 ret = crypto_wait_req(crypto_acomp_decompress(req), &wait);
3541                 if (ret) {
3542                         pr_err("alg: acomp: decompression failed on test %d for %s: ret=%d\n",
3543                                i + 1, algo, -ret);
3544                         kfree(input_vec);
3545                         acomp_request_free(req);
3546                         goto out;
3547                 }
3548
3549                 if (req->dlen != dtemplate[i].outlen) {
3550                         pr_err("alg: acomp: Decompression test %d failed for %s: output len = %d\n",
3551                                i + 1, algo, req->dlen);
3552                         ret = -EINVAL;
3553                         kfree(input_vec);
3554                         acomp_request_free(req);
3555                         goto out;
3556                 }
3557
3558                 if (memcmp(output, dtemplate[i].output, req->dlen)) {
3559                         pr_err("alg: acomp: Decompression test %d failed for %s\n",
3560                                i + 1, algo);
3561                         hexdump(output, req->dlen);
3562                         ret = -EINVAL;
3563                         kfree(input_vec);
3564                         acomp_request_free(req);
3565                         goto out;
3566                 }
3567
3568 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
3569                 crypto_init_wait(&wait);
3570                 acomp_request_set_params(req, &src, NULL, ilen, 0);
3571
3572                 ret = crypto_wait_req(crypto_acomp_decompress(req), &wait);
3573                 if (ret) {
3574                         pr_err("alg: acomp: decompression failed on NULL dst buffer test %d for %s: ret=%d\n",
3575                                i + 1, algo, -ret);
3576                         kfree(input_vec);
3577                         acomp_request_free(req);
3578                         goto out;
3579                 }
3580 #endif
3581
3582                 kfree(input_vec);
3583                 acomp_request_free(req);
3584         }
3585
3586         ret = 0;
3587
3588 out:
3589         kfree(decomp_out);
3590         kfree(output);
3591         return ret;
3592 }
3593
3594 static int test_cprng(struct crypto_rng *tfm,
3595                       const struct cprng_testvec *template,
3596                       unsigned int tcount)
3597 {
3598         const char *algo = crypto_tfm_alg_driver_name(crypto_rng_tfm(tfm));
3599         int err = 0, i, j, seedsize;
3600         u8 *seed;
3601         char result[32];
3602
3603         seedsize = crypto_rng_seedsize(tfm);
3604
3605         seed = kmalloc(seedsize, GFP_KERNEL);
3606         if (!seed) {
3607                 printk(KERN_ERR "alg: cprng: Failed to allocate seed space "
3608                        "for %s\n", algo);
3609                 return -ENOMEM;
3610         }
3611
3612         for (i = 0; i < tcount; i++) {
3613                 memset(result, 0, 32);
3614
3615                 memcpy(seed, template[i].v, template[i].vlen);
3616                 memcpy(seed + template[i].vlen, template[i].key,
3617                        template[i].klen);
3618                 memcpy(seed + template[i].vlen + template[i].klen,
3619                        template[i].dt, template[i].dtlen);
3620
3621                 err = crypto_rng_reset(tfm, seed, seedsize);
3622                 if (err) {
3623                         printk(KERN_ERR "alg: cprng: Failed to reset rng "
3624                                "for %s\n", algo);
3625                         goto out;
3626                 }
3627
3628                 for (j = 0; j < template[i].loops; j++) {
3629                         err = crypto_rng_get_bytes(tfm, result,
3630                                                    template[i].rlen);
3631                         if (err < 0) {
3632                                 printk(KERN_ERR "alg: cprng: Failed to obtain "
3633                                        "the correct amount of random data for "
3634                                        "%s (requested %d)\n", algo,
3635                                        template[i].rlen);
3636                                 goto out;
3637                         }
3638                 }
3639
3640                 err = memcmp(result, template[i].result,
3641                              template[i].rlen);
3642                 if (err) {
3643                         printk(KERN_ERR "alg: cprng: Test %d failed for %s\n",
3644                                i, algo);
3645                         hexdump(result, template[i].rlen);
3646                         err = -EINVAL;
3647                         goto out;
3648                 }
3649         }
3650
3651 out:
3652         kfree(seed);
3653         return err;
3654 }
3655
3656 static int alg_test_cipher(const struct alg_test_desc *desc,
3657                            const char *driver, u32 type, u32 mask)
3658 {
3659         const struct cipher_test_suite *suite = &desc->suite.cipher;
3660         struct crypto_cipher *tfm;
3661         int err;
3662
3663         tfm = crypto_alloc_cipher(driver, type, mask);
3664         if (IS_ERR(tfm)) {
3665                 printk(KERN_ERR "alg: cipher: Failed to load transform for "
3666                        "%s: %ld\n", driver, PTR_ERR(tfm));
3667                 return PTR_ERR(tfm);
3668         }
3669
3670         err = test_cipher(tfm, ENCRYPT, suite->vecs, suite->count);
3671         if (!err)
3672                 err = test_cipher(tfm, DECRYPT, suite->vecs, suite->count);
3673
3674         crypto_free_cipher(tfm);
3675         return err;
3676 }
3677
3678 static int alg_test_comp(const struct alg_test_desc *desc, const char *driver,
3679                          u32 type, u32 mask)
3680 {
3681         struct crypto_comp *comp;
3682         struct crypto_acomp *acomp;
3683         int err;
3684         u32 algo_type = type & CRYPTO_ALG_TYPE_ACOMPRESS_MASK;
3685
3686         if (algo_type == CRYPTO_ALG_TYPE_ACOMPRESS) {
3687                 acomp = crypto_alloc_acomp(driver, type, mask);
3688                 if (IS_ERR(acomp)) {
3689                         pr_err("alg: acomp: Failed to load transform for %s: %ld\n",
3690                                driver, PTR_ERR(acomp));
3691                         return PTR_ERR(acomp);
3692                 }
3693                 err = test_acomp(acomp, desc->suite.comp.comp.vecs,
3694                                  desc->suite.comp.decomp.vecs,
3695                                  desc->suite.comp.comp.count,
3696                                  desc->suite.comp.decomp.count);
3697                 crypto_free_acomp(acomp);
3698         } else {
3699                 comp = crypto_alloc_comp(driver, type, mask);
3700                 if (IS_ERR(comp)) {
3701                         pr_err("alg: comp: Failed to load transform for %s: %ld\n",
3702                                driver, PTR_ERR(comp));
3703                         return PTR_ERR(comp);
3704                 }
3705
3706                 err = test_comp(comp, desc->suite.comp.comp.vecs,
3707                                 desc->suite.comp.decomp.vecs,
3708                                 desc->suite.comp.comp.count,
3709                                 desc->suite.comp.decomp.count);
3710
3711                 crypto_free_comp(comp);
3712         }
3713         return err;
3714 }
3715
3716 static int alg_test_crc32c(const struct alg_test_desc *desc,
3717                            const char *driver, u32 type, u32 mask)
3718 {
3719         struct crypto_shash *tfm;
3720         __le32 val;
3721         int err;
3722
3723         err = alg_test_hash(desc, driver, type, mask);
3724         if (err)
3725                 return err;
3726
3727         tfm = crypto_alloc_shash(driver, type, mask);
3728         if (IS_ERR(tfm)) {
3729                 if (PTR_ERR(tfm) == -ENOENT) {
3730                         /*
3731                          * This crc32c implementation is only available through
3732                          * ahash API, not the shash API, so the remaining part
3733                          * of the test is not applicable to it.
3734                          */
3735                         return 0;
3736                 }
3737                 printk(KERN_ERR "alg: crc32c: Failed to load transform for %s: "
3738                        "%ld\n", driver, PTR_ERR(tfm));
3739                 return PTR_ERR(tfm);
3740         }
3741         driver = crypto_shash_driver_name(tfm);
3742
3743         do {
3744                 SHASH_DESC_ON_STACK(shash, tfm);
3745                 u32 *ctx = (u32 *)shash_desc_ctx(shash);
3746
3747                 shash->tfm = tfm;
3748
3749                 *ctx = 420553207;
3750                 err = crypto_shash_final(shash, (u8 *)&val);
3751                 if (err) {
3752                         printk(KERN_ERR "alg: crc32c: Operation failed for "
3753                                "%s: %d\n", driver, err);
3754                         break;
3755                 }
3756
3757                 if (val != cpu_to_le32(~420553207)) {
3758                         pr_err("alg: crc32c: Test failed for %s: %u\n",
3759                                driver, le32_to_cpu(val));
3760                         err = -EINVAL;
3761                 }
3762         } while (0);
3763
3764         crypto_free_shash(tfm);
3765
3766         return err;
3767 }
3768
3769 static int alg_test_cprng(const struct alg_test_desc *desc, const char *driver,
3770                           u32 type, u32 mask)
3771 {
3772         struct crypto_rng *rng;
3773         int err;
3774
3775         rng = crypto_alloc_rng(driver, type, mask);
3776         if (IS_ERR(rng)) {
3777                 printk(KERN_ERR "alg: cprng: Failed to load transform for %s: "
3778                        "%ld\n", driver, PTR_ERR(rng));
3779                 return PTR_ERR(rng);
3780         }
3781
3782         err = test_cprng(rng, desc->suite.cprng.vecs, desc->suite.cprng.count);
3783
3784         crypto_free_rng(rng);
3785
3786         return err;
3787 }
3788
3789
3790 static int drbg_cavs_test(const struct drbg_testvec *test, int pr,
3791                           const char *driver, u32 type, u32 mask)
3792 {
3793         int ret = -EAGAIN;
3794         struct crypto_rng *drng;
3795         struct drbg_test_data test_data;
3796         struct drbg_string addtl, pers, testentropy;
3797         unsigned char *buf = kzalloc(test->expectedlen, GFP_KERNEL);
3798
3799         if (!buf)
3800                 return -ENOMEM;
3801
3802         drng = crypto_alloc_rng(driver, type, mask);
3803         if (IS_ERR(drng)) {
3804                 printk(KERN_ERR "alg: drbg: could not allocate DRNG handle for "
3805                        "%s\n", driver);
3806                 kfree_sensitive(buf);
3807                 return -ENOMEM;
3808         }
3809
3810         test_data.testentropy = &testentropy;
3811         drbg_string_fill(&testentropy, test->entropy, test->entropylen);
3812         drbg_string_fill(&pers, test->pers, test->perslen);
3813         ret = crypto_drbg_reset_test(drng, &pers, &test_data);
3814         if (ret) {
3815                 printk(KERN_ERR "alg: drbg: Failed to reset rng\n");
3816                 goto outbuf;
3817         }
3818
3819         drbg_string_fill(&addtl, test->addtla, test->addtllen);
3820         if (pr) {
3821                 drbg_string_fill(&testentropy, test->entpra, test->entprlen);
3822                 ret = crypto_drbg_get_bytes_addtl_test(drng,
3823                         buf, test->expectedlen, &addtl, &test_data);
3824         } else {
3825                 ret = crypto_drbg_get_bytes_addtl(drng,
3826                         buf, test->expectedlen, &addtl);
3827         }
3828         if (ret < 0) {
3829                 printk(KERN_ERR "alg: drbg: could not obtain random data for "
3830                        "driver %s\n", driver);
3831                 goto outbuf;
3832         }
3833
3834         drbg_string_fill(&addtl, test->addtlb, test->addtllen);
3835         if (pr) {
3836                 drbg_string_fill(&testentropy, test->entprb, test->entprlen);
3837                 ret = crypto_drbg_get_bytes_addtl_test(drng,
3838                         buf, test->expectedlen, &addtl, &test_data);
3839         } else {
3840                 ret = crypto_drbg_get_bytes_addtl(drng,
3841                         buf, test->expectedlen, &addtl);
3842         }
3843         if (ret < 0) {
3844                 printk(KERN_ERR "alg: drbg: could not obtain random data for "
3845                        "driver %s\n", driver);
3846                 goto outbuf;
3847         }
3848
3849         ret = memcmp(test->expected, buf, test->expectedlen);
3850
3851 outbuf:
3852         crypto_free_rng(drng);
3853         kfree_sensitive(buf);
3854         return ret;
3855 }
3856
3857
3858 static int alg_test_drbg(const struct alg_test_desc *desc, const char *driver,
3859                          u32 type, u32 mask)
3860 {
3861         int err = 0;
3862         int pr = 0;
3863         int i = 0;
3864         const struct drbg_testvec *template = desc->suite.drbg.vecs;
3865         unsigned int tcount = desc->suite.drbg.count;
3866
3867         if (0 == memcmp(driver, "drbg_pr_", 8))
3868                 pr = 1;
3869
3870         for (i = 0; i < tcount; i++) {
3871                 err = drbg_cavs_test(&template[i], pr, driver, type, mask);
3872                 if (err) {
3873                         printk(KERN_ERR "alg: drbg: Test %d failed for %s\n",
3874                                i, driver);
3875                         err = -EINVAL;
3876                         break;
3877                 }
3878         }
3879         return err;
3880
3881 }
3882
3883 static int do_test_kpp(struct crypto_kpp *tfm, const struct kpp_testvec *vec,
3884                        const char *alg)
3885 {
3886         struct kpp_request *req;
3887         void *input_buf = NULL;
3888         void *output_buf = NULL;
3889         void *a_public = NULL;
3890         void *a_ss = NULL;
3891         void *shared_secret = NULL;
3892         struct crypto_wait wait;
3893         unsigned int out_len_max;
3894         int err = -ENOMEM;
3895         struct scatterlist src, dst;
3896
3897         req = kpp_request_alloc(tfm, GFP_KERNEL);
3898         if (!req)
3899                 return err;
3900
3901         crypto_init_wait(&wait);
3902
3903         err = crypto_kpp_set_secret(tfm, vec->secret, vec->secret_size);
3904         if (err < 0)
3905                 goto free_req;
3906
3907         out_len_max = crypto_kpp_maxsize(tfm);
3908         output_buf = kzalloc(out_len_max, GFP_KERNEL);
3909         if (!output_buf) {
3910                 err = -ENOMEM;
3911                 goto free_req;
3912         }
3913
3914         /* Use appropriate parameter as base */
3915         kpp_request_set_input(req, NULL, 0);
3916         sg_init_one(&dst, output_buf, out_len_max);
3917         kpp_request_set_output(req, &dst, out_len_max);
3918         kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3919                                  crypto_req_done, &wait);
3920
3921         /* Compute party A's public key */
3922         err = crypto_wait_req(crypto_kpp_generate_public_key(req), &wait);
3923         if (err) {
3924                 pr_err("alg: %s: Party A: generate public key test failed. err %d\n",
3925                        alg, err);
3926                 goto free_output;
3927         }
3928
3929         if (vec->genkey) {
3930                 /* Save party A's public key */
3931                 a_public = kmemdup(sg_virt(req->dst), out_len_max, GFP_KERNEL);
3932                 if (!a_public) {
3933                         err = -ENOMEM;
3934                         goto free_output;
3935                 }
3936         } else {
3937                 /* Verify calculated public key */
3938                 if (memcmp(vec->expected_a_public, sg_virt(req->dst),
3939                            vec->expected_a_public_size)) {
3940                         pr_err("alg: %s: Party A: generate public key test failed. Invalid output\n",
3941                                alg);
3942                         err = -EINVAL;
3943                         goto free_output;
3944                 }
3945         }
3946
3947         /* Calculate shared secret key by using counter part (b) public key. */
3948         input_buf = kmemdup(vec->b_public, vec->b_public_size, GFP_KERNEL);
3949         if (!input_buf) {
3950                 err = -ENOMEM;
3951                 goto free_output;
3952         }
3953
3954         sg_init_one(&src, input_buf, vec->b_public_size);
3955         sg_init_one(&dst, output_buf, out_len_max);
3956         kpp_request_set_input(req, &src, vec->b_public_size);
3957         kpp_request_set_output(req, &dst, out_len_max);
3958         kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3959                                  crypto_req_done, &wait);
3960         err = crypto_wait_req(crypto_kpp_compute_shared_secret(req), &wait);
3961         if (err) {
3962                 pr_err("alg: %s: Party A: compute shared secret test failed. err %d\n",
3963                        alg, err);
3964                 goto free_all;
3965         }
3966
3967         if (vec->genkey) {
3968                 /* Save the shared secret obtained by party A */
3969                 a_ss = kmemdup(sg_virt(req->dst), vec->expected_ss_size, GFP_KERNEL);
3970                 if (!a_ss) {
3971                         err = -ENOMEM;
3972                         goto free_all;
3973                 }
3974
3975                 /*
3976                  * Calculate party B's shared secret by using party A's
3977                  * public key.
3978                  */
3979                 err = crypto_kpp_set_secret(tfm, vec->b_secret,
3980                                             vec->b_secret_size);
3981                 if (err < 0)
3982                         goto free_all;
3983
3984                 sg_init_one(&src, a_public, vec->expected_a_public_size);
3985                 sg_init_one(&dst, output_buf, out_len_max);
3986                 kpp_request_set_input(req, &src, vec->expected_a_public_size);
3987                 kpp_request_set_output(req, &dst, out_len_max);
3988                 kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
3989                                          crypto_req_done, &wait);
3990                 err = crypto_wait_req(crypto_kpp_compute_shared_secret(req),
3991                                       &wait);
3992                 if (err) {
3993                         pr_err("alg: %s: Party B: compute shared secret failed. err %d\n",
3994                                alg, err);
3995                         goto free_all;
3996                 }
3997
3998                 shared_secret = a_ss;
3999         } else {
4000                 shared_secret = (void *)vec->expected_ss;
4001         }
4002
4003         /*
4004          * verify shared secret from which the user will derive
4005          * secret key by executing whatever hash it has chosen
4006          */
4007         if (memcmp(shared_secret, sg_virt(req->dst),
4008                    vec->expected_ss_size)) {
4009                 pr_err("alg: %s: compute shared secret test failed. Invalid output\n",
4010                        alg);
4011                 err = -EINVAL;
4012         }
4013
4014 free_all:
4015         kfree(a_ss);
4016         kfree(input_buf);
4017 free_output:
4018         kfree(a_public);
4019         kfree(output_buf);
4020 free_req:
4021         kpp_request_free(req);
4022         return err;
4023 }
4024
4025 static int test_kpp(struct crypto_kpp *tfm, const char *alg,
4026                     const struct kpp_testvec *vecs, unsigned int tcount)
4027 {
4028         int ret, i;
4029
4030         for (i = 0; i < tcount; i++) {
4031                 ret = do_test_kpp(tfm, vecs++, alg);
4032                 if (ret) {
4033                         pr_err("alg: %s: test failed on vector %d, err=%d\n",
4034                                alg, i + 1, ret);
4035                         return ret;
4036                 }
4037         }
4038         return 0;
4039 }
4040
4041 static int alg_test_kpp(const struct alg_test_desc *desc, const char *driver,
4042                         u32 type, u32 mask)
4043 {
4044         struct crypto_kpp *tfm;
4045         int err = 0;
4046
4047         tfm = crypto_alloc_kpp(driver, type, mask);
4048         if (IS_ERR(tfm)) {
4049                 pr_err("alg: kpp: Failed to load tfm for %s: %ld\n",
4050                        driver, PTR_ERR(tfm));
4051                 return PTR_ERR(tfm);
4052         }
4053         if (desc->suite.kpp.vecs)
4054                 err = test_kpp(tfm, desc->alg, desc->suite.kpp.vecs,
4055                                desc->suite.kpp.count);
4056
4057         crypto_free_kpp(tfm);
4058         return err;
4059 }
4060
4061 static u8 *test_pack_u32(u8 *dst, u32 val)
4062 {
4063         memcpy(dst, &val, sizeof(val));
4064         return dst + sizeof(val);
4065 }
4066
4067 static int test_akcipher_one(struct crypto_akcipher *tfm,
4068                              const struct akcipher_testvec *vecs)
4069 {
4070         char *xbuf[XBUFSIZE];
4071         struct akcipher_request *req;
4072         void *outbuf_enc = NULL;
4073         void *outbuf_dec = NULL;
4074         struct crypto_wait wait;
4075         unsigned int out_len_max, out_len = 0;
4076         int err = -ENOMEM;
4077         struct scatterlist src, dst, src_tab[3];
4078         const char *m, *c;
4079         unsigned int m_size, c_size;
4080         const char *op;
4081         u8 *key, *ptr;
4082
4083         if (testmgr_alloc_buf(xbuf))
4084                 return err;
4085
4086         req = akcipher_request_alloc(tfm, GFP_KERNEL);
4087         if (!req)
4088                 goto free_xbuf;
4089
4090         crypto_init_wait(&wait);
4091
4092         key = kmalloc(vecs->key_len + sizeof(u32) * 2 + vecs->param_len,
4093                       GFP_KERNEL);
4094         if (!key)
4095                 goto free_req;
4096         memcpy(key, vecs->key, vecs->key_len);
4097         ptr = key + vecs->key_len;
4098         ptr = test_pack_u32(ptr, vecs->algo);
4099         ptr = test_pack_u32(ptr, vecs->param_len);
4100         memcpy(ptr, vecs->params, vecs->param_len);
4101
4102         if (vecs->public_key_vec)
4103                 err = crypto_akcipher_set_pub_key(tfm, key, vecs->key_len);
4104         else
4105                 err = crypto_akcipher_set_priv_key(tfm, key, vecs->key_len);
4106         if (err)
4107                 goto free_key;
4108
4109         /*
4110          * First run test which do not require a private key, such as
4111          * encrypt or verify.
4112          */
4113         err = -ENOMEM;
4114         out_len_max = crypto_akcipher_maxsize(tfm);
4115         outbuf_enc = kzalloc(out_len_max, GFP_KERNEL);
4116         if (!outbuf_enc)
4117                 goto free_key;
4118
4119         if (!vecs->siggen_sigver_test) {
4120                 m = vecs->m;
4121                 m_size = vecs->m_size;
4122                 c = vecs->c;
4123                 c_size = vecs->c_size;
4124                 op = "encrypt";
4125         } else {
4126                 /* Swap args so we could keep plaintext (digest)
4127                  * in vecs->m, and cooked signature in vecs->c.
4128                  */
4129                 m = vecs->c; /* signature */
4130                 m_size = vecs->c_size;
4131                 c = vecs->m; /* digest */
4132                 c_size = vecs->m_size;
4133                 op = "verify";
4134         }
4135
4136         err = -E2BIG;
4137         if (WARN_ON(m_size > PAGE_SIZE))
4138                 goto free_all;
4139         memcpy(xbuf[0], m, m_size);
4140
4141         sg_init_table(src_tab, 3);
4142         sg_set_buf(&src_tab[0], xbuf[0], 8);
4143         sg_set_buf(&src_tab[1], xbuf[0] + 8, m_size - 8);
4144         if (vecs->siggen_sigver_test) {
4145                 if (WARN_ON(c_size > PAGE_SIZE))
4146                         goto free_all;
4147                 memcpy(xbuf[1], c, c_size);
4148                 sg_set_buf(&src_tab[2], xbuf[1], c_size);
4149                 akcipher_request_set_crypt(req, src_tab, NULL, m_size, c_size);
4150         } else {
4151                 sg_init_one(&dst, outbuf_enc, out_len_max);
4152                 akcipher_request_set_crypt(req, src_tab, &dst, m_size,
4153                                            out_len_max);
4154         }
4155         akcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
4156                                       crypto_req_done, &wait);
4157
4158         err = crypto_wait_req(vecs->siggen_sigver_test ?
4159                               /* Run asymmetric signature verification */
4160                               crypto_akcipher_verify(req) :
4161                               /* Run asymmetric encrypt */
4162                               crypto_akcipher_encrypt(req), &wait);
4163         if (err) {
4164                 pr_err("alg: akcipher: %s test failed. err %d\n", op, err);
4165                 goto free_all;
4166         }
4167         if (!vecs->siggen_sigver_test && c) {
4168                 if (req->dst_len != c_size) {
4169                         pr_err("alg: akcipher: %s test failed. Invalid output len\n",
4170                                op);
4171                         err = -EINVAL;
4172                         goto free_all;
4173                 }
4174                 /* verify that encrypted message is equal to expected */
4175                 if (memcmp(c, outbuf_enc, c_size) != 0) {
4176                         pr_err("alg: akcipher: %s test failed. Invalid output\n",
4177                                op);
4178                         hexdump(outbuf_enc, c_size);
4179                         err = -EINVAL;
4180                         goto free_all;
4181                 }
4182         }
4183
4184         /*
4185          * Don't invoke (decrypt or sign) test which require a private key
4186          * for vectors with only a public key.
4187          */
4188         if (vecs->public_key_vec) {
4189                 err = 0;
4190                 goto free_all;
4191         }
4192         outbuf_dec = kzalloc(out_len_max, GFP_KERNEL);
4193         if (!outbuf_dec) {
4194                 err = -ENOMEM;
4195                 goto free_all;
4196         }
4197
4198         if (!vecs->siggen_sigver_test && !c) {
4199                 c = outbuf_enc;
4200                 c_size = req->dst_len;
4201         }
4202
4203         err = -E2BIG;
4204         op = vecs->siggen_sigver_test ? "sign" : "decrypt";
4205         if (WARN_ON(c_size > PAGE_SIZE))
4206                 goto free_all;
4207         memcpy(xbuf[0], c, c_size);
4208
4209         sg_init_one(&src, xbuf[0], c_size);
4210         sg_init_one(&dst, outbuf_dec, out_len_max);
4211         crypto_init_wait(&wait);
4212         akcipher_request_set_crypt(req, &src, &dst, c_size, out_len_max);
4213
4214         err = crypto_wait_req(vecs->siggen_sigver_test ?
4215                               /* Run asymmetric signature generation */
4216                               crypto_akcipher_sign(req) :
4217                               /* Run asymmetric decrypt */
4218                               crypto_akcipher_decrypt(req), &wait);
4219         if (err) {
4220                 pr_err("alg: akcipher: %s test failed. err %d\n", op, err);
4221                 goto free_all;
4222         }
4223         out_len = req->dst_len;
4224         if (out_len < m_size) {
4225                 pr_err("alg: akcipher: %s test failed. Invalid output len %u\n",
4226                        op, out_len);
4227                 err = -EINVAL;
4228                 goto free_all;
4229         }
4230         /* verify that decrypted message is equal to the original msg */
4231         if (memchr_inv(outbuf_dec, 0, out_len - m_size) ||
4232             memcmp(m, outbuf_dec + out_len - m_size, m_size)) {
4233                 pr_err("alg: akcipher: %s test failed. Invalid output\n", op);
4234                 hexdump(outbuf_dec, out_len);
4235                 err = -EINVAL;
4236         }
4237 free_all:
4238         kfree(outbuf_dec);
4239         kfree(outbuf_enc);
4240 free_key:
4241         kfree(key);
4242 free_req:
4243         akcipher_request_free(req);
4244 free_xbuf:
4245         testmgr_free_buf(xbuf);
4246         return err;
4247 }
4248
4249 static int test_akcipher(struct crypto_akcipher *tfm, const char *alg,
4250                          const struct akcipher_testvec *vecs,
4251                          unsigned int tcount)
4252 {
4253         const char *algo =
4254                 crypto_tfm_alg_driver_name(crypto_akcipher_tfm(tfm));
4255         int ret, i;
4256
4257         for (i = 0; i < tcount; i++) {
4258                 ret = test_akcipher_one(tfm, vecs++);
4259                 if (!ret)
4260                         continue;
4261
4262                 pr_err("alg: akcipher: test %d failed for %s, err=%d\n",
4263                        i + 1, algo, ret);
4264                 return ret;
4265         }
4266         return 0;
4267 }
4268
4269 static int alg_test_akcipher(const struct alg_test_desc *desc,
4270                              const char *driver, u32 type, u32 mask)
4271 {
4272         struct crypto_akcipher *tfm;
4273         int err = 0;
4274
4275         tfm = crypto_alloc_akcipher(driver, type, mask);
4276         if (IS_ERR(tfm)) {
4277                 pr_err("alg: akcipher: Failed to load tfm for %s: %ld\n",
4278                        driver, PTR_ERR(tfm));
4279                 return PTR_ERR(tfm);
4280         }
4281         if (desc->suite.akcipher.vecs)
4282                 err = test_akcipher(tfm, desc->alg, desc->suite.akcipher.vecs,
4283                                     desc->suite.akcipher.count);
4284
4285         crypto_free_akcipher(tfm);
4286         return err;
4287 }
4288
4289 static int alg_test_null(const struct alg_test_desc *desc,
4290                              const char *driver, u32 type, u32 mask)
4291 {
4292         return 0;
4293 }
4294
4295 #define ____VECS(tv)    .vecs = tv, .count = ARRAY_SIZE(tv)
4296 #define __VECS(tv)      { ____VECS(tv) }
4297
4298 /* Please keep this list sorted by algorithm name. */
4299 static const struct alg_test_desc alg_test_descs[] = {
4300         {
4301                 .alg = "adiantum(xchacha12,aes)",
4302                 .generic_driver = "adiantum(xchacha12-generic,aes-generic,nhpoly1305-generic)",
4303                 .test = alg_test_skcipher,
4304                 .suite = {
4305                         .cipher = __VECS(adiantum_xchacha12_aes_tv_template)
4306                 },
4307         }, {
4308                 .alg = "adiantum(xchacha20,aes)",
4309                 .generic_driver = "adiantum(xchacha20-generic,aes-generic,nhpoly1305-generic)",
4310                 .test = alg_test_skcipher,
4311                 .suite = {
4312                         .cipher = __VECS(adiantum_xchacha20_aes_tv_template)
4313                 },
4314         }, {
4315                 .alg = "aegis128",
4316                 .test = alg_test_aead,
4317                 .suite = {
4318                         .aead = __VECS(aegis128_tv_template)
4319                 }
4320         }, {
4321                 .alg = "ansi_cprng",
4322                 .test = alg_test_cprng,
4323                 .suite = {
4324                         .cprng = __VECS(ansi_cprng_aes_tv_template)
4325                 }
4326         }, {
4327                 .alg = "authenc(hmac(md5),ecb(cipher_null))",
4328                 .test = alg_test_aead,
4329                 .suite = {
4330                         .aead = __VECS(hmac_md5_ecb_cipher_null_tv_template)
4331                 }
4332         }, {
4333                 .alg = "authenc(hmac(sha1),cbc(aes))",
4334                 .test = alg_test_aead,
4335                 .fips_allowed = 1,
4336                 .suite = {
4337                         .aead = __VECS(hmac_sha1_aes_cbc_tv_temp)
4338                 }
4339         }, {
4340                 .alg = "authenc(hmac(sha1),cbc(des))",
4341                 .test = alg_test_aead,
4342                 .suite = {
4343                         .aead = __VECS(hmac_sha1_des_cbc_tv_temp)
4344                 }
4345         }, {
4346                 .alg = "authenc(hmac(sha1),cbc(des3_ede))",
4347                 .test = alg_test_aead,
4348                 .suite = {
4349                         .aead = __VECS(hmac_sha1_des3_ede_cbc_tv_temp)
4350                 }
4351         }, {
4352                 .alg = "authenc(hmac(sha1),ctr(aes))",
4353                 .test = alg_test_null,
4354                 .fips_allowed = 1,
4355         }, {
4356                 .alg = "authenc(hmac(sha1),ecb(cipher_null))",
4357                 .test = alg_test_aead,
4358                 .suite = {
4359                         .aead = __VECS(hmac_sha1_ecb_cipher_null_tv_temp)
4360                 }
4361         }, {
4362                 .alg = "authenc(hmac(sha1),rfc3686(ctr(aes)))",
4363                 .test = alg_test_null,
4364                 .fips_allowed = 1,
4365         }, {
4366                 .alg = "authenc(hmac(sha224),cbc(des))",
4367                 .test = alg_test_aead,
4368                 .suite = {
4369                         .aead = __VECS(hmac_sha224_des_cbc_tv_temp)
4370                 }
4371         }, {
4372                 .alg = "authenc(hmac(sha224),cbc(des3_ede))",
4373                 .test = alg_test_aead,
4374                 .suite = {
4375                         .aead = __VECS(hmac_sha224_des3_ede_cbc_tv_temp)
4376                 }
4377         }, {
4378                 .alg = "authenc(hmac(sha256),cbc(aes))",
4379                 .test = alg_test_aead,
4380                 .fips_allowed = 1,
4381                 .suite = {
4382                         .aead = __VECS(hmac_sha256_aes_cbc_tv_temp)
4383                 }
4384         }, {
4385                 .alg = "authenc(hmac(sha256),cbc(des))",
4386                 .test = alg_test_aead,
4387                 .suite = {
4388                         .aead = __VECS(hmac_sha256_des_cbc_tv_temp)
4389                 }
4390         }, {
4391                 .alg = "authenc(hmac(sha256),cbc(des3_ede))",
4392                 .test = alg_test_aead,
4393                 .suite = {
4394                         .aead = __VECS(hmac_sha256_des3_ede_cbc_tv_temp)
4395                 }
4396         }, {
4397                 .alg = "authenc(hmac(sha256),ctr(aes))",
4398                 .test = alg_test_null,
4399                 .fips_allowed = 1,
4400         }, {
4401                 .alg = "authenc(hmac(sha256),rfc3686(ctr(aes)))",
4402                 .test = alg_test_null,
4403                 .fips_allowed = 1,
4404         }, {
4405                 .alg = "authenc(hmac(sha384),cbc(des))",
4406                 .test = alg_test_aead,
4407                 .suite = {
4408                         .aead = __VECS(hmac_sha384_des_cbc_tv_temp)
4409                 }
4410         }, {
4411                 .alg = "authenc(hmac(sha384),cbc(des3_ede))",
4412                 .test = alg_test_aead,
4413                 .suite = {
4414                         .aead = __VECS(hmac_sha384_des3_ede_cbc_tv_temp)
4415                 }
4416         }, {
4417                 .alg = "authenc(hmac(sha384),ctr(aes))",
4418                 .test = alg_test_null,
4419                 .fips_allowed = 1,
4420         }, {
4421                 .alg = "authenc(hmac(sha384),rfc3686(ctr(aes)))",
4422                 .test = alg_test_null,
4423                 .fips_allowed = 1,
4424         }, {
4425                 .alg = "authenc(hmac(sha512),cbc(aes))",
4426                 .fips_allowed = 1,
4427                 .test = alg_test_aead,
4428                 .suite = {
4429                         .aead = __VECS(hmac_sha512_aes_cbc_tv_temp)
4430                 }
4431         }, {
4432                 .alg = "authenc(hmac(sha512),cbc(des))",
4433                 .test = alg_test_aead,
4434                 .suite = {
4435                         .aead = __VECS(hmac_sha512_des_cbc_tv_temp)
4436                 }
4437         }, {
4438                 .alg = "authenc(hmac(sha512),cbc(des3_ede))",
4439                 .test = alg_test_aead,
4440                 .suite = {
4441                         .aead = __VECS(hmac_sha512_des3_ede_cbc_tv_temp)
4442                 }
4443         }, {
4444                 .alg = "authenc(hmac(sha512),ctr(aes))",
4445                 .test = alg_test_null,
4446                 .fips_allowed = 1,
4447         }, {
4448                 .alg = "authenc(hmac(sha512),rfc3686(ctr(aes)))",
4449                 .test = alg_test_null,
4450                 .fips_allowed = 1,
4451         }, {
4452                 .alg = "blake2b-160",
4453                 .test = alg_test_hash,
4454                 .fips_allowed = 0,
4455                 .suite = {
4456                         .hash = __VECS(blake2b_160_tv_template)
4457                 }
4458         }, {
4459                 .alg = "blake2b-256",
4460                 .test = alg_test_hash,
4461                 .fips_allowed = 0,
4462                 .suite = {
4463                         .hash = __VECS(blake2b_256_tv_template)
4464                 }
4465         }, {
4466                 .alg = "blake2b-384",
4467                 .test = alg_test_hash,
4468                 .fips_allowed = 0,
4469                 .suite = {
4470                         .hash = __VECS(blake2b_384_tv_template)
4471                 }
4472         }, {
4473                 .alg = "blake2b-512",
4474                 .test = alg_test_hash,
4475                 .fips_allowed = 0,
4476                 .suite = {
4477                         .hash = __VECS(blake2b_512_tv_template)
4478                 }
4479         }, {
4480                 .alg = "cbc(aes)",
4481                 .test = alg_test_skcipher,
4482                 .fips_allowed = 1,
4483                 .suite = {
4484                         .cipher = __VECS(aes_cbc_tv_template)
4485                 },
4486         }, {
4487                 .alg = "cbc(anubis)",
4488                 .test = alg_test_skcipher,
4489                 .suite = {
4490                         .cipher = __VECS(anubis_cbc_tv_template)
4491                 },
4492         }, {
4493                 .alg = "cbc(aria)",
4494                 .test = alg_test_skcipher,
4495                 .suite = {
4496                         .cipher = __VECS(aria_cbc_tv_template)
4497                 },
4498         }, {
4499                 .alg = "cbc(blowfish)",
4500                 .test = alg_test_skcipher,
4501                 .suite = {
4502                         .cipher = __VECS(bf_cbc_tv_template)
4503                 },
4504         }, {
4505                 .alg = "cbc(camellia)",
4506                 .test = alg_test_skcipher,
4507                 .suite = {
4508                         .cipher = __VECS(camellia_cbc_tv_template)
4509                 },
4510         }, {
4511                 .alg = "cbc(cast5)",
4512                 .test = alg_test_skcipher,
4513                 .suite = {
4514                         .cipher = __VECS(cast5_cbc_tv_template)
4515                 },
4516         }, {
4517                 .alg = "cbc(cast6)",
4518                 .test = alg_test_skcipher,
4519                 .suite = {
4520                         .cipher = __VECS(cast6_cbc_tv_template)
4521                 },
4522         }, {
4523                 .alg = "cbc(des)",
4524                 .test = alg_test_skcipher,
4525                 .suite = {
4526                         .cipher = __VECS(des_cbc_tv_template)
4527                 },
4528         }, {
4529                 .alg = "cbc(des3_ede)",
4530                 .test = alg_test_skcipher,
4531                 .suite = {
4532                         .cipher = __VECS(des3_ede_cbc_tv_template)
4533                 },
4534         }, {
4535                 /* Same as cbc(aes) except the key is stored in
4536                  * hardware secure memory which we reference by index
4537                  */
4538                 .alg = "cbc(paes)",
4539                 .test = alg_test_null,
4540                 .fips_allowed = 1,
4541         }, {
4542                 /* Same as cbc(sm4) except the key is stored in
4543                  * hardware secure memory which we reference by index
4544                  */
4545                 .alg = "cbc(psm4)",
4546                 .test = alg_test_null,
4547         }, {
4548                 .alg = "cbc(serpent)",
4549                 .test = alg_test_skcipher,
4550                 .suite = {
4551                         .cipher = __VECS(serpent_cbc_tv_template)
4552                 },
4553         }, {
4554                 .alg = "cbc(sm4)",
4555                 .test = alg_test_skcipher,
4556                 .suite = {
4557                         .cipher = __VECS(sm4_cbc_tv_template)
4558                 }
4559         }, {
4560                 .alg = "cbc(twofish)",
4561                 .test = alg_test_skcipher,
4562                 .suite = {
4563                         .cipher = __VECS(tf_cbc_tv_template)
4564                 },
4565         }, {
4566 #if IS_ENABLED(CONFIG_CRYPTO_PAES_S390)
4567                 .alg = "cbc-paes-s390",
4568                 .fips_allowed = 1,
4569                 .test = alg_test_skcipher,
4570                 .suite = {
4571                         .cipher = __VECS(aes_cbc_tv_template)
4572                 }
4573         }, {
4574 #endif
4575                 .alg = "cbcmac(aes)",
4576                 .fips_allowed = 1,
4577                 .test = alg_test_hash,
4578                 .suite = {
4579                         .hash = __VECS(aes_cbcmac_tv_template)
4580                 }
4581         }, {
4582                 .alg = "cbcmac(sm4)",
4583                 .test = alg_test_hash,
4584                 .suite = {
4585                         .hash = __VECS(sm4_cbcmac_tv_template)
4586                 }
4587         }, {
4588                 .alg = "ccm(aes)",
4589                 .generic_driver = "ccm_base(ctr(aes-generic),cbcmac(aes-generic))",
4590                 .test = alg_test_aead,
4591                 .fips_allowed = 1,
4592                 .suite = {
4593                         .aead = {
4594                                 ____VECS(aes_ccm_tv_template),
4595                                 .einval_allowed = 1,
4596                         }
4597                 }
4598         }, {
4599                 .alg = "ccm(sm4)",
4600                 .generic_driver = "ccm_base(ctr(sm4-generic),cbcmac(sm4-generic))",
4601                 .test = alg_test_aead,
4602                 .suite = {
4603                         .aead = {
4604                                 ____VECS(sm4_ccm_tv_template),
4605                                 .einval_allowed = 1,
4606                         }
4607                 }
4608         }, {
4609                 .alg = "cfb(aes)",
4610                 .test = alg_test_skcipher,
4611                 .fips_allowed = 1,
4612                 .suite = {
4613                         .cipher = __VECS(aes_cfb_tv_template)
4614                 },
4615         }, {
4616                 .alg = "cfb(aria)",
4617                 .test = alg_test_skcipher,
4618                 .suite = {
4619                         .cipher = __VECS(aria_cfb_tv_template)
4620                 },
4621         }, {
4622                 .alg = "cfb(sm4)",
4623                 .test = alg_test_skcipher,
4624                 .suite = {
4625                         .cipher = __VECS(sm4_cfb_tv_template)
4626                 }
4627         }, {
4628                 .alg = "chacha20",
4629                 .test = alg_test_skcipher,
4630                 .suite = {
4631                         .cipher = __VECS(chacha20_tv_template)
4632                 },
4633         }, {
4634                 .alg = "cmac(aes)",
4635                 .fips_allowed = 1,
4636                 .test = alg_test_hash,
4637                 .suite = {
4638                         .hash = __VECS(aes_cmac128_tv_template)
4639                 }
4640         }, {
4641                 .alg = "cmac(des3_ede)",
4642                 .test = alg_test_hash,
4643                 .suite = {
4644                         .hash = __VECS(des3_ede_cmac64_tv_template)
4645                 }
4646         }, {
4647                 .alg = "cmac(sm4)",
4648                 .test = alg_test_hash,
4649                 .suite = {
4650                         .hash = __VECS(sm4_cmac128_tv_template)
4651                 }
4652         }, {
4653                 .alg = "compress_null",
4654                 .test = alg_test_null,
4655         }, {
4656                 .alg = "crc32",
4657                 .test = alg_test_hash,
4658                 .fips_allowed = 1,
4659                 .suite = {
4660                         .hash = __VECS(crc32_tv_template)
4661                 }
4662         }, {
4663                 .alg = "crc32c",
4664                 .test = alg_test_crc32c,
4665                 .fips_allowed = 1,
4666                 .suite = {
4667                         .hash = __VECS(crc32c_tv_template)
4668                 }
4669         }, {
4670                 .alg = "crc64-rocksoft",
4671                 .test = alg_test_hash,
4672                 .fips_allowed = 1,
4673                 .suite = {
4674                         .hash = __VECS(crc64_rocksoft_tv_template)
4675                 }
4676         }, {
4677                 .alg = "crct10dif",
4678                 .test = alg_test_hash,
4679                 .fips_allowed = 1,
4680                 .suite = {
4681                         .hash = __VECS(crct10dif_tv_template)
4682                 }
4683         }, {
4684                 .alg = "ctr(aes)",
4685                 .test = alg_test_skcipher,
4686                 .fips_allowed = 1,
4687                 .suite = {
4688                         .cipher = __VECS(aes_ctr_tv_template)
4689                 }
4690         }, {
4691                 .alg = "ctr(aria)",
4692                 .test = alg_test_skcipher,
4693                 .suite = {
4694                         .cipher = __VECS(aria_ctr_tv_template)
4695                 }
4696         }, {
4697                 .alg = "ctr(blowfish)",
4698                 .test = alg_test_skcipher,
4699                 .suite = {
4700                         .cipher = __VECS(bf_ctr_tv_template)
4701                 }
4702         }, {
4703                 .alg = "ctr(camellia)",
4704                 .test = alg_test_skcipher,
4705                 .suite = {
4706                         .cipher = __VECS(camellia_ctr_tv_template)
4707                 }
4708         }, {
4709                 .alg = "ctr(cast5)",
4710                 .test = alg_test_skcipher,
4711                 .suite = {
4712                         .cipher = __VECS(cast5_ctr_tv_template)
4713                 }
4714         }, {
4715                 .alg = "ctr(cast6)",
4716                 .test = alg_test_skcipher,
4717                 .suite = {
4718                         .cipher = __VECS(cast6_ctr_tv_template)
4719                 }
4720         }, {
4721                 .alg = "ctr(des)",
4722                 .test = alg_test_skcipher,
4723                 .suite = {
4724                         .cipher = __VECS(des_ctr_tv_template)
4725                 }
4726         }, {
4727                 .alg = "ctr(des3_ede)",
4728                 .test = alg_test_skcipher,
4729                 .suite = {
4730                         .cipher = __VECS(des3_ede_ctr_tv_template)
4731                 }
4732         }, {
4733                 /* Same as ctr(aes) except the key is stored in
4734                  * hardware secure memory which we reference by index
4735                  */
4736                 .alg = "ctr(paes)",
4737                 .test = alg_test_null,
4738                 .fips_allowed = 1,
4739         }, {
4740
4741                 /* Same as ctr(sm4) except the key is stored in
4742                  * hardware secure memory which we reference by index
4743                  */
4744                 .alg = "ctr(psm4)",
4745                 .test = alg_test_null,
4746         }, {
4747                 .alg = "ctr(serpent)",
4748                 .test = alg_test_skcipher,
4749                 .suite = {
4750                         .cipher = __VECS(serpent_ctr_tv_template)
4751                 }
4752         }, {
4753                 .alg = "ctr(sm4)",
4754                 .test = alg_test_skcipher,
4755                 .suite = {
4756                         .cipher = __VECS(sm4_ctr_tv_template)
4757                 }
4758         }, {
4759                 .alg = "ctr(twofish)",
4760                 .test = alg_test_skcipher,
4761                 .suite = {
4762                         .cipher = __VECS(tf_ctr_tv_template)
4763                 }
4764         }, {
4765 #if IS_ENABLED(CONFIG_CRYPTO_PAES_S390)
4766                 .alg = "ctr-paes-s390",
4767                 .fips_allowed = 1,
4768                 .test = alg_test_skcipher,
4769                 .suite = {
4770                         .cipher = __VECS(aes_ctr_tv_template)
4771                 }
4772         }, {
4773 #endif
4774                 .alg = "cts(cbc(aes))",
4775                 .test = alg_test_skcipher,
4776                 .fips_allowed = 1,
4777                 .suite = {
4778                         .cipher = __VECS(cts_mode_tv_template)
4779                 }
4780         }, {
4781                 /* Same as cts(cbc((aes)) except the key is stored in
4782                  * hardware secure memory which we reference by index
4783                  */
4784                 .alg = "cts(cbc(paes))",
4785                 .test = alg_test_null,
4786                 .fips_allowed = 1,
4787         }, {
4788                 .alg = "curve25519",
4789                 .test = alg_test_kpp,
4790                 .suite = {
4791                         .kpp = __VECS(curve25519_tv_template)
4792                 }
4793         }, {
4794                 .alg = "deflate",
4795                 .test = alg_test_comp,
4796                 .fips_allowed = 1,
4797                 .suite = {
4798                         .comp = {
4799                                 .comp = __VECS(deflate_comp_tv_template),
4800                                 .decomp = __VECS(deflate_decomp_tv_template)
4801                         }
4802                 }
4803         }, {
4804                 .alg = "dh",
4805                 .test = alg_test_kpp,
4806                 .suite = {
4807                         .kpp = __VECS(dh_tv_template)
4808                 }
4809         }, {
4810                 .alg = "digest_null",
4811                 .test = alg_test_null,
4812         }, {
4813                 .alg = "drbg_nopr_ctr_aes128",
4814                 .test = alg_test_drbg,
4815                 .fips_allowed = 1,
4816                 .suite = {
4817                         .drbg = __VECS(drbg_nopr_ctr_aes128_tv_template)
4818                 }
4819         }, {
4820                 .alg = "drbg_nopr_ctr_aes192",
4821                 .test = alg_test_drbg,
4822                 .fips_allowed = 1,
4823                 .suite = {
4824                         .drbg = __VECS(drbg_nopr_ctr_aes192_tv_template)
4825                 }
4826         }, {
4827                 .alg = "drbg_nopr_ctr_aes256",
4828                 .test = alg_test_drbg,
4829                 .fips_allowed = 1,
4830                 .suite = {
4831                         .drbg = __VECS(drbg_nopr_ctr_aes256_tv_template)
4832                 }
4833         }, {
4834                 /*
4835                  * There is no need to specifically test the DRBG with every
4836                  * backend cipher -- covered by drbg_nopr_hmac_sha256 test
4837                  */
4838                 .alg = "drbg_nopr_hmac_sha1",
4839                 .fips_allowed = 1,
4840                 .test = alg_test_null,
4841         }, {
4842                 .alg = "drbg_nopr_hmac_sha256",
4843                 .test = alg_test_drbg,
4844                 .fips_allowed = 1,
4845                 .suite = {
4846                         .drbg = __VECS(drbg_nopr_hmac_sha256_tv_template)
4847                 }
4848         }, {
4849                 /* covered by drbg_nopr_hmac_sha256 test */
4850                 .alg = "drbg_nopr_hmac_sha384",
4851                 .fips_allowed = 1,
4852                 .test = alg_test_null,
4853         }, {
4854                 .alg = "drbg_nopr_hmac_sha512",
4855                 .test = alg_test_drbg,
4856                 .fips_allowed = 1,
4857                 .suite = {
4858                         .drbg = __VECS(drbg_nopr_hmac_sha512_tv_template)
4859                 }
4860         }, {
4861                 .alg = "drbg_nopr_sha1",
4862                 .fips_allowed = 1,
4863                 .test = alg_test_null,
4864         }, {
4865                 .alg = "drbg_nopr_sha256",
4866                 .test = alg_test_drbg,
4867                 .fips_allowed = 1,
4868                 .suite = {
4869                         .drbg = __VECS(drbg_nopr_sha256_tv_template)
4870                 }
4871         }, {
4872                 /* covered by drbg_nopr_sha256 test */
4873                 .alg = "drbg_nopr_sha384",
4874                 .fips_allowed = 1,
4875                 .test = alg_test_null,
4876         }, {
4877                 .alg = "drbg_nopr_sha512",
4878                 .fips_allowed = 1,
4879                 .test = alg_test_null,
4880         }, {
4881                 .alg = "drbg_pr_ctr_aes128",
4882                 .test = alg_test_drbg,
4883                 .fips_allowed = 1,
4884                 .suite = {
4885                         .drbg = __VECS(drbg_pr_ctr_aes128_tv_template)
4886                 }
4887         }, {
4888                 /* covered by drbg_pr_ctr_aes128 test */
4889                 .alg = "drbg_pr_ctr_aes192",
4890                 .fips_allowed = 1,
4891                 .test = alg_test_null,
4892         }, {
4893                 .alg = "drbg_pr_ctr_aes256",
4894                 .fips_allowed = 1,
4895                 .test = alg_test_null,
4896         }, {
4897                 .alg = "drbg_pr_hmac_sha1",
4898                 .fips_allowed = 1,
4899                 .test = alg_test_null,
4900         }, {
4901                 .alg = "drbg_pr_hmac_sha256",
4902                 .test = alg_test_drbg,
4903                 .fips_allowed = 1,
4904                 .suite = {
4905                         .drbg = __VECS(drbg_pr_hmac_sha256_tv_template)
4906                 }
4907         }, {
4908                 /* covered by drbg_pr_hmac_sha256 test */
4909                 .alg = "drbg_pr_hmac_sha384",
4910                 .fips_allowed = 1,
4911                 .test = alg_test_null,
4912         }, {
4913                 .alg = "drbg_pr_hmac_sha512",
4914                 .test = alg_test_null,
4915                 .fips_allowed = 1,
4916         }, {
4917                 .alg = "drbg_pr_sha1",
4918                 .fips_allowed = 1,
4919                 .test = alg_test_null,
4920         }, {
4921                 .alg = "drbg_pr_sha256",
4922                 .test = alg_test_drbg,
4923                 .fips_allowed = 1,
4924                 .suite = {
4925                         .drbg = __VECS(drbg_pr_sha256_tv_template)
4926                 }
4927         }, {
4928                 /* covered by drbg_pr_sha256 test */
4929                 .alg = "drbg_pr_sha384",
4930                 .fips_allowed = 1,
4931                 .test = alg_test_null,
4932         }, {
4933                 .alg = "drbg_pr_sha512",
4934                 .fips_allowed = 1,
4935                 .test = alg_test_null,
4936         }, {
4937                 .alg = "ecb(aes)",
4938                 .test = alg_test_skcipher,
4939                 .fips_allowed = 1,
4940                 .suite = {
4941                         .cipher = __VECS(aes_tv_template)
4942                 }
4943         }, {
4944                 .alg = "ecb(anubis)",
4945                 .test = alg_test_skcipher,
4946                 .suite = {
4947                         .cipher = __VECS(anubis_tv_template)
4948                 }
4949         }, {
4950                 .alg = "ecb(arc4)",
4951                 .generic_driver = "ecb(arc4)-generic",
4952                 .test = alg_test_skcipher,
4953                 .suite = {
4954                         .cipher = __VECS(arc4_tv_template)
4955                 }
4956         }, {
4957                 .alg = "ecb(aria)",
4958                 .test = alg_test_skcipher,
4959                 .suite = {
4960                         .cipher = __VECS(aria_tv_template)
4961                 }
4962         }, {
4963                 .alg = "ecb(blowfish)",
4964                 .test = alg_test_skcipher,
4965                 .suite = {
4966                         .cipher = __VECS(bf_tv_template)
4967                 }
4968         }, {
4969                 .alg = "ecb(camellia)",
4970                 .test = alg_test_skcipher,
4971                 .suite = {
4972                         .cipher = __VECS(camellia_tv_template)
4973                 }
4974         }, {
4975                 .alg = "ecb(cast5)",
4976                 .test = alg_test_skcipher,
4977                 .suite = {
4978                         .cipher = __VECS(cast5_tv_template)
4979                 }
4980         }, {
4981                 .alg = "ecb(cast6)",
4982                 .test = alg_test_skcipher,
4983                 .suite = {
4984                         .cipher = __VECS(cast6_tv_template)
4985                 }
4986         }, {
4987                 .alg = "ecb(cipher_null)",
4988                 .test = alg_test_null,
4989                 .fips_allowed = 1,
4990         }, {
4991                 .alg = "ecb(des)",
4992                 .test = alg_test_skcipher,
4993                 .suite = {
4994                         .cipher = __VECS(des_tv_template)
4995                 }
4996         }, {
4997                 .alg = "ecb(des3_ede)",
4998                 .test = alg_test_skcipher,
4999                 .suite = {
5000                         .cipher = __VECS(des3_ede_tv_template)
5001                 }
5002         }, {
5003                 .alg = "ecb(fcrypt)",
5004                 .test = alg_test_skcipher,
5005                 .suite = {
5006                         .cipher = {
5007                                 .vecs = fcrypt_pcbc_tv_template,
5008                                 .count = 1
5009                         }
5010                 }
5011         }, {
5012                 .alg = "ecb(khazad)",
5013                 .test = alg_test_skcipher,
5014                 .suite = {
5015                         .cipher = __VECS(khazad_tv_template)
5016                 }
5017         }, {
5018                 /* Same as ecb(aes) except the key is stored in
5019                  * hardware secure memory which we reference by index
5020                  */
5021                 .alg = "ecb(paes)",
5022                 .test = alg_test_null,
5023                 .fips_allowed = 1,
5024         }, {
5025                 .alg = "ecb(seed)",
5026                 .test = alg_test_skcipher,
5027                 .suite = {
5028                         .cipher = __VECS(seed_tv_template)
5029                 }
5030         }, {
5031                 .alg = "ecb(serpent)",
5032                 .test = alg_test_skcipher,
5033                 .suite = {
5034                         .cipher = __VECS(serpent_tv_template)
5035                 }
5036         }, {
5037                 .alg = "ecb(sm4)",
5038                 .test = alg_test_skcipher,
5039                 .suite = {
5040                         .cipher = __VECS(sm4_tv_template)
5041                 }
5042         }, {
5043                 .alg = "ecb(tea)",
5044                 .test = alg_test_skcipher,
5045                 .suite = {
5046                         .cipher = __VECS(tea_tv_template)
5047                 }
5048         }, {
5049                 .alg = "ecb(twofish)",
5050                 .test = alg_test_skcipher,
5051                 .suite = {
5052                         .cipher = __VECS(tf_tv_template)
5053                 }
5054         }, {
5055                 .alg = "ecb(xeta)",
5056                 .test = alg_test_skcipher,
5057                 .suite = {
5058                         .cipher = __VECS(xeta_tv_template)
5059                 }
5060         }, {
5061                 .alg = "ecb(xtea)",
5062                 .test = alg_test_skcipher,
5063                 .suite = {
5064                         .cipher = __VECS(xtea_tv_template)
5065                 }
5066         }, {
5067 #if IS_ENABLED(CONFIG_CRYPTO_PAES_S390)
5068                 .alg = "ecb-paes-s390",
5069                 .fips_allowed = 1,
5070                 .test = alg_test_skcipher,
5071                 .suite = {
5072                         .cipher = __VECS(aes_tv_template)
5073                 }
5074         }, {
5075 #endif
5076                 .alg = "ecdh-nist-p192",
5077                 .test = alg_test_kpp,
5078                 .suite = {
5079                         .kpp = __VECS(ecdh_p192_tv_template)
5080                 }
5081         }, {
5082                 .alg = "ecdh-nist-p256",
5083                 .test = alg_test_kpp,
5084                 .fips_allowed = 1,
5085                 .suite = {
5086                         .kpp = __VECS(ecdh_p256_tv_template)
5087                 }
5088         }, {
5089                 .alg = "ecdh-nist-p384",
5090                 .test = alg_test_kpp,
5091                 .fips_allowed = 1,
5092                 .suite = {
5093                         .kpp = __VECS(ecdh_p384_tv_template)
5094                 }
5095         }, {
5096                 .alg = "ecdsa-nist-p192",
5097                 .test = alg_test_akcipher,
5098                 .suite = {
5099                         .akcipher = __VECS(ecdsa_nist_p192_tv_template)
5100                 }
5101         }, {
5102                 .alg = "ecdsa-nist-p256",
5103                 .test = alg_test_akcipher,
5104                 .suite = {
5105                         .akcipher = __VECS(ecdsa_nist_p256_tv_template)
5106                 }
5107         }, {
5108                 .alg = "ecdsa-nist-p384",
5109                 .test = alg_test_akcipher,
5110                 .suite = {
5111                         .akcipher = __VECS(ecdsa_nist_p384_tv_template)
5112                 }
5113         }, {
5114                 .alg = "ecrdsa",
5115                 .test = alg_test_akcipher,
5116                 .suite = {
5117                         .akcipher = __VECS(ecrdsa_tv_template)
5118                 }
5119         }, {
5120                 .alg = "essiv(authenc(hmac(sha256),cbc(aes)),sha256)",
5121                 .test = alg_test_aead,
5122                 .fips_allowed = 1,
5123                 .suite = {
5124                         .aead = __VECS(essiv_hmac_sha256_aes_cbc_tv_temp)
5125                 }
5126         }, {
5127                 .alg = "essiv(cbc(aes),sha256)",
5128                 .test = alg_test_skcipher,
5129                 .fips_allowed = 1,
5130                 .suite = {
5131                         .cipher = __VECS(essiv_aes_cbc_tv_template)
5132                 }
5133         }, {
5134 #if IS_ENABLED(CONFIG_CRYPTO_DH_RFC7919_GROUPS)
5135                 .alg = "ffdhe2048(dh)",
5136                 .test = alg_test_kpp,
5137                 .fips_allowed = 1,
5138                 .suite = {
5139                         .kpp = __VECS(ffdhe2048_dh_tv_template)
5140                 }
5141         }, {
5142                 .alg = "ffdhe3072(dh)",
5143                 .test = alg_test_kpp,
5144                 .fips_allowed = 1,
5145                 .suite = {
5146                         .kpp = __VECS(ffdhe3072_dh_tv_template)
5147                 }
5148         }, {
5149                 .alg = "ffdhe4096(dh)",
5150                 .test = alg_test_kpp,
5151                 .fips_allowed = 1,
5152                 .suite = {
5153                         .kpp = __VECS(ffdhe4096_dh_tv_template)
5154                 }
5155         }, {
5156                 .alg = "ffdhe6144(dh)",
5157                 .test = alg_test_kpp,
5158                 .fips_allowed = 1,
5159                 .suite = {
5160                         .kpp = __VECS(ffdhe6144_dh_tv_template)
5161                 }
5162         }, {
5163                 .alg = "ffdhe8192(dh)",
5164                 .test = alg_test_kpp,
5165                 .fips_allowed = 1,
5166                 .suite = {
5167                         .kpp = __VECS(ffdhe8192_dh_tv_template)
5168                 }
5169         }, {
5170 #endif /* CONFIG_CRYPTO_DH_RFC7919_GROUPS */
5171                 .alg = "gcm(aes)",
5172                 .generic_driver = "gcm_base(ctr(aes-generic),ghash-generic)",
5173                 .test = alg_test_aead,
5174                 .fips_allowed = 1,
5175                 .suite = {
5176                         .aead = __VECS(aes_gcm_tv_template)
5177                 }
5178         }, {
5179                 .alg = "gcm(aria)",
5180                 .generic_driver = "gcm_base(ctr(aria-generic),ghash-generic)",
5181                 .test = alg_test_aead,
5182                 .suite = {
5183                         .aead = __VECS(aria_gcm_tv_template)
5184                 }
5185         }, {
5186                 .alg = "gcm(sm4)",
5187                 .generic_driver = "gcm_base(ctr(sm4-generic),ghash-generic)",
5188                 .test = alg_test_aead,
5189                 .suite = {
5190                         .aead = __VECS(sm4_gcm_tv_template)
5191                 }
5192         }, {
5193                 .alg = "ghash",
5194                 .test = alg_test_hash,
5195                 .fips_allowed = 1,
5196                 .suite = {
5197                         .hash = __VECS(ghash_tv_template)
5198                 }
5199         }, {
5200                 .alg = "hctr2(aes)",
5201                 .generic_driver =
5202                     "hctr2_base(xctr(aes-generic),polyval-generic)",
5203                 .test = alg_test_skcipher,
5204                 .suite = {
5205                         .cipher = __VECS(aes_hctr2_tv_template)
5206                 }
5207         }, {
5208                 .alg = "hmac(md5)",
5209                 .test = alg_test_hash,
5210                 .suite = {
5211                         .hash = __VECS(hmac_md5_tv_template)
5212                 }
5213         }, {
5214                 .alg = "hmac(rmd160)",
5215                 .test = alg_test_hash,
5216                 .suite = {
5217                         .hash = __VECS(hmac_rmd160_tv_template)
5218                 }
5219         }, {
5220                 .alg = "hmac(sha1)",
5221                 .test = alg_test_hash,
5222                 .fips_allowed = 1,
5223                 .suite = {
5224                         .hash = __VECS(hmac_sha1_tv_template)
5225                 }
5226         }, {
5227                 .alg = "hmac(sha224)",
5228                 .test = alg_test_hash,
5229                 .fips_allowed = 1,
5230                 .suite = {
5231                         .hash = __VECS(hmac_sha224_tv_template)
5232                 }
5233         }, {
5234                 .alg = "hmac(sha256)",
5235                 .test = alg_test_hash,
5236                 .fips_allowed = 1,
5237                 .suite = {
5238                         .hash = __VECS(hmac_sha256_tv_template)
5239                 }
5240         }, {
5241                 .alg = "hmac(sha3-224)",
5242                 .test = alg_test_hash,
5243                 .fips_allowed = 1,
5244                 .suite = {
5245                         .hash = __VECS(hmac_sha3_224_tv_template)
5246                 }
5247         }, {
5248                 .alg = "hmac(sha3-256)",
5249                 .test = alg_test_hash,
5250                 .fips_allowed = 1,
5251                 .suite = {
5252                         .hash = __VECS(hmac_sha3_256_tv_template)
5253                 }
5254         }, {
5255                 .alg = "hmac(sha3-384)",
5256                 .test = alg_test_hash,
5257                 .fips_allowed = 1,
5258                 .suite = {
5259                         .hash = __VECS(hmac_sha3_384_tv_template)
5260                 }
5261         }, {
5262                 .alg = "hmac(sha3-512)",
5263                 .test = alg_test_hash,
5264                 .fips_allowed = 1,
5265                 .suite = {
5266                         .hash = __VECS(hmac_sha3_512_tv_template)
5267                 }
5268         }, {
5269                 .alg = "hmac(sha384)",
5270                 .test = alg_test_hash,
5271                 .fips_allowed = 1,
5272                 .suite = {
5273                         .hash = __VECS(hmac_sha384_tv_template)
5274                 }
5275         }, {
5276                 .alg = "hmac(sha512)",
5277                 .test = alg_test_hash,
5278                 .fips_allowed = 1,
5279                 .suite = {
5280                         .hash = __VECS(hmac_sha512_tv_template)
5281                 }
5282         }, {
5283                 .alg = "hmac(sm3)",
5284                 .test = alg_test_hash,
5285                 .suite = {
5286                         .hash = __VECS(hmac_sm3_tv_template)
5287                 }
5288         }, {
5289                 .alg = "hmac(streebog256)",
5290                 .test = alg_test_hash,
5291                 .suite = {
5292                         .hash = __VECS(hmac_streebog256_tv_template)
5293                 }
5294         }, {
5295                 .alg = "hmac(streebog512)",
5296                 .test = alg_test_hash,
5297                 .suite = {
5298                         .hash = __VECS(hmac_streebog512_tv_template)
5299                 }
5300         }, {
5301                 .alg = "jitterentropy_rng",
5302                 .fips_allowed = 1,
5303                 .test = alg_test_null,
5304         }, {
5305                 .alg = "kw(aes)",
5306                 .test = alg_test_skcipher,
5307                 .fips_allowed = 1,
5308                 .suite = {
5309                         .cipher = __VECS(aes_kw_tv_template)
5310                 }
5311         }, {
5312                 .alg = "lrw(aes)",
5313                 .generic_driver = "lrw(ecb(aes-generic))",
5314                 .test = alg_test_skcipher,
5315                 .suite = {
5316                         .cipher = __VECS(aes_lrw_tv_template)
5317                 }
5318         }, {
5319                 .alg = "lrw(camellia)",
5320                 .generic_driver = "lrw(ecb(camellia-generic))",
5321                 .test = alg_test_skcipher,
5322                 .suite = {
5323                         .cipher = __VECS(camellia_lrw_tv_template)
5324                 }
5325         }, {
5326                 .alg = "lrw(cast6)",
5327                 .generic_driver = "lrw(ecb(cast6-generic))",
5328                 .test = alg_test_skcipher,
5329                 .suite = {
5330                         .cipher = __VECS(cast6_lrw_tv_template)
5331                 }
5332         }, {
5333                 .alg = "lrw(serpent)",
5334                 .generic_driver = "lrw(ecb(serpent-generic))",
5335                 .test = alg_test_skcipher,
5336                 .suite = {
5337                         .cipher = __VECS(serpent_lrw_tv_template)
5338                 }
5339         }, {
5340                 .alg = "lrw(twofish)",
5341                 .generic_driver = "lrw(ecb(twofish-generic))",
5342                 .test = alg_test_skcipher,
5343                 .suite = {
5344                         .cipher = __VECS(tf_lrw_tv_template)
5345                 }
5346         }, {
5347                 .alg = "lz4",
5348                 .test = alg_test_comp,
5349                 .fips_allowed = 1,
5350                 .suite = {
5351                         .comp = {
5352                                 .comp = __VECS(lz4_comp_tv_template),
5353                                 .decomp = __VECS(lz4_decomp_tv_template)
5354                         }
5355                 }
5356         }, {
5357                 .alg = "lz4hc",
5358                 .test = alg_test_comp,
5359                 .fips_allowed = 1,
5360                 .suite = {
5361                         .comp = {
5362                                 .comp = __VECS(lz4hc_comp_tv_template),
5363                                 .decomp = __VECS(lz4hc_decomp_tv_template)
5364                         }
5365                 }
5366         }, {
5367                 .alg = "lzo",
5368                 .test = alg_test_comp,
5369                 .fips_allowed = 1,
5370                 .suite = {
5371                         .comp = {
5372                                 .comp = __VECS(lzo_comp_tv_template),
5373                                 .decomp = __VECS(lzo_decomp_tv_template)
5374                         }
5375                 }
5376         }, {
5377                 .alg = "lzo-rle",
5378                 .test = alg_test_comp,
5379                 .fips_allowed = 1,
5380                 .suite = {
5381                         .comp = {
5382                                 .comp = __VECS(lzorle_comp_tv_template),
5383                                 .decomp = __VECS(lzorle_decomp_tv_template)
5384                         }
5385                 }
5386         }, {
5387                 .alg = "md4",
5388                 .test = alg_test_hash,
5389                 .suite = {
5390                         .hash = __VECS(md4_tv_template)
5391                 }
5392         }, {
5393                 .alg = "md5",
5394                 .test = alg_test_hash,
5395                 .suite = {
5396                         .hash = __VECS(md5_tv_template)
5397                 }
5398         }, {
5399                 .alg = "michael_mic",
5400                 .test = alg_test_hash,
5401                 .suite = {
5402                         .hash = __VECS(michael_mic_tv_template)
5403                 }
5404         }, {
5405                 .alg = "nhpoly1305",
5406                 .test = alg_test_hash,
5407                 .suite = {
5408                         .hash = __VECS(nhpoly1305_tv_template)
5409                 }
5410         }, {
5411                 .alg = "ofb(aes)",
5412                 .test = alg_test_skcipher,
5413                 .fips_allowed = 1,
5414                 .suite = {
5415                         .cipher = __VECS(aes_ofb_tv_template)
5416                 }
5417         }, {
5418                 /* Same as ofb(aes) except the key is stored in
5419                  * hardware secure memory which we reference by index
5420                  */
5421                 .alg = "ofb(paes)",
5422                 .test = alg_test_null,
5423                 .fips_allowed = 1,
5424         }, {
5425                 .alg = "ofb(sm4)",
5426                 .test = alg_test_skcipher,
5427                 .suite = {
5428                         .cipher = __VECS(sm4_ofb_tv_template)
5429                 }
5430         }, {
5431                 .alg = "pcbc(fcrypt)",
5432                 .test = alg_test_skcipher,
5433                 .suite = {
5434                         .cipher = __VECS(fcrypt_pcbc_tv_template)
5435                 }
5436         }, {
5437                 .alg = "pkcs1pad(rsa,sha224)",
5438                 .test = alg_test_null,
5439                 .fips_allowed = 1,
5440         }, {
5441                 .alg = "pkcs1pad(rsa,sha256)",
5442                 .test = alg_test_akcipher,
5443                 .fips_allowed = 1,
5444                 .suite = {
5445                         .akcipher = __VECS(pkcs1pad_rsa_tv_template)
5446                 }
5447         }, {
5448                 .alg = "pkcs1pad(rsa,sha384)",
5449                 .test = alg_test_null,
5450                 .fips_allowed = 1,
5451         }, {
5452                 .alg = "pkcs1pad(rsa,sha512)",
5453                 .test = alg_test_null,
5454                 .fips_allowed = 1,
5455         }, {
5456                 .alg = "poly1305",
5457                 .test = alg_test_hash,
5458                 .suite = {
5459                         .hash = __VECS(poly1305_tv_template)
5460                 }
5461         }, {
5462                 .alg = "polyval",
5463                 .test = alg_test_hash,
5464                 .suite = {
5465                         .hash = __VECS(polyval_tv_template)
5466                 }
5467         }, {
5468                 .alg = "rfc3686(ctr(aes))",
5469                 .test = alg_test_skcipher,
5470                 .fips_allowed = 1,
5471                 .suite = {
5472                         .cipher = __VECS(aes_ctr_rfc3686_tv_template)
5473                 }
5474         }, {
5475                 .alg = "rfc3686(ctr(sm4))",
5476                 .test = alg_test_skcipher,
5477                 .suite = {
5478                         .cipher = __VECS(sm4_ctr_rfc3686_tv_template)
5479                 }
5480         }, {
5481                 .alg = "rfc4106(gcm(aes))",
5482                 .generic_driver = "rfc4106(gcm_base(ctr(aes-generic),ghash-generic))",
5483                 .test = alg_test_aead,
5484                 .fips_allowed = 1,
5485                 .suite = {
5486                         .aead = {
5487                                 ____VECS(aes_gcm_rfc4106_tv_template),
5488                                 .einval_allowed = 1,
5489                                 .aad_iv = 1,
5490                         }
5491                 }
5492         }, {
5493                 .alg = "rfc4309(ccm(aes))",
5494                 .generic_driver = "rfc4309(ccm_base(ctr(aes-generic),cbcmac(aes-generic)))",
5495                 .test = alg_test_aead,
5496                 .fips_allowed = 1,
5497                 .suite = {
5498                         .aead = {
5499                                 ____VECS(aes_ccm_rfc4309_tv_template),
5500                                 .einval_allowed = 1,
5501                                 .aad_iv = 1,
5502                         }
5503                 }
5504         }, {
5505                 .alg = "rfc4543(gcm(aes))",
5506                 .generic_driver = "rfc4543(gcm_base(ctr(aes-generic),ghash-generic))",
5507                 .test = alg_test_aead,
5508                 .suite = {
5509                         .aead = {
5510                                 ____VECS(aes_gcm_rfc4543_tv_template),
5511                                 .einval_allowed = 1,
5512                                 .aad_iv = 1,
5513                         }
5514                 }
5515         }, {
5516                 .alg = "rfc7539(chacha20,poly1305)",
5517                 .test = alg_test_aead,
5518                 .suite = {
5519                         .aead = __VECS(rfc7539_tv_template)
5520                 }
5521         }, {
5522                 .alg = "rfc7539esp(chacha20,poly1305)",
5523                 .test = alg_test_aead,
5524                 .suite = {
5525                         .aead = {
5526                                 ____VECS(rfc7539esp_tv_template),
5527                                 .einval_allowed = 1,
5528                                 .aad_iv = 1,
5529                         }
5530                 }
5531         }, {
5532                 .alg = "rmd160",
5533                 .test = alg_test_hash,
5534                 .suite = {
5535                         .hash = __VECS(rmd160_tv_template)
5536                 }
5537         }, {
5538                 .alg = "rsa",
5539                 .test = alg_test_akcipher,
5540                 .fips_allowed = 1,
5541                 .suite = {
5542                         .akcipher = __VECS(rsa_tv_template)
5543                 }
5544         }, {
5545                 .alg = "sha1",
5546                 .test = alg_test_hash,
5547                 .fips_allowed = 1,
5548                 .suite = {
5549                         .hash = __VECS(sha1_tv_template)
5550                 }
5551         }, {
5552                 .alg = "sha224",
5553                 .test = alg_test_hash,
5554                 .fips_allowed = 1,
5555                 .suite = {
5556                         .hash = __VECS(sha224_tv_template)
5557                 }
5558         }, {
5559                 .alg = "sha256",
5560                 .test = alg_test_hash,
5561                 .fips_allowed = 1,
5562                 .suite = {
5563                         .hash = __VECS(sha256_tv_template)
5564                 }
5565         }, {
5566                 .alg = "sha3-224",
5567                 .test = alg_test_hash,
5568                 .fips_allowed = 1,
5569                 .suite = {
5570                         .hash = __VECS(sha3_224_tv_template)
5571                 }
5572         }, {
5573                 .alg = "sha3-256",
5574                 .test = alg_test_hash,
5575                 .fips_allowed = 1,
5576                 .suite = {
5577                         .hash = __VECS(sha3_256_tv_template)
5578                 }
5579         }, {
5580                 .alg = "sha3-384",
5581                 .test = alg_test_hash,
5582                 .fips_allowed = 1,
5583                 .suite = {
5584                         .hash = __VECS(sha3_384_tv_template)
5585                 }
5586         }, {
5587                 .alg = "sha3-512",
5588                 .test = alg_test_hash,
5589                 .fips_allowed = 1,
5590                 .suite = {
5591                         .hash = __VECS(sha3_512_tv_template)
5592                 }
5593         }, {
5594                 .alg = "sha384",
5595                 .test = alg_test_hash,
5596                 .fips_allowed = 1,
5597                 .suite = {
5598                         .hash = __VECS(sha384_tv_template)
5599                 }
5600         }, {
5601                 .alg = "sha512",
5602                 .test = alg_test_hash,
5603                 .fips_allowed = 1,
5604                 .suite = {
5605                         .hash = __VECS(sha512_tv_template)
5606                 }
5607         }, {
5608                 .alg = "sm2",
5609                 .test = alg_test_akcipher,
5610                 .suite = {
5611                         .akcipher = __VECS(sm2_tv_template)
5612                 }
5613         }, {
5614                 .alg = "sm3",
5615                 .test = alg_test_hash,
5616                 .suite = {
5617                         .hash = __VECS(sm3_tv_template)
5618                 }
5619         }, {
5620                 .alg = "streebog256",
5621                 .test = alg_test_hash,
5622                 .suite = {
5623                         .hash = __VECS(streebog256_tv_template)
5624                 }
5625         }, {
5626                 .alg = "streebog512",
5627                 .test = alg_test_hash,
5628                 .suite = {
5629                         .hash = __VECS(streebog512_tv_template)
5630                 }
5631         }, {
5632                 .alg = "vmac64(aes)",
5633                 .test = alg_test_hash,
5634                 .suite = {
5635                         .hash = __VECS(vmac64_aes_tv_template)
5636                 }
5637         }, {
5638                 .alg = "wp256",
5639                 .test = alg_test_hash,
5640                 .suite = {
5641                         .hash = __VECS(wp256_tv_template)
5642                 }
5643         }, {
5644                 .alg = "wp384",
5645                 .test = alg_test_hash,
5646                 .suite = {
5647                         .hash = __VECS(wp384_tv_template)
5648                 }
5649         }, {
5650                 .alg = "wp512",
5651                 .test = alg_test_hash,
5652                 .suite = {
5653                         .hash = __VECS(wp512_tv_template)
5654                 }
5655         }, {
5656                 .alg = "xcbc(aes)",
5657                 .test = alg_test_hash,
5658                 .suite = {
5659                         .hash = __VECS(aes_xcbc128_tv_template)
5660                 }
5661         }, {
5662                 .alg = "xchacha12",
5663                 .test = alg_test_skcipher,
5664                 .suite = {
5665                         .cipher = __VECS(xchacha12_tv_template)
5666                 },
5667         }, {
5668                 .alg = "xchacha20",
5669                 .test = alg_test_skcipher,
5670                 .suite = {
5671                         .cipher = __VECS(xchacha20_tv_template)
5672                 },
5673         }, {
5674                 .alg = "xctr(aes)",
5675                 .test = alg_test_skcipher,
5676                 .suite = {
5677                         .cipher = __VECS(aes_xctr_tv_template)
5678                 }
5679         }, {
5680                 .alg = "xts(aes)",
5681                 .generic_driver = "xts(ecb(aes-generic))",
5682                 .test = alg_test_skcipher,
5683                 .fips_allowed = 1,
5684                 .suite = {
5685                         .cipher = __VECS(aes_xts_tv_template)
5686                 }
5687         }, {
5688                 .alg = "xts(camellia)",
5689                 .generic_driver = "xts(ecb(camellia-generic))",
5690                 .test = alg_test_skcipher,
5691                 .suite = {
5692                         .cipher = __VECS(camellia_xts_tv_template)
5693                 }
5694         }, {
5695                 .alg = "xts(cast6)",
5696                 .generic_driver = "xts(ecb(cast6-generic))",
5697                 .test = alg_test_skcipher,
5698                 .suite = {
5699                         .cipher = __VECS(cast6_xts_tv_template)
5700                 }
5701         }, {
5702                 /* Same as xts(aes) except the key is stored in
5703                  * hardware secure memory which we reference by index
5704                  */
5705                 .alg = "xts(paes)",
5706                 .test = alg_test_null,
5707                 .fips_allowed = 1,
5708         }, {
5709                 .alg = "xts(serpent)",
5710                 .generic_driver = "xts(ecb(serpent-generic))",
5711                 .test = alg_test_skcipher,
5712                 .suite = {
5713                         .cipher = __VECS(serpent_xts_tv_template)
5714                 }
5715         }, {
5716                 .alg = "xts(twofish)",
5717                 .generic_driver = "xts(ecb(twofish-generic))",
5718                 .test = alg_test_skcipher,
5719                 .suite = {
5720                         .cipher = __VECS(tf_xts_tv_template)
5721                 }
5722         }, {
5723 #if IS_ENABLED(CONFIG_CRYPTO_PAES_S390)
5724                 .alg = "xts-paes-s390",
5725                 .fips_allowed = 1,
5726                 .test = alg_test_skcipher,
5727                 .suite = {
5728                         .cipher = __VECS(aes_xts_tv_template)
5729                 }
5730         }, {
5731 #endif
5732                 .alg = "xts4096(paes)",
5733                 .test = alg_test_null,
5734                 .fips_allowed = 1,
5735         }, {
5736                 .alg = "xts512(paes)",
5737                 .test = alg_test_null,
5738                 .fips_allowed = 1,
5739         }, {
5740                 .alg = "xxhash64",
5741                 .test = alg_test_hash,
5742                 .fips_allowed = 1,
5743                 .suite = {
5744                         .hash = __VECS(xxhash64_tv_template)
5745                 }
5746         }, {
5747                 .alg = "zlib-deflate",
5748                 .test = alg_test_comp,
5749                 .fips_allowed = 1,
5750                 .suite = {
5751                         .comp = {
5752                                 .comp = __VECS(zlib_deflate_comp_tv_template),
5753                                 .decomp = __VECS(zlib_deflate_decomp_tv_template)
5754                         }
5755                 }
5756         }, {
5757                 .alg = "zstd",
5758                 .test = alg_test_comp,
5759                 .fips_allowed = 1,
5760                 .suite = {
5761                         .comp = {
5762                                 .comp = __VECS(zstd_comp_tv_template),
5763                                 .decomp = __VECS(zstd_decomp_tv_template)
5764                         }
5765                 }
5766         }
5767 };
5768
5769 static void alg_check_test_descs_order(void)
5770 {
5771         int i;
5772
5773         for (i = 1; i < ARRAY_SIZE(alg_test_descs); i++) {
5774                 int diff = strcmp(alg_test_descs[i - 1].alg,
5775                                   alg_test_descs[i].alg);
5776
5777                 if (WARN_ON(diff > 0)) {
5778                         pr_warn("testmgr: alg_test_descs entries in wrong order: '%s' before '%s'\n",
5779                                 alg_test_descs[i - 1].alg,
5780                                 alg_test_descs[i].alg);
5781                 }
5782
5783                 if (WARN_ON(diff == 0)) {
5784                         pr_warn("testmgr: duplicate alg_test_descs entry: '%s'\n",
5785                                 alg_test_descs[i].alg);
5786                 }
5787         }
5788 }
5789
5790 static void alg_check_testvec_configs(void)
5791 {
5792         int i;
5793
5794         for (i = 0; i < ARRAY_SIZE(default_cipher_testvec_configs); i++)
5795                 WARN_ON(!valid_testvec_config(
5796                                 &default_cipher_testvec_configs[i]));
5797
5798         for (i = 0; i < ARRAY_SIZE(default_hash_testvec_configs); i++)
5799                 WARN_ON(!valid_testvec_config(
5800                                 &default_hash_testvec_configs[i]));
5801 }
5802
5803 static void testmgr_onetime_init(void)
5804 {
5805         alg_check_test_descs_order();
5806         alg_check_testvec_configs();
5807
5808 #ifdef CONFIG_CRYPTO_MANAGER_EXTRA_TESTS
5809         pr_warn("alg: extra crypto tests enabled.  This is intended for developer use only.\n");
5810 #endif
5811 }
5812
5813 static int alg_find_test(const char *alg)
5814 {
5815         int start = 0;
5816         int end = ARRAY_SIZE(alg_test_descs);
5817
5818         while (start < end) {
5819                 int i = (start + end) / 2;
5820                 int diff = strcmp(alg_test_descs[i].alg, alg);
5821
5822                 if (diff > 0) {
5823                         end = i;
5824                         continue;
5825                 }
5826
5827                 if (diff < 0) {
5828                         start = i + 1;
5829                         continue;
5830                 }
5831
5832                 return i;
5833         }
5834
5835         return -1;
5836 }
5837
5838 static int alg_fips_disabled(const char *driver, const char *alg)
5839 {
5840         pr_info("alg: %s (%s) is disabled due to FIPS\n", alg, driver);
5841
5842         return -ECANCELED;
5843 }
5844
5845 int alg_test(const char *driver, const char *alg, u32 type, u32 mask)
5846 {
5847         int i;
5848         int j;
5849         int rc;
5850
5851         if (!fips_enabled && notests) {
5852                 printk_once(KERN_INFO "alg: self-tests disabled\n");
5853                 return 0;
5854         }
5855
5856         DO_ONCE(testmgr_onetime_init);
5857
5858         if ((type & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_CIPHER) {
5859                 char nalg[CRYPTO_MAX_ALG_NAME];
5860
5861                 if (snprintf(nalg, sizeof(nalg), "ecb(%s)", alg) >=
5862                     sizeof(nalg))
5863                         return -ENAMETOOLONG;
5864
5865                 i = alg_find_test(nalg);
5866                 if (i < 0)
5867                         goto notest;
5868
5869                 if (fips_enabled && !alg_test_descs[i].fips_allowed)
5870                         goto non_fips_alg;
5871
5872                 rc = alg_test_cipher(alg_test_descs + i, driver, type, mask);
5873                 goto test_done;
5874         }
5875
5876         i = alg_find_test(alg);
5877         j = alg_find_test(driver);
5878         if (i < 0 && j < 0)
5879                 goto notest;
5880
5881         if (fips_enabled) {
5882                 if (j >= 0 && !alg_test_descs[j].fips_allowed)
5883                         return -EINVAL;
5884
5885                 if (i >= 0 && !alg_test_descs[i].fips_allowed)
5886                         goto non_fips_alg;
5887         }
5888
5889         rc = 0;
5890         if (i >= 0)
5891                 rc |= alg_test_descs[i].test(alg_test_descs + i, driver,
5892                                              type, mask);
5893         if (j >= 0 && j != i)
5894                 rc |= alg_test_descs[j].test(alg_test_descs + j, driver,
5895                                              type, mask);
5896
5897 test_done:
5898         if (rc) {
5899                 if (fips_enabled || panic_on_fail) {
5900                         fips_fail_notify();
5901                         panic("alg: self-tests for %s (%s) failed in %s mode!\n",
5902                               driver, alg,
5903                               fips_enabled ? "fips" : "panic_on_fail");
5904                 }
5905                 pr_warn("alg: self-tests for %s using %s failed (rc=%d)",
5906                         alg, driver, rc);
5907                 WARN(rc != -ENOENT,
5908                      "alg: self-tests for %s using %s failed (rc=%d)",
5909                      alg, driver, rc);
5910         } else {
5911                 if (fips_enabled)
5912                         pr_info("alg: self-tests for %s (%s) passed\n",
5913                                 driver, alg);
5914         }
5915
5916         return rc;
5917
5918 notest:
5919         printk(KERN_INFO "alg: No test for %s (%s)\n", alg, driver);
5920
5921         if (type & CRYPTO_ALG_FIPS_INTERNAL)
5922                 return alg_fips_disabled(driver, alg);
5923
5924         return 0;
5925 non_fips_alg:
5926         return alg_fips_disabled(driver, alg);
5927 }
5928
5929 #endif /* CONFIG_CRYPTO_MANAGER_DISABLE_TESTS */
5930
5931 EXPORT_SYMBOL_GPL(alg_test);