xref: /openssl/apps/speed.c (revision 607a46d0)
1 /*
2  * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10 
11 #undef SECONDS
12 #define SECONDS          3
13 #define PKEY_SECONDS    10
14 
15 #define RSA_SECONDS     PKEY_SECONDS
16 #define DSA_SECONDS     PKEY_SECONDS
17 #define ECDSA_SECONDS   PKEY_SECONDS
18 #define ECDH_SECONDS    PKEY_SECONDS
19 #define EdDSA_SECONDS   PKEY_SECONDS
20 #define SM2_SECONDS     PKEY_SECONDS
21 #define FFDH_SECONDS    PKEY_SECONDS
22 #define KEM_SECONDS     PKEY_SECONDS
23 #define SIG_SECONDS     PKEY_SECONDS
24 
25 #define MAX_ALGNAME_SUFFIX 100
26 
27 /* We need to use some deprecated APIs */
28 #define OPENSSL_SUPPRESS_DEPRECATED
29 #include "internal/e_os.h"
30 
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <math.h>
35 #include "apps.h"
36 #include "progs.h"
37 #include "internal/nelem.h"
38 #include "internal/numbers.h"
39 #include <openssl/crypto.h>
40 #include <openssl/rand.h>
41 #include <openssl/err.h>
42 #include <openssl/evp.h>
43 #include <openssl/objects.h>
44 #include <openssl/core_names.h>
45 #include <openssl/async.h>
46 #include <openssl/provider.h>
47 #if !defined(OPENSSL_SYS_MSDOS)
48 # include <unistd.h>
49 #endif
50 
51 #if defined(_WIN32)
52 # include <windows.h>
53 /*
54  * While VirtualLock is available under the app partition (e.g. UWP),
55  * the headers do not define the API. Define it ourselves instead.
56  */
57 WINBASEAPI
58 BOOL
59 WINAPI
60 VirtualLock(
61     _In_ LPVOID lpAddress,
62     _In_ SIZE_T dwSize
63     );
64 #endif
65 
66 #if defined(OPENSSL_SYS_LINUX)
67 # include <sys/mman.h>
68 #endif
69 
70 #include <openssl/bn.h>
71 #include <openssl/rsa.h>
72 #include "./testrsa.h"
73 #ifndef OPENSSL_NO_DH
74 # include <openssl/dh.h>
75 #endif
76 #include <openssl/x509.h>
77 #include <openssl/dsa.h>
78 #include "./testdsa.h"
79 #include <openssl/modes.h>
80 
81 #ifndef HAVE_FORK
82 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_VXWORKS)
83 #  define HAVE_FORK 0
84 # else
85 #  define HAVE_FORK 1
86 #  include <sys/wait.h>
87 # endif
88 #endif
89 
90 #if HAVE_FORK
91 # undef NO_FORK
92 #else
93 # define NO_FORK
94 #endif
95 
96 #define MAX_MISALIGNMENT 63
97 #define MAX_ECDH_SIZE   256
98 #define MISALIGN        64
99 #define MAX_FFDH_SIZE 1024
100 
101 #ifndef RSA_DEFAULT_PRIME_NUM
102 # define RSA_DEFAULT_PRIME_NUM 2
103 #endif
104 
105 typedef struct openssl_speed_sec_st {
106     int sym;
107     int rsa;
108     int dsa;
109     int ecdsa;
110     int ecdh;
111     int eddsa;
112     int sm2;
113     int ffdh;
114     int kem;
115     int sig;
116 } openssl_speed_sec_t;
117 
118 static volatile int run = 0;
119 
120 static int mr = 0;  /* machine-readeable output format to merge fork results */
121 static int usertime = 1;
122 
123 static double Time_F(int s);
124 static void print_message(const char *s, int length, int tm);
125 static void pkey_print_message(const char *str, const char *str2,
126                                unsigned int bits, int sec);
127 static void kskey_print_message(const char *str, const char *str2, int tm);
128 static void print_result(int alg, int run_no, int count, double time_used);
129 #ifndef NO_FORK
130 static int do_multi(int multi, int size_num);
131 #endif
132 
133 static int domlock = 0;
134 static int testmode = 0;
135 static int testmoderesult = 0;
136 
137 static const int lengths_list[] = {
138     16, 64, 256, 1024, 8 * 1024, 16 * 1024
139 };
140 #define SIZE_NUM         OSSL_NELEM(lengths_list)
141 static const int *lengths = lengths_list;
142 
143 static const int aead_lengths_list[] = {
144     2, 31, 136, 1024, 8 * 1024, 16 * 1024
145 };
146 
147 #define START   0
148 #define STOP    1
149 
150 #ifdef SIGALRM
151 
alarmed(ossl_unused int sig)152 static void alarmed(ossl_unused int sig)
153 {
154     signal(SIGALRM, alarmed);
155     run = 0;
156 }
157 
Time_F(int s)158 static double Time_F(int s)
159 {
160     double ret = app_tminterval(s, usertime);
161     if (s == STOP)
162         alarm(0);
163     return ret;
164 }
165 
166 #elif defined(_WIN32)
167 
168 # define SIGALRM -1
169 
170 static unsigned int lapse;
171 static volatile unsigned int schlock;
alarm_win32(unsigned int secs)172 static void alarm_win32(unsigned int secs)
173 {
174     lapse = secs * 1000;
175 }
176 
177 # define alarm alarm_win32
178 
sleepy(VOID * arg)179 static DWORD WINAPI sleepy(VOID * arg)
180 {
181     schlock = 1;
182     Sleep(lapse);
183     run = 0;
184     return 0;
185 }
186 
Time_F(int s)187 static double Time_F(int s)
188 {
189     double ret;
190     static HANDLE thr;
191 
192     if (s == START) {
193         schlock = 0;
194         thr = CreateThread(NULL, 4096, sleepy, NULL, 0, NULL);
195         if (thr == NULL) {
196             DWORD err = GetLastError();
197             BIO_printf(bio_err, "unable to CreateThread (%lu)", err);
198             ExitProcess(err);
199         }
200         while (!schlock)
201             Sleep(0);           /* scheduler spinlock */
202         ret = app_tminterval(s, usertime);
203     } else {
204         ret = app_tminterval(s, usertime);
205         if (run)
206             TerminateThread(thr, 0);
207         CloseHandle(thr);
208     }
209 
210     return ret;
211 }
212 #else
213 # error "SIGALRM not defined and the platform is not Windows"
214 #endif
215 
216 static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single,
217                              const openssl_speed_sec_t *seconds);
218 
opt_found(const char * name,unsigned int * result,const OPT_PAIR pairs[],unsigned int nbelem)219 static int opt_found(const char *name, unsigned int *result,
220                      const OPT_PAIR pairs[], unsigned int nbelem)
221 {
222     unsigned int idx;
223 
224     for (idx = 0; idx < nbelem; ++idx, pairs++)
225         if (strcmp(name, pairs->name) == 0) {
226             *result = pairs->retval;
227             return 1;
228         }
229     return 0;
230 }
231 #define opt_found(value, pairs, result)\
232     opt_found(value, result, pairs, OSSL_NELEM(pairs))
233 
234 typedef enum OPTION_choice {
235     OPT_COMMON,
236     OPT_ELAPSED, OPT_EVP, OPT_HMAC, OPT_DECRYPT, OPT_ENGINE, OPT_MULTI,
237     OPT_MR, OPT_MB, OPT_MISALIGN, OPT_ASYNCJOBS, OPT_R_ENUM, OPT_PROV_ENUM,
238     OPT_CONFIG, OPT_PRIMES, OPT_SECONDS, OPT_BYTES, OPT_AEAD, OPT_CMAC,
239     OPT_MLOCK, OPT_TESTMODE, OPT_KEM, OPT_SIG
240 } OPTION_CHOICE;
241 
242 const OPTIONS speed_options[] = {
243     {OPT_HELP_STR, 1, '-',
244      "Usage: %s [options] [algorithm...]\n"
245      "All +int options consider prefix '0' as base-8 input, "
246      "prefix '0x'/'0X' as base-16 input.\n"
247     },
248 
249     OPT_SECTION("General"),
250     {"help", OPT_HELP, '-', "Display this summary"},
251     {"mb", OPT_MB, '-',
252      "Enable (tls1>=1) multi-block mode on EVP-named cipher"},
253     {"mr", OPT_MR, '-', "Produce machine readable output"},
254 #ifndef NO_FORK
255     {"multi", OPT_MULTI, 'p', "Run benchmarks in parallel"},
256 #endif
257 #ifndef OPENSSL_NO_ASYNC
258     {"async_jobs", OPT_ASYNCJOBS, 'p',
259      "Enable async mode and start specified number of jobs"},
260 #endif
261 #ifndef OPENSSL_NO_ENGINE
262     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
263 #endif
264     {"primes", OPT_PRIMES, 'p', "Specify number of primes (for RSA only)"},
265     {"mlock", OPT_MLOCK, '-', "Lock memory for better result determinism"},
266     {"testmode", OPT_TESTMODE, '-', "Run the speed command in test mode"},
267     OPT_CONFIG_OPTION,
268 
269     OPT_SECTION("Selection"),
270     {"evp", OPT_EVP, 's', "Use EVP-named cipher or digest"},
271     {"hmac", OPT_HMAC, 's', "HMAC using EVP-named digest"},
272     {"cmac", OPT_CMAC, 's', "CMAC using EVP-named cipher"},
273     {"decrypt", OPT_DECRYPT, '-',
274      "Time decryption instead of encryption (only EVP)"},
275     {"aead", OPT_AEAD, '-',
276      "Benchmark EVP-named AEAD cipher in TLS-like sequence"},
277     {"kem-algorithms", OPT_KEM, '-',
278      "Benchmark KEM algorithms"},
279     {"signature-algorithms", OPT_SIG, '-',
280      "Benchmark signature algorithms"},
281 
282     OPT_SECTION("Timing"),
283     {"elapsed", OPT_ELAPSED, '-',
284      "Use wall-clock time instead of CPU user time as divisor"},
285     {"seconds", OPT_SECONDS, 'p',
286      "Run benchmarks for specified amount of seconds"},
287     {"bytes", OPT_BYTES, 'p',
288      "Run [non-PKI] benchmarks on custom-sized buffer"},
289     {"misalign", OPT_MISALIGN, 'p',
290      "Use specified offset to mis-align buffers"},
291 
292     OPT_R_OPTIONS,
293     OPT_PROV_OPTIONS,
294 
295     OPT_PARAMETERS(),
296     {"algorithm", 0, 0, "Algorithm(s) to test (optional; otherwise tests all)"},
297     {NULL}
298 };
299 
300 enum {
301     D_MD2, D_MDC2, D_MD4, D_MD5, D_SHA1, D_RMD160,
302     D_SHA256, D_SHA512, D_WHIRLPOOL, D_HMAC,
303     D_CBC_DES, D_EDE3_DES, D_RC4, D_CBC_IDEA, D_CBC_SEED,
304     D_CBC_RC2, D_CBC_RC5, D_CBC_BF, D_CBC_CAST,
305     D_CBC_128_AES, D_CBC_192_AES, D_CBC_256_AES,
306     D_CBC_128_CML, D_CBC_192_CML, D_CBC_256_CML,
307     D_EVP, D_GHASH, D_RAND, D_EVP_CMAC, D_KMAC128, D_KMAC256,
308     ALGOR_NUM
309 };
310 /* name of algorithms to test. MUST BE KEEP IN SYNC with above enum ! */
311 static const char *names[ALGOR_NUM] = {
312     "md2", "mdc2", "md4", "md5", "sha1", "rmd160",
313     "sha256", "sha512", "whirlpool", "hmac(sha256)",
314     "des-cbc", "des-ede3", "rc4", "idea-cbc", "seed-cbc",
315     "rc2-cbc", "rc5-cbc", "blowfish", "cast-cbc",
316     "aes-128-cbc", "aes-192-cbc", "aes-256-cbc",
317     "camellia-128-cbc", "camellia-192-cbc", "camellia-256-cbc",
318     "evp", "ghash", "rand", "cmac", "kmac128", "kmac256"
319 };
320 
321 /* list of configured algorithm (remaining), with some few alias */
322 static const OPT_PAIR doit_choices[] = {
323     {"md2", D_MD2},
324     {"mdc2", D_MDC2},
325     {"md4", D_MD4},
326     {"md5", D_MD5},
327     {"hmac", D_HMAC},
328     {"sha1", D_SHA1},
329     {"sha256", D_SHA256},
330     {"sha512", D_SHA512},
331     {"whirlpool", D_WHIRLPOOL},
332     {"ripemd", D_RMD160},
333     {"rmd160", D_RMD160},
334     {"ripemd160", D_RMD160},
335     {"rc4", D_RC4},
336     {"des-cbc", D_CBC_DES},
337     {"des-ede3", D_EDE3_DES},
338     {"aes-128-cbc", D_CBC_128_AES},
339     {"aes-192-cbc", D_CBC_192_AES},
340     {"aes-256-cbc", D_CBC_256_AES},
341     {"camellia-128-cbc", D_CBC_128_CML},
342     {"camellia-192-cbc", D_CBC_192_CML},
343     {"camellia-256-cbc", D_CBC_256_CML},
344     {"rc2-cbc", D_CBC_RC2},
345     {"rc2", D_CBC_RC2},
346     {"rc5-cbc", D_CBC_RC5},
347     {"rc5", D_CBC_RC5},
348     {"idea-cbc", D_CBC_IDEA},
349     {"idea", D_CBC_IDEA},
350     {"seed-cbc", D_CBC_SEED},
351     {"seed", D_CBC_SEED},
352     {"bf-cbc", D_CBC_BF},
353     {"blowfish", D_CBC_BF},
354     {"bf", D_CBC_BF},
355     {"cast-cbc", D_CBC_CAST},
356     {"cast", D_CBC_CAST},
357     {"cast5", D_CBC_CAST},
358     {"ghash", D_GHASH},
359     {"rand", D_RAND},
360     {"kmac128", D_KMAC128},
361     {"kmac256", D_KMAC256},
362 };
363 
364 static double results[ALGOR_NUM][SIZE_NUM];
365 
366 #ifndef OPENSSL_NO_DSA
367 enum { R_DSA_1024, R_DSA_2048, DSA_NUM };
368 static const OPT_PAIR dsa_choices[DSA_NUM] = {
369     {"dsa1024", R_DSA_1024},
370     {"dsa2048", R_DSA_2048}
371 };
372 static double dsa_results[DSA_NUM][2];  /* 2 ops: sign then verify */
373 #endif /* OPENSSL_NO_DSA */
374 
375 enum {
376     R_RSA_512, R_RSA_1024, R_RSA_2048, R_RSA_3072, R_RSA_4096, R_RSA_7680,
377     R_RSA_15360, RSA_NUM
378 };
379 static const OPT_PAIR rsa_choices[RSA_NUM] = {
380     {"rsa512", R_RSA_512},
381     {"rsa1024", R_RSA_1024},
382     {"rsa2048", R_RSA_2048},
383     {"rsa3072", R_RSA_3072},
384     {"rsa4096", R_RSA_4096},
385     {"rsa7680", R_RSA_7680},
386     {"rsa15360", R_RSA_15360}
387 };
388 
389 static double rsa_results[RSA_NUM][4];  /* 4 ops: sign, verify, encrypt, decrypt */
390 
391 #ifndef OPENSSL_NO_DH
392 enum ff_params_t {
393     R_FFDH_2048, R_FFDH_3072, R_FFDH_4096, R_FFDH_6144, R_FFDH_8192, FFDH_NUM
394 };
395 
396 static const OPT_PAIR ffdh_choices[FFDH_NUM] = {
397     {"ffdh2048", R_FFDH_2048},
398     {"ffdh3072", R_FFDH_3072},
399     {"ffdh4096", R_FFDH_4096},
400     {"ffdh6144", R_FFDH_6144},
401     {"ffdh8192", R_FFDH_8192},
402 };
403 
404 static double ffdh_results[FFDH_NUM][1];  /* 1 op: derivation */
405 #endif /* OPENSSL_NO_DH */
406 
407 enum ec_curves_t {
408     R_EC_P160, R_EC_P192, R_EC_P224, R_EC_P256, R_EC_P384, R_EC_P521,
409 #ifndef OPENSSL_NO_EC2M
410     R_EC_K163, R_EC_K233, R_EC_K283, R_EC_K409, R_EC_K571,
411     R_EC_B163, R_EC_B233, R_EC_B283, R_EC_B409, R_EC_B571,
412 #endif
413     R_EC_BRP256R1, R_EC_BRP256T1, R_EC_BRP384R1, R_EC_BRP384T1,
414     R_EC_BRP512R1, R_EC_BRP512T1, ECDSA_NUM
415 };
416 /* list of ecdsa curves */
417 static const OPT_PAIR ecdsa_choices[ECDSA_NUM] = {
418     {"ecdsap160", R_EC_P160},
419     {"ecdsap192", R_EC_P192},
420     {"ecdsap224", R_EC_P224},
421     {"ecdsap256", R_EC_P256},
422     {"ecdsap384", R_EC_P384},
423     {"ecdsap521", R_EC_P521},
424 #ifndef OPENSSL_NO_EC2M
425     {"ecdsak163", R_EC_K163},
426     {"ecdsak233", R_EC_K233},
427     {"ecdsak283", R_EC_K283},
428     {"ecdsak409", R_EC_K409},
429     {"ecdsak571", R_EC_K571},
430     {"ecdsab163", R_EC_B163},
431     {"ecdsab233", R_EC_B233},
432     {"ecdsab283", R_EC_B283},
433     {"ecdsab409", R_EC_B409},
434     {"ecdsab571", R_EC_B571},
435 #endif
436     {"ecdsabrp256r1", R_EC_BRP256R1},
437     {"ecdsabrp256t1", R_EC_BRP256T1},
438     {"ecdsabrp384r1", R_EC_BRP384R1},
439     {"ecdsabrp384t1", R_EC_BRP384T1},
440     {"ecdsabrp512r1", R_EC_BRP512R1},
441     {"ecdsabrp512t1", R_EC_BRP512T1}
442 };
443 enum {
444 #ifndef OPENSSL_NO_ECX
445     R_EC_X25519 = ECDSA_NUM, R_EC_X448, EC_NUM
446 #else
447     EC_NUM = ECDSA_NUM
448 #endif
449 };
450 /* list of ecdh curves, extension of |ecdsa_choices| list above */
451 static const OPT_PAIR ecdh_choices[EC_NUM] = {
452     {"ecdhp160", R_EC_P160},
453     {"ecdhp192", R_EC_P192},
454     {"ecdhp224", R_EC_P224},
455     {"ecdhp256", R_EC_P256},
456     {"ecdhp384", R_EC_P384},
457     {"ecdhp521", R_EC_P521},
458 #ifndef OPENSSL_NO_EC2M
459     {"ecdhk163", R_EC_K163},
460     {"ecdhk233", R_EC_K233},
461     {"ecdhk283", R_EC_K283},
462     {"ecdhk409", R_EC_K409},
463     {"ecdhk571", R_EC_K571},
464     {"ecdhb163", R_EC_B163},
465     {"ecdhb233", R_EC_B233},
466     {"ecdhb283", R_EC_B283},
467     {"ecdhb409", R_EC_B409},
468     {"ecdhb571", R_EC_B571},
469 #endif
470     {"ecdhbrp256r1", R_EC_BRP256R1},
471     {"ecdhbrp256t1", R_EC_BRP256T1},
472     {"ecdhbrp384r1", R_EC_BRP384R1},
473     {"ecdhbrp384t1", R_EC_BRP384T1},
474     {"ecdhbrp512r1", R_EC_BRP512R1},
475     {"ecdhbrp512t1", R_EC_BRP512T1},
476 #ifndef OPENSSL_NO_ECX
477     {"ecdhx25519", R_EC_X25519},
478     {"ecdhx448", R_EC_X448}
479 #endif
480 };
481 
482 static double ecdh_results[EC_NUM][1];      /* 1 op: derivation */
483 static double ecdsa_results[ECDSA_NUM][2];  /* 2 ops: sign then verify */
484 
485 #ifndef OPENSSL_NO_ECX
486 enum { R_EC_Ed25519, R_EC_Ed448, EdDSA_NUM };
487 static const OPT_PAIR eddsa_choices[EdDSA_NUM] = {
488     {"ed25519", R_EC_Ed25519},
489     {"ed448", R_EC_Ed448}
490 
491 };
492 static double eddsa_results[EdDSA_NUM][2];    /* 2 ops: sign then verify */
493 #endif /* OPENSSL_NO_ECX */
494 
495 #ifndef OPENSSL_NO_SM2
496 enum { R_EC_CURVESM2, SM2_NUM };
497 static const OPT_PAIR sm2_choices[SM2_NUM] = {
498     {"curveSM2", R_EC_CURVESM2}
499 };
500 # define SM2_ID        "TLSv1.3+GM+Cipher+Suite"
501 # define SM2_ID_LEN    sizeof("TLSv1.3+GM+Cipher+Suite") - 1
502 static double sm2_results[SM2_NUM][2];    /* 2 ops: sign then verify */
503 #endif /* OPENSSL_NO_SM2 */
504 
505 #define MAX_KEM_NUM 111
506 static size_t kems_algs_len = 0;
507 static char *kems_algname[MAX_KEM_NUM] = { NULL };
508 static double kems_results[MAX_KEM_NUM][3];  /* keygen, encaps, decaps */
509 
510 #define MAX_SIG_NUM 111
511 static size_t sigs_algs_len = 0;
512 static char *sigs_algname[MAX_SIG_NUM] = { NULL };
513 static double sigs_results[MAX_SIG_NUM][3];  /* keygen, sign, verify */
514 
515 #define COND(unused_cond) (run && count < (testmode ? 1 : INT_MAX))
516 #define COUNT(d) (count)
517 
518 #define TAG_LEN 16
519 
520 static unsigned int mode_op; /* AE Mode of operation */
521 static unsigned int aead = 0; /* AEAD flag */
522 static unsigned char aead_iv[12]; /* For AEAD modes */
523 static unsigned char aad[EVP_AEAD_TLS1_AAD_LEN] = { 0xcc };
524 static int aead_ivlen = sizeof(aead_iv);
525 
526 typedef struct loopargs_st {
527     ASYNC_JOB *inprogress_job;
528     ASYNC_WAIT_CTX *wait_ctx;
529     unsigned char *buf;
530     unsigned char *buf2;
531     unsigned char *buf_malloc;
532     unsigned char *buf2_malloc;
533     unsigned char *key;
534     unsigned char tag[TAG_LEN];
535     size_t buflen;
536     size_t sigsize;
537     size_t encsize;
538     EVP_PKEY_CTX *rsa_sign_ctx[RSA_NUM];
539     EVP_PKEY_CTX *rsa_verify_ctx[RSA_NUM];
540     EVP_PKEY_CTX *rsa_encrypt_ctx[RSA_NUM];
541     EVP_PKEY_CTX *rsa_decrypt_ctx[RSA_NUM];
542 #ifndef OPENSSL_NO_DSA
543     EVP_PKEY_CTX *dsa_sign_ctx[DSA_NUM];
544     EVP_PKEY_CTX *dsa_verify_ctx[DSA_NUM];
545 #endif
546     EVP_PKEY_CTX *ecdsa_sign_ctx[ECDSA_NUM];
547     EVP_PKEY_CTX *ecdsa_verify_ctx[ECDSA_NUM];
548     EVP_PKEY_CTX *ecdh_ctx[EC_NUM];
549 #ifndef OPENSSL_NO_ECX
550     EVP_MD_CTX *eddsa_ctx[EdDSA_NUM];
551     EVP_MD_CTX *eddsa_ctx2[EdDSA_NUM];
552 #endif /* OPENSSL_NO_ECX */
553 #ifndef OPENSSL_NO_SM2
554     EVP_MD_CTX *sm2_ctx[SM2_NUM];
555     EVP_MD_CTX *sm2_vfy_ctx[SM2_NUM];
556     EVP_PKEY *sm2_pkey[SM2_NUM];
557 #endif
558     unsigned char *secret_a;
559     unsigned char *secret_b;
560     size_t outlen[EC_NUM];
561 #ifndef OPENSSL_NO_DH
562     EVP_PKEY_CTX *ffdh_ctx[FFDH_NUM];
563     unsigned char *secret_ff_a;
564     unsigned char *secret_ff_b;
565 #endif
566     EVP_CIPHER_CTX *ctx;
567     EVP_MAC_CTX *mctx;
568     EVP_PKEY_CTX *kem_gen_ctx[MAX_KEM_NUM];
569     EVP_PKEY_CTX *kem_encaps_ctx[MAX_KEM_NUM];
570     EVP_PKEY_CTX *kem_decaps_ctx[MAX_KEM_NUM];
571     size_t kem_out_len[MAX_KEM_NUM];
572     size_t kem_secret_len[MAX_KEM_NUM];
573     unsigned char *kem_out[MAX_KEM_NUM];
574     unsigned char *kem_send_secret[MAX_KEM_NUM];
575     unsigned char *kem_rcv_secret[MAX_KEM_NUM];
576     EVP_PKEY_CTX *sig_gen_ctx[MAX_KEM_NUM];
577     EVP_PKEY_CTX *sig_sign_ctx[MAX_KEM_NUM];
578     EVP_PKEY_CTX *sig_verify_ctx[MAX_KEM_NUM];
579     size_t sig_max_sig_len[MAX_KEM_NUM];
580     size_t sig_act_sig_len[MAX_KEM_NUM];
581     unsigned char *sig_sig[MAX_KEM_NUM];
582 } loopargs_t;
583 static int run_benchmark(int async_jobs, int (*loop_function) (void *),
584                          loopargs_t *loopargs);
585 
586 static unsigned int testnum;
587 
588 static char *evp_mac_mdname = "sha256";
589 static char *evp_hmac_name = NULL;
590 static const char *evp_md_name = NULL;
591 static char *evp_mac_ciphername = "aes-128-cbc";
592 static char *evp_cmac_name = NULL;
593 
dofail(void)594 static void dofail(void)
595 {
596     ERR_print_errors(bio_err);
597     testmoderesult = 1;
598 }
599 
have_md(const char * name)600 static int have_md(const char *name)
601 {
602     int ret = 0;
603     EVP_MD *md = NULL;
604 
605     if (opt_md_silent(name, &md)) {
606         EVP_MD_CTX *ctx = EVP_MD_CTX_new();
607 
608         if (ctx != NULL && EVP_DigestInit(ctx, md) > 0)
609             ret = 1;
610         EVP_MD_CTX_free(ctx);
611         EVP_MD_free(md);
612     }
613     return ret;
614 }
615 
have_cipher(const char * name)616 static int have_cipher(const char *name)
617 {
618     int ret = 0;
619     EVP_CIPHER *cipher = NULL;
620 
621     if (opt_cipher_silent(name, &cipher)) {
622         EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
623 
624         if (ctx != NULL
625             && EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1) > 0)
626             ret = 1;
627         EVP_CIPHER_CTX_free(ctx);
628         EVP_CIPHER_free(cipher);
629     }
630     return ret;
631 }
632 
EVP_Digest_loop(const char * mdname,ossl_unused int algindex,void * args)633 static int EVP_Digest_loop(const char *mdname, ossl_unused int algindex, void *args)
634 {
635     loopargs_t *tempargs = *(loopargs_t **) args;
636     unsigned char *buf = tempargs->buf;
637     unsigned char digest[EVP_MAX_MD_SIZE];
638     int count;
639     EVP_MD *md = NULL;
640     EVP_MD_CTX *ctx = NULL;
641 
642     if (!opt_md_silent(mdname, &md))
643         return -1;
644     if (EVP_MD_xof(md)) {
645         ctx = EVP_MD_CTX_new();
646         if (ctx == NULL) {
647             count = -1;
648             goto out;
649         }
650 
651         for (count = 0; COND(c[algindex][testnum]); count++) {
652              if (!EVP_DigestInit_ex2(ctx, md, NULL)
653                  || !EVP_DigestUpdate(ctx, buf, (size_t)lengths[testnum])
654                  || !EVP_DigestFinalXOF(ctx, digest, sizeof(digest))) {
655                 count = -1;
656                 break;
657             }
658         }
659     } else {
660         for (count = 0; COND(c[algindex][testnum]); count++) {
661             if (!EVP_Digest(buf, (size_t)lengths[testnum], digest, NULL, md,
662                             NULL)) {
663                 count = -1;
664                 break;
665             }
666         }
667     }
668 out:
669     EVP_MD_free(md);
670     EVP_MD_CTX_free(ctx);
671     return count;
672 }
673 
EVP_Digest_md_loop(void * args)674 static int EVP_Digest_md_loop(void *args)
675 {
676     return EVP_Digest_loop(evp_md_name, D_EVP, args);
677 }
678 
EVP_Digest_MD2_loop(void * args)679 static int EVP_Digest_MD2_loop(void *args)
680 {
681     return EVP_Digest_loop("md2", D_MD2, args);
682 }
683 
EVP_Digest_MDC2_loop(void * args)684 static int EVP_Digest_MDC2_loop(void *args)
685 {
686     return EVP_Digest_loop("mdc2", D_MDC2, args);
687 }
688 
EVP_Digest_MD4_loop(void * args)689 static int EVP_Digest_MD4_loop(void *args)
690 {
691     return EVP_Digest_loop("md4", D_MD4, args);
692 }
693 
MD5_loop(void * args)694 static int MD5_loop(void *args)
695 {
696     return EVP_Digest_loop("md5", D_MD5, args);
697 }
698 
mac_setup(const char * name,EVP_MAC ** mac,OSSL_PARAM params[],loopargs_t * loopargs,unsigned int loopargs_len)699 static int mac_setup(const char *name,
700                      EVP_MAC **mac, OSSL_PARAM params[],
701                      loopargs_t *loopargs, unsigned int loopargs_len)
702 {
703     unsigned int i;
704 
705     *mac = EVP_MAC_fetch(app_get0_libctx(), name, app_get0_propq());
706     if (*mac == NULL)
707         return 0;
708 
709     for (i = 0; i < loopargs_len; i++) {
710         loopargs[i].mctx = EVP_MAC_CTX_new(*mac);
711         if (loopargs[i].mctx == NULL)
712             return 0;
713 
714         if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params))
715             return 0;
716     }
717 
718     return 1;
719 }
720 
mac_teardown(EVP_MAC ** mac,loopargs_t * loopargs,unsigned int loopargs_len)721 static void mac_teardown(EVP_MAC **mac,
722                          loopargs_t *loopargs, unsigned int loopargs_len)
723 {
724     unsigned int i;
725 
726     for (i = 0; i < loopargs_len; i++)
727         EVP_MAC_CTX_free(loopargs[i].mctx);
728     EVP_MAC_free(*mac);
729     *mac = NULL;
730 
731     return;
732 }
733 
EVP_MAC_loop(ossl_unused int algindex,void * args)734 static int EVP_MAC_loop(ossl_unused int algindex, void *args)
735 {
736     loopargs_t *tempargs = *(loopargs_t **) args;
737     unsigned char *buf = tempargs->buf;
738     EVP_MAC_CTX *mctx = tempargs->mctx;
739     unsigned char mac[EVP_MAX_MD_SIZE];
740     int count;
741 
742     for (count = 0; COND(c[algindex][testnum]); count++) {
743         size_t outl;
744 
745         if (!EVP_MAC_init(mctx, NULL, 0, NULL)
746             || !EVP_MAC_update(mctx, buf, lengths[testnum])
747             || !EVP_MAC_final(mctx, mac, &outl, sizeof(mac)))
748             return -1;
749     }
750     return count;
751 }
752 
HMAC_loop(void * args)753 static int HMAC_loop(void *args)
754 {
755     return EVP_MAC_loop(D_HMAC, args);
756 }
757 
CMAC_loop(void * args)758 static int CMAC_loop(void *args)
759 {
760     return EVP_MAC_loop(D_EVP_CMAC, args);
761 }
762 
KMAC128_loop(void * args)763 static int KMAC128_loop(void *args)
764 {
765     return EVP_MAC_loop(D_KMAC128, args);
766 }
767 
KMAC256_loop(void * args)768 static int KMAC256_loop(void *args)
769 {
770     return EVP_MAC_loop(D_KMAC256, args);
771 }
772 
SHA1_loop(void * args)773 static int SHA1_loop(void *args)
774 {
775     return EVP_Digest_loop("sha1", D_SHA1, args);
776 }
777 
SHA256_loop(void * args)778 static int SHA256_loop(void *args)
779 {
780     return EVP_Digest_loop("sha256", D_SHA256, args);
781 }
782 
SHA512_loop(void * args)783 static int SHA512_loop(void *args)
784 {
785     return EVP_Digest_loop("sha512", D_SHA512, args);
786 }
787 
WHIRLPOOL_loop(void * args)788 static int WHIRLPOOL_loop(void *args)
789 {
790     return EVP_Digest_loop("whirlpool", D_WHIRLPOOL, args);
791 }
792 
EVP_Digest_RMD160_loop(void * args)793 static int EVP_Digest_RMD160_loop(void *args)
794 {
795     return EVP_Digest_loop("ripemd160", D_RMD160, args);
796 }
797 
798 static int algindex;
799 
EVP_Cipher_loop(void * args)800 static int EVP_Cipher_loop(void *args)
801 {
802     loopargs_t *tempargs = *(loopargs_t **) args;
803     unsigned char *buf = tempargs->buf;
804     int count;
805 
806     if (tempargs->ctx == NULL)
807         return -1;
808     for (count = 0; COND(c[algindex][testnum]); count++)
809         if (EVP_Cipher(tempargs->ctx, buf, buf, (size_t)lengths[testnum]) <= 0)
810             return -1;
811     return count;
812 }
813 
GHASH_loop(void * args)814 static int GHASH_loop(void *args)
815 {
816     loopargs_t *tempargs = *(loopargs_t **) args;
817     unsigned char *buf = tempargs->buf;
818     EVP_MAC_CTX *mctx = tempargs->mctx;
819     int count;
820 
821     /* just do the update in the loop to be comparable with 1.1.1 */
822     for (count = 0; COND(c[D_GHASH][testnum]); count++) {
823         if (!EVP_MAC_update(mctx, buf, lengths[testnum]))
824             return -1;
825     }
826     return count;
827 }
828 
829 #define MAX_BLOCK_SIZE 128
830 
831 static unsigned char iv[2 * MAX_BLOCK_SIZE / 8];
832 
init_evp_cipher_ctx(const char * ciphername,const unsigned char * key,int keylen)833 static EVP_CIPHER_CTX *init_evp_cipher_ctx(const char *ciphername,
834                                            const unsigned char *key,
835                                            int keylen)
836 {
837     EVP_CIPHER_CTX *ctx = NULL;
838     EVP_CIPHER *cipher = NULL;
839 
840     if (!opt_cipher_silent(ciphername, &cipher))
841         return NULL;
842 
843     if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
844         goto end;
845 
846     if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1)) {
847         EVP_CIPHER_CTX_free(ctx);
848         ctx = NULL;
849         goto end;
850     }
851 
852     if (EVP_CIPHER_CTX_set_key_length(ctx, keylen) <= 0) {
853         EVP_CIPHER_CTX_free(ctx);
854         ctx = NULL;
855         goto end;
856     }
857 
858     if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1)) {
859         EVP_CIPHER_CTX_free(ctx);
860         ctx = NULL;
861         goto end;
862     }
863 
864 end:
865     EVP_CIPHER_free(cipher);
866     return ctx;
867 }
868 
RAND_bytes_loop(void * args)869 static int RAND_bytes_loop(void *args)
870 {
871     loopargs_t *tempargs = *(loopargs_t **) args;
872     unsigned char *buf = tempargs->buf;
873     int count;
874 
875     for (count = 0; COND(c[D_RAND][testnum]); count++)
876         RAND_bytes(buf, lengths[testnum]);
877     return count;
878 }
879 
880 static int decrypt = 0;
EVP_Update_loop(void * args)881 static int EVP_Update_loop(void *args)
882 {
883     loopargs_t *tempargs = *(loopargs_t **) args;
884     unsigned char *buf = tempargs->buf;
885     EVP_CIPHER_CTX *ctx = tempargs->ctx;
886     int outl, count, rc;
887 
888     if (decrypt) {
889         for (count = 0; COND(c[D_EVP][testnum]); count++) {
890             rc = EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
891             if (rc != 1) {
892                 /* reset iv in case of counter overflow */
893                 rc = EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1);
894             }
895         }
896     } else {
897         for (count = 0; COND(c[D_EVP][testnum]); count++) {
898             rc = EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
899             if (rc != 1) {
900                 /* reset iv in case of counter overflow */
901                 rc = EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1);
902             }
903         }
904     }
905     if (decrypt)
906         rc = EVP_DecryptFinal_ex(ctx, buf, &outl);
907     else
908         rc = EVP_EncryptFinal_ex(ctx, buf, &outl);
909 
910     if (rc == 0)
911         BIO_printf(bio_err, "Error finalizing cipher loop\n");
912     return count;
913 }
914 
915 /*
916  * To make AEAD benchmarking more relevant perform TLS-like operations,
917  * 13-byte AAD followed by payload. But don't use TLS-formatted AAD, as
918  * payload length is not actually limited by 16KB...
919  * CCM does not support streaming. For the purpose of performance measurement,
920  * each message is encrypted using the same (key,iv)-pair. Do not use this
921  * code in your application.
922  */
EVP_Update_loop_aead_enc(void * args)923 static int EVP_Update_loop_aead_enc(void *args)
924 {
925     loopargs_t *tempargs = *(loopargs_t **) args;
926     unsigned char *buf = tempargs->buf;
927     unsigned char *key = tempargs->key;
928     EVP_CIPHER_CTX *ctx = tempargs->ctx;
929     int outl, count, realcount = 0;
930 
931     for (count = 0; COND(c[D_EVP][testnum]); count++) {
932         /* Set length of iv (Doesn't apply to SIV mode) */
933         if (mode_op != EVP_CIPH_SIV_MODE) {
934             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
935                                      aead_ivlen, NULL)) {
936                 BIO_printf(bio_err, "\nFailed to set iv length\n");
937                 dofail();
938                 exit(1);
939             }
940         }
941         /* Set tag_len (Not for GCM/SIV at encryption stage) */
942         if (mode_op != EVP_CIPH_GCM_MODE
943             && mode_op != EVP_CIPH_SIV_MODE
944             && mode_op != EVP_CIPH_GCM_SIV_MODE) {
945             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
946                                      TAG_LEN, NULL)) {
947                 BIO_printf(bio_err, "\nFailed to set tag length\n");
948                 dofail();
949                 exit(1);
950             }
951         }
952         if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, aead_iv, -1)) {
953             BIO_printf(bio_err, "\nFailed to set key and iv\n");
954             dofail();
955             exit(1);
956         }
957         /* Set total length of input. Only required for CCM */
958         if (mode_op == EVP_CIPH_CCM_MODE) {
959             if (!EVP_EncryptUpdate(ctx, NULL, &outl,
960                                    NULL, lengths[testnum])) {
961                 BIO_printf(bio_err, "\nCouldn't set input text length\n");
962                 dofail();
963                 exit(1);
964             }
965         }
966         if (aead) {
967             if (!EVP_EncryptUpdate(ctx, NULL, &outl, aad, sizeof(aad))) {
968                 BIO_printf(bio_err, "\nCouldn't insert AAD when encrypting\n");
969                 dofail();
970                 exit(1);
971             }
972         }
973         if (!EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum])) {
974             BIO_printf(bio_err, "\nFailed to encrypt the data\n");
975             dofail();
976             exit(1);
977         }
978         if (EVP_EncryptFinal_ex(ctx, buf, &outl))
979             realcount++;
980     }
981     return realcount;
982 }
983 
984 /*
985  * To make AEAD benchmarking more relevant perform TLS-like operations,
986  * 13-byte AAD followed by payload. But don't use TLS-formatted AAD, as
987  * payload length is not actually limited by 16KB...
988  * CCM does not support streaming. For the purpose of performance measurement,
989  * each message is decrypted using the same (key,iv)-pair. Do not use this
990  * code in your application.
991  * For decryption, we will use buf2 to preserve the input text in buf.
992  */
EVP_Update_loop_aead_dec(void * args)993 static int EVP_Update_loop_aead_dec(void *args)
994 {
995     loopargs_t *tempargs = *(loopargs_t **) args;
996     unsigned char *buf = tempargs->buf;
997     unsigned char *outbuf = tempargs->buf2;
998     unsigned char *key = tempargs->key;
999     unsigned char tag[TAG_LEN];
1000     EVP_CIPHER_CTX *ctx = tempargs->ctx;
1001     int outl, count, realcount = 0;
1002 
1003     for (count = 0; COND(c[D_EVP][testnum]); count++) {
1004         /* Set the length of iv (Doesn't apply to SIV mode) */
1005         if (mode_op != EVP_CIPH_SIV_MODE) {
1006             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
1007                                      aead_ivlen, NULL)) {
1008                 BIO_printf(bio_err, "\nFailed to set iv length\n");
1009                 dofail();
1010                 exit(1);
1011             }
1012         }
1013 
1014         /* Set the tag length (Doesn't apply to SIV mode) */
1015         if (mode_op != EVP_CIPH_SIV_MODE
1016             && mode_op != EVP_CIPH_GCM_MODE
1017             && mode_op != EVP_CIPH_GCM_SIV_MODE) {
1018             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
1019                                      TAG_LEN, NULL)) {
1020                 BIO_printf(bio_err, "\nFailed to set tag length\n");
1021                 dofail();
1022                 exit(1);
1023             }
1024         }
1025         if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, aead_iv, -1)) {
1026             BIO_printf(bio_err, "\nFailed to set key and iv\n");
1027             dofail();
1028             exit(1);
1029         }
1030         /* Set iv before decryption (Doesn't apply to SIV mode) */
1031         if (mode_op != EVP_CIPH_SIV_MODE) {
1032             if (!EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, aead_iv)) {
1033                 BIO_printf(bio_err, "\nFailed to set iv\n");
1034                 dofail();
1035                 exit(1);
1036             }
1037         }
1038         memcpy(tag, tempargs->tag, TAG_LEN);
1039 
1040         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
1041                                  TAG_LEN, tag)) {
1042             BIO_printf(bio_err, "\nFailed to set tag\n");
1043             dofail();
1044             exit(1);
1045         }
1046         /* Set the total length of cipher text. Only required for CCM */
1047         if (mode_op == EVP_CIPH_CCM_MODE) {
1048             if (!EVP_DecryptUpdate(ctx, NULL, &outl,
1049                                    NULL, lengths[testnum])) {
1050                 BIO_printf(bio_err, "\nCouldn't set cipher text length\n");
1051                 dofail();
1052                 exit(1);
1053             }
1054         }
1055         if (aead) {
1056             if (!EVP_DecryptUpdate(ctx, NULL, &outl, aad, sizeof(aad))) {
1057                 BIO_printf(bio_err, "\nCouldn't insert AAD when decrypting\n");
1058                 dofail();
1059                 exit(1);
1060             }
1061         }
1062         if (!EVP_DecryptUpdate(ctx, outbuf, &outl, buf, lengths[testnum])) {
1063             BIO_printf(bio_err, "\nFailed to decrypt the data\n");
1064             dofail();
1065             exit(1);
1066         }
1067         if (EVP_DecryptFinal_ex(ctx, outbuf, &outl))
1068             realcount++;
1069     }
1070     return realcount;
1071 }
1072 
RSA_sign_loop(void * args)1073 static int RSA_sign_loop(void *args)
1074 {
1075     loopargs_t *tempargs = *(loopargs_t **) args;
1076     unsigned char *buf = tempargs->buf;
1077     unsigned char *buf2 = tempargs->buf2;
1078     size_t *rsa_num = &tempargs->sigsize;
1079     EVP_PKEY_CTX **rsa_sign_ctx = tempargs->rsa_sign_ctx;
1080     int ret, count;
1081 
1082     for (count = 0; COND(rsa_c[testnum][0]); count++) {
1083         *rsa_num = tempargs->buflen;
1084         ret = EVP_PKEY_sign(rsa_sign_ctx[testnum], buf2, rsa_num, buf, 36);
1085         if (ret <= 0) {
1086             BIO_printf(bio_err, "RSA sign failure\n");
1087             dofail();
1088             count = -1;
1089             break;
1090         }
1091     }
1092     return count;
1093 }
1094 
RSA_verify_loop(void * args)1095 static int RSA_verify_loop(void *args)
1096 {
1097     loopargs_t *tempargs = *(loopargs_t **) args;
1098     unsigned char *buf = tempargs->buf;
1099     unsigned char *buf2 = tempargs->buf2;
1100     size_t rsa_num = tempargs->sigsize;
1101     EVP_PKEY_CTX **rsa_verify_ctx = tempargs->rsa_verify_ctx;
1102     int ret, count;
1103 
1104     for (count = 0; COND(rsa_c[testnum][1]); count++) {
1105         ret = EVP_PKEY_verify(rsa_verify_ctx[testnum], buf2, rsa_num, buf, 36);
1106         if (ret <= 0) {
1107             BIO_printf(bio_err, "RSA verify failure\n");
1108             dofail();
1109             count = -1;
1110             break;
1111         }
1112     }
1113     return count;
1114 }
1115 
RSA_encrypt_loop(void * args)1116 static int RSA_encrypt_loop(void *args)
1117 {
1118     loopargs_t *tempargs = *(loopargs_t **) args;
1119     unsigned char *buf = tempargs->buf;
1120     unsigned char *buf2 = tempargs->buf2;
1121     size_t *rsa_num = &tempargs->encsize;
1122     EVP_PKEY_CTX **rsa_encrypt_ctx = tempargs->rsa_encrypt_ctx;
1123     int ret, count;
1124 
1125     for (count = 0; COND(rsa_c[testnum][2]); count++) {
1126         *rsa_num = tempargs->buflen;
1127         ret = EVP_PKEY_encrypt(rsa_encrypt_ctx[testnum], buf2, rsa_num, buf, 36);
1128         if (ret <= 0) {
1129             BIO_printf(bio_err, "RSA encrypt failure\n");
1130             dofail();
1131             count = -1;
1132             break;
1133         }
1134     }
1135     return count;
1136 }
1137 
RSA_decrypt_loop(void * args)1138 static int RSA_decrypt_loop(void *args)
1139 {
1140     loopargs_t *tempargs = *(loopargs_t **) args;
1141     unsigned char *buf = tempargs->buf;
1142     unsigned char *buf2 = tempargs->buf2;
1143     size_t rsa_num;
1144     EVP_PKEY_CTX **rsa_decrypt_ctx = tempargs->rsa_decrypt_ctx;
1145     int ret, count;
1146 
1147     for (count = 0; COND(rsa_c[testnum][3]); count++) {
1148         rsa_num = tempargs->buflen;
1149         ret = EVP_PKEY_decrypt(rsa_decrypt_ctx[testnum], buf, &rsa_num, buf2, tempargs->encsize);
1150         if (ret <= 0) {
1151             BIO_printf(bio_err, "RSA decrypt failure\n");
1152             dofail();
1153             count = -1;
1154             break;
1155         }
1156     }
1157     return count;
1158 }
1159 
1160 #ifndef OPENSSL_NO_DH
1161 
FFDH_derive_key_loop(void * args)1162 static int FFDH_derive_key_loop(void *args)
1163 {
1164     loopargs_t *tempargs = *(loopargs_t **) args;
1165     EVP_PKEY_CTX *ffdh_ctx = tempargs->ffdh_ctx[testnum];
1166     unsigned char *derived_secret = tempargs->secret_ff_a;
1167     int count;
1168 
1169     for (count = 0; COND(ffdh_c[testnum][0]); count++) {
1170         /* outlen can be overwritten with a too small value (no padding used) */
1171         size_t outlen = MAX_FFDH_SIZE;
1172 
1173         EVP_PKEY_derive(ffdh_ctx, derived_secret, &outlen);
1174     }
1175     return count;
1176 }
1177 #endif /* OPENSSL_NO_DH */
1178 
1179 #ifndef OPENSSL_NO_DSA
DSA_sign_loop(void * args)1180 static int DSA_sign_loop(void *args)
1181 {
1182     loopargs_t *tempargs = *(loopargs_t **) args;
1183     unsigned char *buf = tempargs->buf;
1184     unsigned char *buf2 = tempargs->buf2;
1185     size_t *dsa_num = &tempargs->sigsize;
1186     EVP_PKEY_CTX **dsa_sign_ctx = tempargs->dsa_sign_ctx;
1187     int ret, count;
1188 
1189     for (count = 0; COND(dsa_c[testnum][0]); count++) {
1190         *dsa_num = tempargs->buflen;
1191         ret = EVP_PKEY_sign(dsa_sign_ctx[testnum], buf2, dsa_num, buf, 20);
1192         if (ret <= 0) {
1193             BIO_printf(bio_err, "DSA sign failure\n");
1194             dofail();
1195             count = -1;
1196             break;
1197         }
1198     }
1199     return count;
1200 }
1201 
DSA_verify_loop(void * args)1202 static int DSA_verify_loop(void *args)
1203 {
1204     loopargs_t *tempargs = *(loopargs_t **) args;
1205     unsigned char *buf = tempargs->buf;
1206     unsigned char *buf2 = tempargs->buf2;
1207     size_t dsa_num = tempargs->sigsize;
1208     EVP_PKEY_CTX **dsa_verify_ctx = tempargs->dsa_verify_ctx;
1209     int ret, count;
1210 
1211     for (count = 0; COND(dsa_c[testnum][1]); count++) {
1212         ret = EVP_PKEY_verify(dsa_verify_ctx[testnum], buf2, dsa_num, buf, 20);
1213         if (ret <= 0) {
1214             BIO_printf(bio_err, "DSA verify failure\n");
1215             dofail();
1216             count = -1;
1217             break;
1218         }
1219     }
1220     return count;
1221 }
1222 #endif /* OPENSSL_NO_DSA */
1223 
ECDSA_sign_loop(void * args)1224 static int ECDSA_sign_loop(void *args)
1225 {
1226     loopargs_t *tempargs = *(loopargs_t **) args;
1227     unsigned char *buf = tempargs->buf;
1228     unsigned char *buf2 = tempargs->buf2;
1229     size_t *ecdsa_num = &tempargs->sigsize;
1230     EVP_PKEY_CTX **ecdsa_sign_ctx = tempargs->ecdsa_sign_ctx;
1231     int ret, count;
1232 
1233     for (count = 0; COND(ecdsa_c[testnum][0]); count++) {
1234         *ecdsa_num = tempargs->buflen;
1235         ret = EVP_PKEY_sign(ecdsa_sign_ctx[testnum], buf2, ecdsa_num, buf, 20);
1236         if (ret <= 0) {
1237             BIO_printf(bio_err, "ECDSA sign failure\n");
1238             dofail();
1239             count = -1;
1240             break;
1241         }
1242     }
1243     return count;
1244 }
1245 
ECDSA_verify_loop(void * args)1246 static int ECDSA_verify_loop(void *args)
1247 {
1248     loopargs_t *tempargs = *(loopargs_t **) args;
1249     unsigned char *buf = tempargs->buf;
1250     unsigned char *buf2 = tempargs->buf2;
1251     size_t ecdsa_num = tempargs->sigsize;
1252     EVP_PKEY_CTX **ecdsa_verify_ctx = tempargs->ecdsa_verify_ctx;
1253     int ret, count;
1254 
1255     for (count = 0; COND(ecdsa_c[testnum][1]); count++) {
1256         ret = EVP_PKEY_verify(ecdsa_verify_ctx[testnum], buf2, ecdsa_num,
1257                               buf, 20);
1258         if (ret <= 0) {
1259             BIO_printf(bio_err, "ECDSA verify failure\n");
1260             dofail();
1261             count = -1;
1262             break;
1263         }
1264     }
1265     return count;
1266 }
1267 
1268 /* ******************************************************************** */
1269 
ECDH_EVP_derive_key_loop(void * args)1270 static int ECDH_EVP_derive_key_loop(void *args)
1271 {
1272     loopargs_t *tempargs = *(loopargs_t **) args;
1273     EVP_PKEY_CTX *ctx = tempargs->ecdh_ctx[testnum];
1274     unsigned char *derived_secret = tempargs->secret_a;
1275     int count;
1276     size_t *outlen = &(tempargs->outlen[testnum]);
1277 
1278     for (count = 0; COND(ecdh_c[testnum][0]); count++)
1279         EVP_PKEY_derive(ctx, derived_secret, outlen);
1280 
1281     return count;
1282 }
1283 
1284 #ifndef OPENSSL_NO_ECX
EdDSA_sign_loop(void * args)1285 static int EdDSA_sign_loop(void *args)
1286 {
1287     loopargs_t *tempargs = *(loopargs_t **) args;
1288     unsigned char *buf = tempargs->buf;
1289     EVP_MD_CTX **edctx = tempargs->eddsa_ctx;
1290     unsigned char *eddsasig = tempargs->buf2;
1291     size_t *eddsasigsize = &tempargs->sigsize;
1292     int ret, count;
1293 
1294     for (count = 0; COND(eddsa_c[testnum][0]); count++) {
1295         ret = EVP_DigestSignInit(edctx[testnum], NULL, NULL, NULL, NULL);
1296         if (ret == 0) {
1297             BIO_printf(bio_err, "EdDSA sign init failure\n");
1298             dofail();
1299             count = -1;
1300             break;
1301         }
1302         ret = EVP_DigestSign(edctx[testnum], eddsasig, eddsasigsize, buf, 20);
1303         if (ret == 0) {
1304             BIO_printf(bio_err, "EdDSA sign failure\n");
1305             dofail();
1306             count = -1;
1307             break;
1308         }
1309     }
1310     return count;
1311 }
1312 
EdDSA_verify_loop(void * args)1313 static int EdDSA_verify_loop(void *args)
1314 {
1315     loopargs_t *tempargs = *(loopargs_t **) args;
1316     unsigned char *buf = tempargs->buf;
1317     EVP_MD_CTX **edctx = tempargs->eddsa_ctx2;
1318     unsigned char *eddsasig = tempargs->buf2;
1319     size_t eddsasigsize = tempargs->sigsize;
1320     int ret, count;
1321 
1322     for (count = 0; COND(eddsa_c[testnum][1]); count++) {
1323         ret = EVP_DigestVerifyInit(edctx[testnum], NULL, NULL, NULL, NULL);
1324         if (ret == 0) {
1325             BIO_printf(bio_err, "EdDSA verify init failure\n");
1326             dofail();
1327             count = -1;
1328             break;
1329         }
1330         ret = EVP_DigestVerify(edctx[testnum], eddsasig, eddsasigsize, buf, 20);
1331         if (ret != 1) {
1332             BIO_printf(bio_err, "EdDSA verify failure\n");
1333             dofail();
1334             count = -1;
1335             break;
1336         }
1337     }
1338     return count;
1339 }
1340 #endif /* OPENSSL_NO_ECX */
1341 
1342 #ifndef OPENSSL_NO_SM2
SM2_sign_loop(void * args)1343 static int SM2_sign_loop(void *args)
1344 {
1345     loopargs_t *tempargs = *(loopargs_t **) args;
1346     unsigned char *buf = tempargs->buf;
1347     EVP_MD_CTX **sm2ctx = tempargs->sm2_ctx;
1348     unsigned char *sm2sig = tempargs->buf2;
1349     size_t sm2sigsize;
1350     int ret, count;
1351     EVP_PKEY **sm2_pkey = tempargs->sm2_pkey;
1352     const size_t max_size = EVP_PKEY_get_size(sm2_pkey[testnum]);
1353 
1354     for (count = 0; COND(sm2_c[testnum][0]); count++) {
1355         sm2sigsize = max_size;
1356 
1357         if (!EVP_DigestSignInit(sm2ctx[testnum], NULL, EVP_sm3(),
1358                                 NULL, sm2_pkey[testnum])) {
1359             BIO_printf(bio_err, "SM2 init sign failure\n");
1360             dofail();
1361             count = -1;
1362             break;
1363         }
1364         ret = EVP_DigestSign(sm2ctx[testnum], sm2sig, &sm2sigsize,
1365                              buf, 20);
1366         if (ret == 0) {
1367             BIO_printf(bio_err, "SM2 sign failure\n");
1368             dofail();
1369             count = -1;
1370             break;
1371         }
1372         /* update the latest returned size and always use the fixed buffer size */
1373         tempargs->sigsize = sm2sigsize;
1374     }
1375 
1376     return count;
1377 }
1378 
SM2_verify_loop(void * args)1379 static int SM2_verify_loop(void *args)
1380 {
1381     loopargs_t *tempargs = *(loopargs_t **) args;
1382     unsigned char *buf = tempargs->buf;
1383     EVP_MD_CTX **sm2ctx = tempargs->sm2_vfy_ctx;
1384     unsigned char *sm2sig = tempargs->buf2;
1385     size_t sm2sigsize = tempargs->sigsize;
1386     int ret, count;
1387     EVP_PKEY **sm2_pkey = tempargs->sm2_pkey;
1388 
1389     for (count = 0; COND(sm2_c[testnum][1]); count++) {
1390         if (!EVP_DigestVerifyInit(sm2ctx[testnum], NULL, EVP_sm3(),
1391                                   NULL, sm2_pkey[testnum])) {
1392             BIO_printf(bio_err, "SM2 verify init failure\n");
1393             dofail();
1394             count = -1;
1395             break;
1396         }
1397         ret = EVP_DigestVerify(sm2ctx[testnum], sm2sig, sm2sigsize,
1398                                buf, 20);
1399         if (ret != 1) {
1400             BIO_printf(bio_err, "SM2 verify failure\n");
1401             dofail();
1402             count = -1;
1403             break;
1404         }
1405     }
1406     return count;
1407 }
1408 #endif                         /* OPENSSL_NO_SM2 */
1409 
KEM_keygen_loop(void * args)1410 static int KEM_keygen_loop(void *args)
1411 {
1412     loopargs_t *tempargs = *(loopargs_t **) args;
1413     EVP_PKEY_CTX *ctx = tempargs->kem_gen_ctx[testnum];
1414     EVP_PKEY *pkey = NULL;
1415     int count;
1416 
1417     for (count = 0; COND(kems_c[testnum][0]); count++) {
1418         if (EVP_PKEY_keygen(ctx, &pkey) <= 0)
1419             return -1;
1420         /*
1421          * runtime defined to quite some degree by randomness,
1422          * so performance overhead of _free doesn't impact
1423          * results significantly. In any case this test is
1424          * meant to permit relative algorithm performance
1425          * comparison.
1426          */
1427         EVP_PKEY_free(pkey);
1428         pkey = NULL;
1429     }
1430     return count;
1431 }
1432 
KEM_encaps_loop(void * args)1433 static int KEM_encaps_loop(void *args)
1434 {
1435     loopargs_t *tempargs = *(loopargs_t **) args;
1436     EVP_PKEY_CTX *ctx = tempargs->kem_encaps_ctx[testnum];
1437     size_t out_len = tempargs->kem_out_len[testnum];
1438     size_t secret_len = tempargs->kem_secret_len[testnum];
1439     unsigned char *out = tempargs->kem_out[testnum];
1440     unsigned char *secret = tempargs->kem_send_secret[testnum];
1441     int count;
1442 
1443     for (count = 0; COND(kems_c[testnum][1]); count++) {
1444         if (EVP_PKEY_encapsulate(ctx, out, &out_len, secret, &secret_len) <= 0)
1445             return -1;
1446     }
1447     return count;
1448 }
1449 
KEM_decaps_loop(void * args)1450 static int KEM_decaps_loop(void *args)
1451 {
1452     loopargs_t *tempargs = *(loopargs_t **) args;
1453     EVP_PKEY_CTX *ctx = tempargs->kem_decaps_ctx[testnum];
1454     size_t out_len = tempargs->kem_out_len[testnum];
1455     size_t secret_len = tempargs->kem_secret_len[testnum];
1456     unsigned char *out = tempargs->kem_out[testnum];
1457     unsigned char *secret = tempargs->kem_send_secret[testnum];
1458     int count;
1459 
1460     for (count = 0; COND(kems_c[testnum][2]); count++) {
1461         if (EVP_PKEY_decapsulate(ctx, secret, &secret_len, out, out_len) <= 0)
1462             return -1;
1463     }
1464     return count;
1465 }
1466 
SIG_keygen_loop(void * args)1467 static int SIG_keygen_loop(void *args)
1468 {
1469     loopargs_t *tempargs = *(loopargs_t **) args;
1470     EVP_PKEY_CTX *ctx = tempargs->sig_gen_ctx[testnum];
1471     EVP_PKEY *pkey = NULL;
1472     int count;
1473 
1474     for (count = 0; COND(kems_c[testnum][0]); count++) {
1475         EVP_PKEY_keygen(ctx, &pkey);
1476         /* TBD: How much does free influence runtime? */
1477         EVP_PKEY_free(pkey);
1478         pkey = NULL;
1479     }
1480     return count;
1481 }
1482 
SIG_sign_loop(void * args)1483 static int SIG_sign_loop(void *args)
1484 {
1485     loopargs_t *tempargs = *(loopargs_t **) args;
1486     EVP_PKEY_CTX *ctx = tempargs->sig_sign_ctx[testnum];
1487     /* be sure to not change stored sig: */
1488     unsigned char *sig = app_malloc(tempargs->sig_max_sig_len[testnum],
1489                                     "sig sign loop");
1490     unsigned char md[SHA256_DIGEST_LENGTH] = { 0 };
1491     size_t md_len = SHA256_DIGEST_LENGTH;
1492     int count;
1493 
1494     for (count = 0; COND(kems_c[testnum][1]); count++) {
1495         size_t sig_len = tempargs->sig_max_sig_len[testnum];
1496         int ret = EVP_PKEY_sign(ctx, sig, &sig_len, md, md_len);
1497 
1498         if (ret <= 0) {
1499             BIO_printf(bio_err, "SIG sign failure at count %d\n", count);
1500             dofail();
1501             count = -1;
1502             break;
1503         }
1504     }
1505     OPENSSL_free(sig);
1506     return count;
1507 }
1508 
SIG_verify_loop(void * args)1509 static int SIG_verify_loop(void *args)
1510 {
1511     loopargs_t *tempargs = *(loopargs_t **) args;
1512     EVP_PKEY_CTX *ctx = tempargs->sig_verify_ctx[testnum];
1513     size_t sig_len = tempargs->sig_act_sig_len[testnum];
1514     unsigned char *sig = tempargs->sig_sig[testnum];
1515     unsigned char md[SHA256_DIGEST_LENGTH] = { 0 };
1516     size_t md_len = SHA256_DIGEST_LENGTH;
1517     int count;
1518 
1519     for (count = 0; COND(kems_c[testnum][2]); count++) {
1520         int ret = EVP_PKEY_verify(ctx, sig, sig_len, md, md_len);
1521 
1522         if (ret <= 0) {
1523             BIO_printf(bio_err, "SIG verify failure at count %d\n", count);
1524             dofail();
1525             count = -1;
1526             break;
1527         }
1528 
1529     }
1530     return count;
1531 }
1532 
check_block_size(EVP_CIPHER_CTX * ctx,int length)1533 static int check_block_size(EVP_CIPHER_CTX *ctx, int length)
1534 {
1535     const EVP_CIPHER *ciph = EVP_CIPHER_CTX_get0_cipher(ctx);
1536     int blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
1537 
1538     if (ciph == NULL || blocksize <= 0) {
1539         BIO_printf(bio_err, "\nInvalid cipher!\n");
1540         return 0;
1541     }
1542     if (length % blocksize != 0) {
1543         BIO_printf(bio_err,
1544                    "\nRequested encryption length not a multiple of block size for %s!\n",
1545                    EVP_CIPHER_get0_name(ciph));
1546         return 0;
1547     }
1548     return 1;
1549 }
1550 
run_benchmark(int async_jobs,int (* loop_function)(void *),loopargs_t * loopargs)1551 static int run_benchmark(int async_jobs,
1552                          int (*loop_function) (void *), loopargs_t *loopargs)
1553 {
1554     int job_op_count = 0;
1555     int total_op_count = 0;
1556     int num_inprogress = 0;
1557     int error = 0, i = 0, ret = 0;
1558     OSSL_ASYNC_FD job_fd = 0;
1559     size_t num_job_fds = 0;
1560 
1561     if (async_jobs == 0) {
1562         return loop_function((void *)&loopargs);
1563     }
1564 
1565     for (i = 0; i < async_jobs && !error; i++) {
1566         loopargs_t *looparg_item = loopargs + i;
1567 
1568         /* Copy pointer content (looparg_t item address) into async context */
1569         ret = ASYNC_start_job(&loopargs[i].inprogress_job, loopargs[i].wait_ctx,
1570                               &job_op_count, loop_function,
1571                               (void *)&looparg_item, sizeof(looparg_item));
1572         switch (ret) {
1573         case ASYNC_PAUSE:
1574             ++num_inprogress;
1575             break;
1576         case ASYNC_FINISH:
1577             if (job_op_count == -1) {
1578                 error = 1;
1579             } else {
1580                 total_op_count += job_op_count;
1581             }
1582             break;
1583         case ASYNC_NO_JOBS:
1584         case ASYNC_ERR:
1585             BIO_printf(bio_err, "Failure in the job\n");
1586             dofail();
1587             error = 1;
1588             break;
1589         }
1590     }
1591 
1592     while (num_inprogress > 0) {
1593 #if defined(OPENSSL_SYS_WINDOWS)
1594         DWORD avail = 0;
1595 #elif defined(OPENSSL_SYS_UNIX)
1596         int select_result = 0;
1597         OSSL_ASYNC_FD max_fd = 0;
1598         fd_set waitfdset;
1599 
1600         FD_ZERO(&waitfdset);
1601 
1602         for (i = 0; i < async_jobs && num_inprogress > 0; i++) {
1603             if (loopargs[i].inprogress_job == NULL)
1604                 continue;
1605 
1606             if (!ASYNC_WAIT_CTX_get_all_fds
1607                 (loopargs[i].wait_ctx, NULL, &num_job_fds)
1608                 || num_job_fds > 1) {
1609                 BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n");
1610                 dofail();
1611                 error = 1;
1612                 break;
1613             }
1614             ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd,
1615                                        &num_job_fds);
1616             FD_SET(job_fd, &waitfdset);
1617             if (job_fd > max_fd)
1618                 max_fd = job_fd;
1619         }
1620 
1621         if (max_fd >= (OSSL_ASYNC_FD)FD_SETSIZE) {
1622             BIO_printf(bio_err,
1623                        "Error: max_fd (%d) must be smaller than FD_SETSIZE (%d). "
1624                        "Decrease the value of async_jobs\n",
1625                        max_fd, FD_SETSIZE);
1626             dofail();
1627             error = 1;
1628             break;
1629         }
1630 
1631         select_result = select(max_fd + 1, &waitfdset, NULL, NULL, NULL);
1632         if (select_result == -1 && errno == EINTR)
1633             continue;
1634 
1635         if (select_result == -1) {
1636             BIO_printf(bio_err, "Failure in the select\n");
1637             dofail();
1638             error = 1;
1639             break;
1640         }
1641 
1642         if (select_result == 0)
1643             continue;
1644 #endif
1645 
1646         for (i = 0; i < async_jobs; i++) {
1647             if (loopargs[i].inprogress_job == NULL)
1648                 continue;
1649 
1650             if (!ASYNC_WAIT_CTX_get_all_fds
1651                 (loopargs[i].wait_ctx, NULL, &num_job_fds)
1652                 || num_job_fds > 1) {
1653                 BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n");
1654                 dofail();
1655                 error = 1;
1656                 break;
1657             }
1658             ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd,
1659                                        &num_job_fds);
1660 
1661 #if defined(OPENSSL_SYS_UNIX)
1662             if (num_job_fds == 1 && !FD_ISSET(job_fd, &waitfdset))
1663                 continue;
1664 #elif defined(OPENSSL_SYS_WINDOWS)
1665             if (num_job_fds == 1
1666                 && !PeekNamedPipe(job_fd, NULL, 0, NULL, &avail, NULL)
1667                 && avail > 0)
1668                 continue;
1669 #endif
1670 
1671             ret = ASYNC_start_job(&loopargs[i].inprogress_job,
1672                                   loopargs[i].wait_ctx, &job_op_count,
1673                                   loop_function, (void *)(loopargs + i),
1674                                   sizeof(loopargs_t));
1675             switch (ret) {
1676             case ASYNC_PAUSE:
1677                 break;
1678             case ASYNC_FINISH:
1679                 if (job_op_count == -1) {
1680                     error = 1;
1681                 } else {
1682                     total_op_count += job_op_count;
1683                 }
1684                 --num_inprogress;
1685                 loopargs[i].inprogress_job = NULL;
1686                 break;
1687             case ASYNC_NO_JOBS:
1688             case ASYNC_ERR:
1689                 --num_inprogress;
1690                 loopargs[i].inprogress_job = NULL;
1691                 BIO_printf(bio_err, "Failure in the job\n");
1692                 dofail();
1693                 error = 1;
1694                 break;
1695             }
1696         }
1697     }
1698 
1699     return error ? -1 : total_op_count;
1700 }
1701 
1702 typedef struct ec_curve_st {
1703     const char *name;
1704     unsigned int nid;
1705     unsigned int bits;
1706     size_t sigsize; /* only used for EdDSA curves */
1707 } EC_CURVE;
1708 
get_ecdsa(const EC_CURVE * curve)1709 static EVP_PKEY *get_ecdsa(const EC_CURVE *curve)
1710 {
1711     EVP_PKEY_CTX *kctx = NULL;
1712     EVP_PKEY *key = NULL;
1713 
1714     /* Ensure that the error queue is empty */
1715     if (ERR_peek_error()) {
1716         BIO_printf(bio_err,
1717                    "WARNING: the error queue contains previous unhandled errors.\n");
1718         dofail();
1719     }
1720 
1721     /*
1722      * Let's try to create a ctx directly from the NID: this works for
1723      * curves like Curve25519 that are not implemented through the low
1724      * level EC interface.
1725      * If this fails we try creating a EVP_PKEY_EC generic param ctx,
1726      * then we set the curve by NID before deriving the actual keygen
1727      * ctx for that specific curve.
1728      */
1729     kctx = EVP_PKEY_CTX_new_id(curve->nid, NULL);
1730     if (kctx == NULL) {
1731         EVP_PKEY_CTX *pctx = NULL;
1732         EVP_PKEY *params = NULL;
1733         /*
1734          * If we reach this code EVP_PKEY_CTX_new_id() failed and a
1735          * "int_ctx_new:unsupported algorithm" error was added to the
1736          * error queue.
1737          * We remove it from the error queue as we are handling it.
1738          */
1739         unsigned long error = ERR_peek_error();
1740 
1741         if (error == ERR_peek_last_error() /* oldest and latest errors match */
1742             /* check that the error origin matches */
1743             && ERR_GET_LIB(error) == ERR_LIB_EVP
1744             && (ERR_GET_REASON(error) == EVP_R_UNSUPPORTED_ALGORITHM
1745                 || ERR_GET_REASON(error) == ERR_R_UNSUPPORTED))
1746             ERR_get_error(); /* pop error from queue */
1747         if (ERR_peek_error()) {
1748             BIO_printf(bio_err,
1749                        "Unhandled error in the error queue during EC key setup.\n");
1750             dofail();
1751             return NULL;
1752         }
1753 
1754         /* Create the context for parameter generation */
1755         if ((pctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) == NULL
1756             || EVP_PKEY_paramgen_init(pctx) <= 0
1757             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
1758                                                       curve->nid) <= 0
1759             || EVP_PKEY_paramgen(pctx, &params) <= 0) {
1760             BIO_printf(bio_err, "EC params init failure.\n");
1761             dofail();
1762             EVP_PKEY_CTX_free(pctx);
1763             return NULL;
1764         }
1765         EVP_PKEY_CTX_free(pctx);
1766 
1767         /* Create the context for the key generation */
1768         kctx = EVP_PKEY_CTX_new(params, NULL);
1769         EVP_PKEY_free(params);
1770     }
1771     if (kctx == NULL
1772         || EVP_PKEY_keygen_init(kctx) <= 0
1773         || EVP_PKEY_keygen(kctx, &key) <= 0) {
1774         BIO_printf(bio_err, "EC key generation failure.\n");
1775         dofail();
1776         key = NULL;
1777     }
1778     EVP_PKEY_CTX_free(kctx);
1779     return key;
1780 }
1781 
1782 #define stop_it(do_it, test_num)\
1783     memset(do_it + test_num, 0, OSSL_NELEM(do_it) - test_num);
1784 
1785 /* Checks to see if algorithms are fetchable */
1786 #define IS_FETCHABLE(type, TYPE)                                \
1787     static int is_ ## type ## _fetchable(const TYPE *alg)       \
1788     {                                                           \
1789         TYPE *impl;                                             \
1790         const char *propq = app_get0_propq();                   \
1791         OSSL_LIB_CTX *libctx = app_get0_libctx();               \
1792         const char *name = TYPE ## _get0_name(alg);             \
1793                                                                 \
1794         ERR_set_mark();                                         \
1795         impl = TYPE ## _fetch(libctx, name, propq);             \
1796         ERR_pop_to_mark();                                      \
1797         if (impl == NULL)                                       \
1798             return 0;                                           \
1799         TYPE ## _free(impl);                                    \
1800         return 1;                                               \
1801     }
1802 
IS_FETCHABLE(signature,EVP_SIGNATURE)1803 IS_FETCHABLE(signature, EVP_SIGNATURE)
1804 IS_FETCHABLE(kem, EVP_KEM)
1805 
1806 DEFINE_STACK_OF(EVP_KEM)
1807 
1808 static int kems_cmp(const EVP_KEM * const *a,
1809                     const EVP_KEM * const *b)
1810 {
1811     return strcmp(OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*a)),
1812                   OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*b)));
1813 }
1814 
collect_kem(EVP_KEM * kem,void * stack)1815 static void collect_kem(EVP_KEM *kem, void *stack)
1816 {
1817     STACK_OF(EVP_KEM) *kem_stack = stack;
1818 
1819     if (is_kem_fetchable(kem)
1820             && sk_EVP_KEM_push(kem_stack, kem) > 0) {
1821         EVP_KEM_up_ref(kem);
1822     }
1823 }
1824 
kem_locate(const char * algo,unsigned int * idx)1825 static int kem_locate(const char *algo, unsigned int *idx)
1826 {
1827     unsigned int i;
1828 
1829     for (i = 0; i < kems_algs_len; i++) {
1830         if (strcmp(kems_algname[i], algo) == 0) {
1831             *idx = i;
1832             return 1;
1833         }
1834     }
1835     return 0;
1836 }
1837 
DEFINE_STACK_OF(EVP_SIGNATURE)1838 DEFINE_STACK_OF(EVP_SIGNATURE)
1839 
1840 static int signatures_cmp(const EVP_SIGNATURE * const *a,
1841                           const EVP_SIGNATURE * const *b)
1842 {
1843     return strcmp(OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*a)),
1844                   OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*b)));
1845 }
1846 
collect_signatures(EVP_SIGNATURE * sig,void * stack)1847 static void collect_signatures(EVP_SIGNATURE *sig, void *stack)
1848 {
1849     STACK_OF(EVP_SIGNATURE) *sig_stack = stack;
1850 
1851     if (is_signature_fetchable(sig)
1852             && sk_EVP_SIGNATURE_push(sig_stack, sig) > 0)
1853         EVP_SIGNATURE_up_ref(sig);
1854 }
1855 
sig_locate(const char * algo,unsigned int * idx)1856 static int sig_locate(const char *algo, unsigned int *idx)
1857 {
1858     unsigned int i;
1859 
1860     for (i = 0; i < sigs_algs_len; i++) {
1861         if (strcmp(sigs_algname[i], algo) == 0) {
1862             *idx = i;
1863             return 1;
1864         }
1865     }
1866     return 0;
1867 }
1868 
get_max(const uint8_t doit[],size_t algs_len)1869 static int get_max(const uint8_t doit[], size_t algs_len) {
1870     size_t i = 0;
1871     int maxcnt = 0;
1872 
1873     for (i = 0; i < algs_len; i++)
1874         if (maxcnt < doit[i]) maxcnt = doit[i];
1875     return maxcnt;
1876 }
1877 
speed_main(int argc,char ** argv)1878 int speed_main(int argc, char **argv)
1879 {
1880     CONF *conf = NULL;
1881     ENGINE *e = NULL;
1882     loopargs_t *loopargs = NULL;
1883     const char *prog;
1884     const char *engine_id = NULL;
1885     EVP_CIPHER *evp_cipher = NULL;
1886     EVP_MAC *mac = NULL;
1887     double d = 0.0;
1888     OPTION_CHOICE o;
1889     int async_init = 0, multiblock = 0, pr_header = 0;
1890     uint8_t doit[ALGOR_NUM] = { 0 };
1891     int ret = 1, misalign = 0, lengths_single = 0;
1892     STACK_OF(EVP_KEM) *kem_stack = NULL;
1893     STACK_OF(EVP_SIGNATURE) *sig_stack = NULL;
1894     long count = 0;
1895     unsigned int size_num = SIZE_NUM;
1896     unsigned int i, k, loopargs_len = 0, async_jobs = 0;
1897     unsigned int idx;
1898     int keylen = 0;
1899     int buflen;
1900     size_t declen;
1901     BIGNUM *bn = NULL;
1902     EVP_PKEY_CTX *genctx = NULL;
1903 #ifndef NO_FORK
1904     int multi = 0;
1905 #endif
1906     long op_count = 1;
1907     openssl_speed_sec_t seconds = { SECONDS, RSA_SECONDS, DSA_SECONDS,
1908                                     ECDSA_SECONDS, ECDH_SECONDS,
1909                                     EdDSA_SECONDS, SM2_SECONDS,
1910                                     FFDH_SECONDS, KEM_SECONDS,
1911                                     SIG_SECONDS };
1912 
1913     static const unsigned char key32[32] = {
1914         0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
1915         0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
1916         0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
1917         0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56
1918     };
1919     static const unsigned char deskey[] = {
1920         0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, /* key1 */
1921         0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, /* key2 */
1922         0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34  /* key3 */
1923     };
1924     static const struct {
1925         const unsigned char *data;
1926         unsigned int length;
1927         unsigned int bits;
1928     } rsa_keys[] = {
1929         {   test512,   sizeof(test512),   512 },
1930         {  test1024,  sizeof(test1024),  1024 },
1931         {  test2048,  sizeof(test2048),  2048 },
1932         {  test3072,  sizeof(test3072),  3072 },
1933         {  test4096,  sizeof(test4096),  4096 },
1934         {  test7680,  sizeof(test7680),  7680 },
1935         { test15360, sizeof(test15360), 15360 }
1936     };
1937     uint8_t rsa_doit[RSA_NUM] = { 0 };
1938     int primes = RSA_DEFAULT_PRIME_NUM;
1939 #ifndef OPENSSL_NO_DH
1940     typedef struct ffdh_params_st {
1941         const char *name;
1942         unsigned int nid;
1943         unsigned int bits;
1944     } FFDH_PARAMS;
1945 
1946     static const FFDH_PARAMS ffdh_params[FFDH_NUM] = {
1947         {"ffdh2048", NID_ffdhe2048, 2048},
1948         {"ffdh3072", NID_ffdhe3072, 3072},
1949         {"ffdh4096", NID_ffdhe4096, 4096},
1950         {"ffdh6144", NID_ffdhe6144, 6144},
1951         {"ffdh8192", NID_ffdhe8192, 8192}
1952     };
1953     uint8_t ffdh_doit[FFDH_NUM] = { 0 };
1954 
1955 #endif /* OPENSSL_NO_DH */
1956 #ifndef OPENSSL_NO_DSA
1957     static const unsigned int dsa_bits[DSA_NUM] = { 1024, 2048 };
1958     uint8_t dsa_doit[DSA_NUM] = { 0 };
1959 #endif /* OPENSSL_NO_DSA */
1960     /*
1961      * We only test over the following curves as they are representative, To
1962      * add tests over more curves, simply add the curve NID and curve name to
1963      * the following arrays and increase the |ecdh_choices| and |ecdsa_choices|
1964      * lists accordingly.
1965      */
1966     static const EC_CURVE ec_curves[EC_NUM] = {
1967         /* Prime Curves */
1968         {"secp160r1", NID_secp160r1, 160},
1969         {"nistp192", NID_X9_62_prime192v1, 192},
1970         {"nistp224", NID_secp224r1, 224},
1971         {"nistp256", NID_X9_62_prime256v1, 256},
1972         {"nistp384", NID_secp384r1, 384},
1973         {"nistp521", NID_secp521r1, 521},
1974 #ifndef OPENSSL_NO_EC2M
1975         /* Binary Curves */
1976         {"nistk163", NID_sect163k1, 163},
1977         {"nistk233", NID_sect233k1, 233},
1978         {"nistk283", NID_sect283k1, 283},
1979         {"nistk409", NID_sect409k1, 409},
1980         {"nistk571", NID_sect571k1, 571},
1981         {"nistb163", NID_sect163r2, 163},
1982         {"nistb233", NID_sect233r1, 233},
1983         {"nistb283", NID_sect283r1, 283},
1984         {"nistb409", NID_sect409r1, 409},
1985         {"nistb571", NID_sect571r1, 571},
1986 #endif
1987         {"brainpoolP256r1", NID_brainpoolP256r1, 256},
1988         {"brainpoolP256t1", NID_brainpoolP256t1, 256},
1989         {"brainpoolP384r1", NID_brainpoolP384r1, 384},
1990         {"brainpoolP384t1", NID_brainpoolP384t1, 384},
1991         {"brainpoolP512r1", NID_brainpoolP512r1, 512},
1992         {"brainpoolP512t1", NID_brainpoolP512t1, 512},
1993 #ifndef OPENSSL_NO_ECX
1994         /* Other and ECDH only ones */
1995         {"X25519", NID_X25519, 253},
1996         {"X448", NID_X448, 448}
1997 #endif
1998     };
1999 #ifndef OPENSSL_NO_ECX
2000     static const EC_CURVE ed_curves[EdDSA_NUM] = {
2001         /* EdDSA */
2002         {"Ed25519", NID_ED25519, 253, 64},
2003         {"Ed448", NID_ED448, 456, 114}
2004     };
2005 #endif /* OPENSSL_NO_ECX */
2006 #ifndef OPENSSL_NO_SM2
2007     static const EC_CURVE sm2_curves[SM2_NUM] = {
2008         /* SM2 */
2009         {"CurveSM2", NID_sm2, 256}
2010     };
2011     uint8_t sm2_doit[SM2_NUM] = { 0 };
2012 #endif
2013     uint8_t ecdsa_doit[ECDSA_NUM] = { 0 };
2014     uint8_t ecdh_doit[EC_NUM] = { 0 };
2015 #ifndef OPENSSL_NO_ECX
2016     uint8_t eddsa_doit[EdDSA_NUM] = { 0 };
2017 #endif /* OPENSSL_NO_ECX */
2018 
2019     uint8_t kems_doit[MAX_KEM_NUM] = { 0 };
2020     uint8_t sigs_doit[MAX_SIG_NUM] = { 0 };
2021 
2022     uint8_t do_kems = 0;
2023     uint8_t do_sigs = 0;
2024 
2025     /* checks declared curves against choices list. */
2026 #ifndef OPENSSL_NO_ECX
2027     OPENSSL_assert(ed_curves[EdDSA_NUM - 1].nid == NID_ED448);
2028     OPENSSL_assert(strcmp(eddsa_choices[EdDSA_NUM - 1].name, "ed448") == 0);
2029 
2030     OPENSSL_assert(ec_curves[EC_NUM - 1].nid == NID_X448);
2031     OPENSSL_assert(strcmp(ecdh_choices[EC_NUM - 1].name, "ecdhx448") == 0);
2032 
2033     OPENSSL_assert(ec_curves[ECDSA_NUM - 1].nid == NID_brainpoolP512t1);
2034     OPENSSL_assert(strcmp(ecdsa_choices[ECDSA_NUM - 1].name, "ecdsabrp512t1") == 0);
2035 #endif /* OPENSSL_NO_ECX */
2036 
2037 #ifndef OPENSSL_NO_SM2
2038     OPENSSL_assert(sm2_curves[SM2_NUM - 1].nid == NID_sm2);
2039     OPENSSL_assert(strcmp(sm2_choices[SM2_NUM - 1].name, "curveSM2") == 0);
2040 #endif
2041 
2042     prog = opt_init(argc, argv, speed_options);
2043     while ((o = opt_next()) != OPT_EOF) {
2044         switch (o) {
2045         case OPT_EOF:
2046         case OPT_ERR:
2047  opterr:
2048             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
2049             goto end;
2050         case OPT_HELP:
2051             opt_help(speed_options);
2052             ret = 0;
2053             goto end;
2054         case OPT_ELAPSED:
2055             usertime = 0;
2056             break;
2057         case OPT_EVP:
2058             if (doit[D_EVP]) {
2059                 BIO_printf(bio_err, "%s: -evp option cannot be used more than once\n", prog);
2060                 goto opterr;
2061             }
2062             ERR_set_mark();
2063             if (!opt_cipher_silent(opt_arg(), &evp_cipher)) {
2064                 if (have_md(opt_arg()))
2065                     evp_md_name = opt_arg();
2066             }
2067             if (evp_cipher == NULL && evp_md_name == NULL) {
2068                 ERR_clear_last_mark();
2069                 BIO_printf(bio_err,
2070                            "%s: %s is an unknown cipher or digest\n",
2071                            prog, opt_arg());
2072                 goto end;
2073             }
2074             ERR_pop_to_mark();
2075             doit[D_EVP] = 1;
2076             break;
2077         case OPT_HMAC:
2078             if (!have_md(opt_arg())) {
2079                 BIO_printf(bio_err, "%s: %s is an unknown digest\n",
2080                            prog, opt_arg());
2081                 goto end;
2082             }
2083             evp_mac_mdname = opt_arg();
2084             doit[D_HMAC] = 1;
2085             break;
2086         case OPT_CMAC:
2087             if (!have_cipher(opt_arg())) {
2088                 BIO_printf(bio_err, "%s: %s is an unknown cipher\n",
2089                            prog, opt_arg());
2090                 goto end;
2091             }
2092             evp_mac_ciphername = opt_arg();
2093             doit[D_EVP_CMAC] = 1;
2094             break;
2095         case OPT_DECRYPT:
2096             decrypt = 1;
2097             break;
2098         case OPT_ENGINE:
2099             /*
2100              * In a forked execution, an engine might need to be
2101              * initialised by each child process, not by the parent.
2102              * So store the name here and run setup_engine() later on.
2103              */
2104             engine_id = opt_arg();
2105             break;
2106         case OPT_MULTI:
2107 #ifndef NO_FORK
2108             multi = opt_int_arg();
2109             if ((size_t)multi >= SIZE_MAX / sizeof(int)) {
2110                 BIO_printf(bio_err, "%s: multi argument too large\n", prog);
2111                 return 0;
2112             }
2113 #endif
2114             break;
2115         case OPT_ASYNCJOBS:
2116 #ifndef OPENSSL_NO_ASYNC
2117             async_jobs = opt_int_arg();
2118             if (async_jobs > 99999) {
2119                 BIO_printf(bio_err, "%s: too many async_jobs\n", prog);
2120                 goto opterr;
2121             }
2122             if (!ASYNC_is_capable()) {
2123                 BIO_printf(bio_err,
2124                            "%s: async_jobs specified but async not supported\n",
2125                            prog);
2126                 if (testmode)
2127                     /* Return success in the testmode. */
2128                     return 0;
2129                 goto opterr;
2130             }
2131 #endif
2132             break;
2133         case OPT_MISALIGN:
2134             misalign = opt_int_arg();
2135             if (misalign > MISALIGN) {
2136                 BIO_printf(bio_err,
2137                            "%s: Maximum offset is %d\n", prog, MISALIGN);
2138                 goto opterr;
2139             }
2140             break;
2141         case OPT_MR:
2142             mr = 1;
2143             break;
2144         case OPT_MB:
2145             multiblock = 1;
2146 #ifdef OPENSSL_NO_MULTIBLOCK
2147             BIO_printf(bio_err,
2148                        "%s: -mb specified but multi-block support is disabled\n",
2149                        prog);
2150             goto end;
2151 #endif
2152             break;
2153         case OPT_R_CASES:
2154             if (!opt_rand(o))
2155                 goto end;
2156             break;
2157         case OPT_PROV_CASES:
2158             if (!opt_provider(o))
2159                 goto end;
2160             break;
2161         case OPT_CONFIG:
2162             conf = app_load_config_modules(opt_arg());
2163             if (conf == NULL)
2164                 goto end;
2165             break;
2166         case OPT_PRIMES:
2167             primes = opt_int_arg();
2168             break;
2169         case OPT_SECONDS:
2170             seconds.sym = seconds.rsa = seconds.dsa = seconds.ecdsa
2171                         = seconds.ecdh = seconds.eddsa
2172                         = seconds.sm2 = seconds.ffdh
2173                         = seconds.kem = seconds.sig = opt_int_arg();
2174             break;
2175         case OPT_BYTES:
2176             lengths_single = opt_int_arg();
2177             lengths = &lengths_single;
2178             size_num = 1;
2179             break;
2180         case OPT_AEAD:
2181             aead = 1;
2182             break;
2183         case OPT_KEM:
2184             do_kems = 1;
2185             break;
2186         case OPT_SIG:
2187             do_sigs = 1;
2188             break;
2189         case OPT_MLOCK:
2190             domlock = 1;
2191 #if !defined(_WIN32) && !defined(OPENSSL_SYS_LINUX)
2192             BIO_printf(bio_err,
2193                        "%s: -mlock not supported on this platform\n",
2194                        prog);
2195             goto end;
2196 #endif
2197             break;
2198         case OPT_TESTMODE:
2199             testmode = 1;
2200             break;
2201         }
2202     }
2203 
2204     /* find all KEMs currently available */
2205     kem_stack = sk_EVP_KEM_new(kems_cmp);
2206     EVP_KEM_do_all_provided(app_get0_libctx(), collect_kem, kem_stack);
2207 
2208     kems_algs_len = 0;
2209 
2210     for (idx = 0; idx < (unsigned int)sk_EVP_KEM_num(kem_stack); idx++) {
2211         EVP_KEM *kem = sk_EVP_KEM_value(kem_stack, idx);
2212 
2213         if (strcmp(EVP_KEM_get0_name(kem), "RSA") == 0) {
2214             if (kems_algs_len + OSSL_NELEM(rsa_choices) >= MAX_KEM_NUM) {
2215                 BIO_printf(bio_err,
2216                            "Too many KEMs registered. Change MAX_KEM_NUM.\n");
2217                 goto end;
2218             }
2219             for (i = 0; i < OSSL_NELEM(rsa_choices); i++) {
2220                 kems_doit[kems_algs_len] = 1;
2221                 kems_algname[kems_algs_len++] = OPENSSL_strdup(rsa_choices[i].name);
2222             }
2223         } else if (strcmp(EVP_KEM_get0_name(kem), "EC") == 0) {
2224             if (kems_algs_len + 3 >= MAX_KEM_NUM) {
2225                 BIO_printf(bio_err,
2226                            "Too many KEMs registered. Change MAX_KEM_NUM.\n");
2227                 goto end;
2228             }
2229             kems_doit[kems_algs_len] = 1;
2230             kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-256");
2231             kems_doit[kems_algs_len] = 1;
2232             kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-384");
2233             kems_doit[kems_algs_len] = 1;
2234             kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-521");
2235         } else {
2236             if (kems_algs_len + 1 >= MAX_KEM_NUM) {
2237                 BIO_printf(bio_err,
2238                            "Too many KEMs registered. Change MAX_KEM_NUM.\n");
2239                 goto end;
2240             }
2241             kems_doit[kems_algs_len] = 1;
2242             kems_algname[kems_algs_len++] = OPENSSL_strdup(EVP_KEM_get0_name(kem));
2243         }
2244     }
2245     sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free);
2246     kem_stack = NULL;
2247 
2248     /* find all SIGNATUREs currently available */
2249     sig_stack = sk_EVP_SIGNATURE_new(signatures_cmp);
2250     EVP_SIGNATURE_do_all_provided(app_get0_libctx(), collect_signatures, sig_stack);
2251 
2252     sigs_algs_len = 0;
2253 
2254     for (idx = 0; idx < (unsigned int)sk_EVP_SIGNATURE_num(sig_stack); idx++) {
2255         EVP_SIGNATURE *s = sk_EVP_SIGNATURE_value(sig_stack, idx);
2256         const char *sig_name = EVP_SIGNATURE_get0_name(s);
2257 
2258         if (strcmp(sig_name, "RSA") == 0) {
2259             if (sigs_algs_len + OSSL_NELEM(rsa_choices) >= MAX_SIG_NUM) {
2260                 BIO_printf(bio_err,
2261                            "Too many signatures registered. Change MAX_SIG_NUM.\n");
2262                 goto end;
2263             }
2264             for (i = 0; i < OSSL_NELEM(rsa_choices); i++) {
2265                 sigs_doit[sigs_algs_len] = 1;
2266                 sigs_algname[sigs_algs_len++] = OPENSSL_strdup(rsa_choices[i].name);
2267             }
2268         }
2269 #ifndef OPENSSL_NO_DSA
2270         else if (strcmp(sig_name, "DSA") == 0) {
2271             if (sigs_algs_len + DSA_NUM >= MAX_SIG_NUM) {
2272                 BIO_printf(bio_err,
2273                            "Too many signatures registered. Change MAX_SIG_NUM.\n");
2274                 goto end;
2275             }
2276             for (i = 0; i < DSA_NUM; i++) {
2277                 sigs_doit[sigs_algs_len] = 1;
2278                 sigs_algname[sigs_algs_len++] = OPENSSL_strdup(dsa_choices[i].name);
2279             }
2280         }
2281 #endif /* OPENSSL_NO_DSA */
2282         /* skipping these algs as tested elsewhere - and b/o setup is a pain */
2283         else if (strcmp(sig_name, "ED25519") &&
2284                  strcmp(sig_name, "ED448") &&
2285                  strcmp(sig_name, "ECDSA") &&
2286                  strcmp(sig_name, "HMAC") &&
2287                  strcmp(sig_name, "SIPHASH") &&
2288                  strcmp(sig_name, "POLY1305") &&
2289                  strcmp(sig_name, "CMAC") &&
2290                  strcmp(sig_name, "SM2")) { /* skip alg */
2291             if (sigs_algs_len + 1 >= MAX_SIG_NUM) {
2292                 BIO_printf(bio_err,
2293                            "Too many signatures registered. Change MAX_SIG_NUM.\n");
2294                 goto end;
2295             }
2296             /* activate this provider algorithm */
2297             sigs_doit[sigs_algs_len] = 1;
2298             sigs_algname[sigs_algs_len++] = OPENSSL_strdup(sig_name);
2299         }
2300     }
2301     sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free);
2302     sig_stack = NULL;
2303 
2304     /* Remaining arguments are algorithms. */
2305     argc = opt_num_rest();
2306     argv = opt_rest();
2307 
2308     if (!app_RAND_load())
2309         goto end;
2310 
2311     for (; *argv; argv++) {
2312         const char *algo = *argv;
2313         int algo_found = 0;
2314 
2315         if (opt_found(algo, doit_choices, &i)) {
2316             doit[i] = 1;
2317             algo_found = 1;
2318         }
2319         if (strcmp(algo, "des") == 0) {
2320             doit[D_CBC_DES] = doit[D_EDE3_DES] = 1;
2321             algo_found = 1;
2322         }
2323         if (strcmp(algo, "sha") == 0) {
2324             doit[D_SHA1] = doit[D_SHA256] = doit[D_SHA512] = 1;
2325             algo_found = 1;
2326         }
2327 #ifndef OPENSSL_NO_DEPRECATED_3_0
2328         if (strcmp(algo, "openssl") == 0) /* just for compatibility */
2329             algo_found = 1;
2330 #endif
2331         if (HAS_PREFIX(algo, "rsa")) {
2332             if (algo[sizeof("rsa") - 1] == '\0') {
2333                 memset(rsa_doit, 1, sizeof(rsa_doit));
2334                 algo_found = 1;
2335             }
2336             if (opt_found(algo, rsa_choices, &i)) {
2337                 rsa_doit[i] = 1;
2338                 algo_found = 1;
2339             }
2340         }
2341 #ifndef OPENSSL_NO_DH
2342         if (HAS_PREFIX(algo, "ffdh")) {
2343             if (algo[sizeof("ffdh") - 1] == '\0') {
2344                 memset(ffdh_doit, 1, sizeof(ffdh_doit));
2345                 algo_found = 1;
2346             }
2347             if (opt_found(algo, ffdh_choices, &i)) {
2348                 ffdh_doit[i] = 2;
2349                 algo_found = 1;
2350             }
2351         }
2352 #endif
2353 #ifndef OPENSSL_NO_DSA
2354         if (HAS_PREFIX(algo, "dsa")) {
2355             if (algo[sizeof("dsa") - 1] == '\0') {
2356                 memset(dsa_doit, 1, sizeof(dsa_doit));
2357                 algo_found = 1;
2358             }
2359             if (opt_found(algo, dsa_choices, &i)) {
2360                 dsa_doit[i] = 2;
2361                 algo_found = 1;
2362             }
2363         }
2364 #endif
2365         if (strcmp(algo, "aes") == 0) {
2366             doit[D_CBC_128_AES] = doit[D_CBC_192_AES] = doit[D_CBC_256_AES] = 1;
2367             algo_found = 1;
2368         }
2369         if (strcmp(algo, "camellia") == 0) {
2370             doit[D_CBC_128_CML] = doit[D_CBC_192_CML] = doit[D_CBC_256_CML] = 1;
2371             algo_found = 1;
2372         }
2373         if (HAS_PREFIX(algo, "ecdsa")) {
2374             if (algo[sizeof("ecdsa") - 1] == '\0') {
2375                 memset(ecdsa_doit, 1, sizeof(ecdsa_doit));
2376                 algo_found = 1;
2377             }
2378             if (opt_found(algo, ecdsa_choices, &i)) {
2379                 ecdsa_doit[i] = 2;
2380                 algo_found = 1;
2381             }
2382         }
2383         if (HAS_PREFIX(algo, "ecdh")) {
2384             if (algo[sizeof("ecdh") - 1] == '\0') {
2385                 memset(ecdh_doit, 1, sizeof(ecdh_doit));
2386                 algo_found = 1;
2387             }
2388             if (opt_found(algo, ecdh_choices, &i)) {
2389                 ecdh_doit[i] = 2;
2390                 algo_found = 1;
2391             }
2392         }
2393 #ifndef OPENSSL_NO_ECX
2394         if (strcmp(algo, "eddsa") == 0) {
2395             memset(eddsa_doit, 1, sizeof(eddsa_doit));
2396             algo_found = 1;
2397         }
2398         if (opt_found(algo, eddsa_choices, &i)) {
2399             eddsa_doit[i] = 2;
2400             algo_found = 1;
2401         }
2402 #endif /* OPENSSL_NO_ECX */
2403 #ifndef OPENSSL_NO_SM2
2404         if (strcmp(algo, "sm2") == 0) {
2405             memset(sm2_doit, 1, sizeof(sm2_doit));
2406             algo_found = 1;
2407         }
2408         if (opt_found(algo, sm2_choices, &i)) {
2409             sm2_doit[i] = 2;
2410             algo_found = 1;
2411         }
2412 #endif
2413         if (kem_locate(algo, &idx)) {
2414             kems_doit[idx]++;
2415             do_kems = 1;
2416             algo_found = 1;
2417         }
2418         if (sig_locate(algo, &idx)) {
2419             sigs_doit[idx]++;
2420             do_sigs = 1;
2421             algo_found = 1;
2422         }
2423         if (strcmp(algo, "kmac") == 0) {
2424             doit[D_KMAC128] = doit[D_KMAC256] = 1;
2425             algo_found = 1;
2426         }
2427         if (strcmp(algo, "cmac") == 0) {
2428             doit[D_EVP_CMAC] = 1;
2429             algo_found = 1;
2430         }
2431 
2432         if (!algo_found) {
2433             BIO_printf(bio_err, "%s: Unknown algorithm %s\n", prog, algo);
2434             goto end;
2435         }
2436     }
2437 
2438     /* Sanity checks */
2439     if (aead) {
2440         if (evp_cipher == NULL) {
2441             BIO_printf(bio_err, "-aead can be used only with an AEAD cipher\n");
2442             goto end;
2443         } else if (!(EVP_CIPHER_get_flags(evp_cipher) &
2444                      EVP_CIPH_FLAG_AEAD_CIPHER)) {
2445             BIO_printf(bio_err, "%s is not an AEAD cipher\n",
2446                        EVP_CIPHER_get0_name(evp_cipher));
2447             goto end;
2448         }
2449     }
2450     if (kems_algs_len > 0) {
2451         int maxcnt = get_max(kems_doit, kems_algs_len);
2452 
2453         if (maxcnt > 1) {
2454             /* some algs explicitly selected */
2455             for (i = 0; i < kems_algs_len; i++) {
2456                 /* disable the rest */
2457                 kems_doit[i]--;
2458             }
2459         }
2460     }
2461     if (sigs_algs_len > 0) {
2462         int maxcnt = get_max(sigs_doit, sigs_algs_len);
2463 
2464         if (maxcnt > 1) {
2465             /* some algs explicitly selected */
2466             for (i = 0; i < sigs_algs_len; i++) {
2467                 /* disable the rest */
2468                 sigs_doit[i]--;
2469             }
2470         }
2471     }
2472     if (multiblock) {
2473         if (evp_cipher == NULL) {
2474             BIO_printf(bio_err, "-mb can be used only with a multi-block"
2475                                 " capable cipher\n");
2476             goto end;
2477         } else if (!(EVP_CIPHER_get_flags(evp_cipher) &
2478                      EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
2479             BIO_printf(bio_err, "%s is not a multi-block capable\n",
2480                        EVP_CIPHER_get0_name(evp_cipher));
2481             goto end;
2482         } else if (async_jobs > 0) {
2483             BIO_printf(bio_err, "Async mode is not supported with -mb");
2484             goto end;
2485         }
2486     }
2487 
2488     /* Initialize the job pool if async mode is enabled */
2489     if (async_jobs > 0) {
2490         async_init = ASYNC_init_thread(async_jobs, async_jobs);
2491         if (!async_init) {
2492             BIO_printf(bio_err, "Error creating the ASYNC job pool\n");
2493             goto end;
2494         }
2495     }
2496 
2497     loopargs_len = (async_jobs == 0 ? 1 : async_jobs);
2498     loopargs =
2499         app_malloc(loopargs_len * sizeof(loopargs_t), "array of loopargs");
2500     memset(loopargs, 0, loopargs_len * sizeof(loopargs_t));
2501 
2502     buflen = lengths[size_num - 1];
2503     if (buflen < 36)    /* size of random vector in RSA benchmark */
2504         buflen = 36;
2505     if (INT_MAX - (MAX_MISALIGNMENT + 1) < buflen) {
2506         BIO_printf(bio_err, "Error: buffer size too large\n");
2507         goto end;
2508     }
2509     buflen += MAX_MISALIGNMENT + 1;
2510     for (i = 0; i < loopargs_len; i++) {
2511         if (async_jobs > 0) {
2512             loopargs[i].wait_ctx = ASYNC_WAIT_CTX_new();
2513             if (loopargs[i].wait_ctx == NULL) {
2514                 BIO_printf(bio_err, "Error creating the ASYNC_WAIT_CTX\n");
2515                 goto end;
2516             }
2517         }
2518 
2519         loopargs[i].buf_malloc = app_malloc(buflen, "input buffer");
2520         loopargs[i].buf2_malloc = app_malloc(buflen, "input buffer");
2521 
2522         /* Align the start of buffers on a 64 byte boundary */
2523         loopargs[i].buf = loopargs[i].buf_malloc + misalign;
2524         loopargs[i].buf2 = loopargs[i].buf2_malloc + misalign;
2525         loopargs[i].buflen = buflen - misalign;
2526         loopargs[i].sigsize = buflen - misalign;
2527         loopargs[i].secret_a = app_malloc(MAX_ECDH_SIZE, "ECDH secret a");
2528         loopargs[i].secret_b = app_malloc(MAX_ECDH_SIZE, "ECDH secret b");
2529 #ifndef OPENSSL_NO_DH
2530         loopargs[i].secret_ff_a = app_malloc(MAX_FFDH_SIZE, "FFDH secret a");
2531         loopargs[i].secret_ff_b = app_malloc(MAX_FFDH_SIZE, "FFDH secret b");
2532 #endif
2533     }
2534 
2535 #ifndef NO_FORK
2536     if (multi && do_multi(multi, size_num))
2537         goto show_res;
2538 #endif
2539 
2540     for (i = 0; i < loopargs_len; ++i) {
2541         if (domlock) {
2542 #if defined(_WIN32)
2543             (void)VirtualLock(loopargs[i].buf_malloc, buflen);
2544             (void)VirtualLock(loopargs[i].buf2_malloc, buflen);
2545 #elif defined(OPENSSL_SYS_LINUX)
2546             (void)mlock(loopargs[i].buf_malloc, buflen);
2547             (void)mlock(loopargs[i].buf_malloc, buflen);
2548 #endif
2549         }
2550         memset(loopargs[i].buf_malloc, 0, buflen);
2551         memset(loopargs[i].buf2_malloc, 0, buflen);
2552     }
2553 
2554     /* Initialize the engine after the fork */
2555     e = setup_engine(engine_id, 0);
2556 
2557     /* No parameters; turn on everything. */
2558     if (argc == 0 && !doit[D_EVP] && !doit[D_HMAC]
2559         && !doit[D_EVP_CMAC] && !do_kems && !do_sigs) {
2560         memset(doit, 1, sizeof(doit));
2561         doit[D_EVP] = doit[D_EVP_CMAC] = 0;
2562         ERR_set_mark();
2563         for (i = D_MD2; i <= D_WHIRLPOOL; i++) {
2564             if (!have_md(names[i]))
2565                 doit[i] = 0;
2566         }
2567         for (i = D_CBC_DES; i <= D_CBC_256_CML; i++) {
2568             if (!have_cipher(names[i]))
2569                 doit[i] = 0;
2570         }
2571         if ((mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC",
2572                                  app_get0_propq())) != NULL) {
2573             EVP_MAC_free(mac);
2574             mac = NULL;
2575         } else {
2576             doit[D_GHASH] = 0;
2577         }
2578         if ((mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC",
2579                                  app_get0_propq())) != NULL) {
2580             EVP_MAC_free(mac);
2581             mac = NULL;
2582         } else {
2583             doit[D_HMAC] = 0;
2584         }
2585         ERR_pop_to_mark();
2586         memset(rsa_doit, 1, sizeof(rsa_doit));
2587 #ifndef OPENSSL_NO_DH
2588         memset(ffdh_doit, 1, sizeof(ffdh_doit));
2589 #endif
2590 #ifndef OPENSSL_NO_DSA
2591         memset(dsa_doit, 1, sizeof(dsa_doit));
2592 #endif
2593 #ifndef OPENSSL_NO_ECX
2594         memset(ecdsa_doit, 1, sizeof(ecdsa_doit));
2595         memset(ecdh_doit, 1, sizeof(ecdh_doit));
2596         memset(eddsa_doit, 1, sizeof(eddsa_doit));
2597 #endif /* OPENSSL_NO_ECX */
2598 #ifndef OPENSSL_NO_SM2
2599         memset(sm2_doit, 1, sizeof(sm2_doit));
2600 #endif
2601         memset(kems_doit, 1, sizeof(kems_doit));
2602         do_kems = 1;
2603         memset(sigs_doit, 1, sizeof(sigs_doit));
2604         do_sigs = 1;
2605     }
2606     for (i = 0; i < ALGOR_NUM; i++)
2607         if (doit[i])
2608             pr_header++;
2609 
2610     if (usertime == 0 && !mr)
2611         BIO_printf(bio_err,
2612                    "You have chosen to measure elapsed time "
2613                    "instead of user CPU time.\n");
2614 
2615 #if SIGALRM > 0
2616     signal(SIGALRM, alarmed);
2617 #endif
2618 
2619     if (doit[D_MD2]) {
2620         for (testnum = 0; testnum < size_num; testnum++) {
2621             print_message(names[D_MD2], lengths[testnum], seconds.sym);
2622             Time_F(START);
2623             count = run_benchmark(async_jobs, EVP_Digest_MD2_loop, loopargs);
2624             d = Time_F(STOP);
2625             print_result(D_MD2, testnum, count, d);
2626             if (count < 0)
2627                 break;
2628         }
2629     }
2630 
2631     if (doit[D_MDC2]) {
2632         for (testnum = 0; testnum < size_num; testnum++) {
2633             print_message(names[D_MDC2], lengths[testnum], seconds.sym);
2634             Time_F(START);
2635             count = run_benchmark(async_jobs, EVP_Digest_MDC2_loop, loopargs);
2636             d = Time_F(STOP);
2637             print_result(D_MDC2, testnum, count, d);
2638             if (count < 0)
2639                 break;
2640         }
2641     }
2642 
2643     if (doit[D_MD4]) {
2644         for (testnum = 0; testnum < size_num; testnum++) {
2645             print_message(names[D_MD4], lengths[testnum], seconds.sym);
2646             Time_F(START);
2647             count = run_benchmark(async_jobs, EVP_Digest_MD4_loop, loopargs);
2648             d = Time_F(STOP);
2649             print_result(D_MD4, testnum, count, d);
2650             if (count < 0)
2651                 break;
2652         }
2653     }
2654 
2655     if (doit[D_MD5]) {
2656         for (testnum = 0; testnum < size_num; testnum++) {
2657             print_message(names[D_MD5], lengths[testnum], seconds.sym);
2658             Time_F(START);
2659             count = run_benchmark(async_jobs, MD5_loop, loopargs);
2660             d = Time_F(STOP);
2661             print_result(D_MD5, testnum, count, d);
2662             if (count < 0)
2663                 break;
2664         }
2665     }
2666 
2667     if (doit[D_SHA1]) {
2668         for (testnum = 0; testnum < size_num; testnum++) {
2669             print_message(names[D_SHA1], lengths[testnum], seconds.sym);
2670             Time_F(START);
2671             count = run_benchmark(async_jobs, SHA1_loop, loopargs);
2672             d = Time_F(STOP);
2673             print_result(D_SHA1, testnum, count, d);
2674             if (count < 0)
2675                 break;
2676         }
2677     }
2678 
2679     if (doit[D_SHA256]) {
2680         for (testnum = 0; testnum < size_num; testnum++) {
2681             print_message(names[D_SHA256], lengths[testnum], seconds.sym);
2682             Time_F(START);
2683             count = run_benchmark(async_jobs, SHA256_loop, loopargs);
2684             d = Time_F(STOP);
2685             print_result(D_SHA256, testnum, count, d);
2686             if (count < 0)
2687                 break;
2688         }
2689     }
2690 
2691     if (doit[D_SHA512]) {
2692         for (testnum = 0; testnum < size_num; testnum++) {
2693             print_message(names[D_SHA512], lengths[testnum], seconds.sym);
2694             Time_F(START);
2695             count = run_benchmark(async_jobs, SHA512_loop, loopargs);
2696             d = Time_F(STOP);
2697             print_result(D_SHA512, testnum, count, d);
2698             if (count < 0)
2699                 break;
2700         }
2701     }
2702 
2703     if (doit[D_WHIRLPOOL]) {
2704         for (testnum = 0; testnum < size_num; testnum++) {
2705             print_message(names[D_WHIRLPOOL], lengths[testnum], seconds.sym);
2706             Time_F(START);
2707             count = run_benchmark(async_jobs, WHIRLPOOL_loop, loopargs);
2708             d = Time_F(STOP);
2709             print_result(D_WHIRLPOOL, testnum, count, d);
2710             if (count < 0)
2711                 break;
2712         }
2713     }
2714 
2715     if (doit[D_RMD160]) {
2716         for (testnum = 0; testnum < size_num; testnum++) {
2717             print_message(names[D_RMD160], lengths[testnum], seconds.sym);
2718             Time_F(START);
2719             count = run_benchmark(async_jobs, EVP_Digest_RMD160_loop, loopargs);
2720             d = Time_F(STOP);
2721             print_result(D_RMD160, testnum, count, d);
2722             if (count < 0)
2723                 break;
2724         }
2725     }
2726 
2727     if (doit[D_HMAC]) {
2728         static const char hmac_key[] = "This is a key...";
2729         int len = strlen(hmac_key);
2730         size_t hmac_name_len = sizeof("hmac()") + strlen(evp_mac_mdname);
2731         OSSL_PARAM params[3];
2732 
2733         if (evp_mac_mdname == NULL)
2734             goto end;
2735         evp_hmac_name = app_malloc(hmac_name_len, "HMAC name");
2736         BIO_snprintf(evp_hmac_name, hmac_name_len, "hmac(%s)", evp_mac_mdname);
2737         names[D_HMAC] = evp_hmac_name;
2738 
2739         params[0] =
2740             OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
2741                                              evp_mac_mdname, 0);
2742         params[1] =
2743             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
2744                                               (char *)hmac_key, len);
2745         params[2] = OSSL_PARAM_construct_end();
2746 
2747         if (mac_setup("HMAC", &mac, params, loopargs, loopargs_len) < 1)
2748             goto end;
2749         for (testnum = 0; testnum < size_num; testnum++) {
2750             print_message(names[D_HMAC], lengths[testnum], seconds.sym);
2751             Time_F(START);
2752             count = run_benchmark(async_jobs, HMAC_loop, loopargs);
2753             d = Time_F(STOP);
2754             print_result(D_HMAC, testnum, count, d);
2755             if (count < 0)
2756                 break;
2757         }
2758         mac_teardown(&mac, loopargs, loopargs_len);
2759     }
2760 
2761     if (doit[D_CBC_DES]) {
2762         int st = 1;
2763 
2764         for (i = 0; st && i < loopargs_len; i++) {
2765             loopargs[i].ctx = init_evp_cipher_ctx("des-cbc", deskey,
2766                                                   sizeof(deskey) / 3);
2767             st = loopargs[i].ctx != NULL;
2768         }
2769         algindex = D_CBC_DES;
2770         for (testnum = 0; st && testnum < size_num; testnum++) {
2771             if (!check_block_size(loopargs[0].ctx, lengths[testnum]))
2772                 break;
2773             print_message(names[D_CBC_DES], lengths[testnum], seconds.sym);
2774             Time_F(START);
2775             count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2776             d = Time_F(STOP);
2777             print_result(D_CBC_DES, testnum, count, d);
2778         }
2779         for (i = 0; i < loopargs_len; i++)
2780             EVP_CIPHER_CTX_free(loopargs[i].ctx);
2781     }
2782 
2783     if (doit[D_EDE3_DES]) {
2784         int st = 1;
2785 
2786         for (i = 0; st && i < loopargs_len; i++) {
2787             loopargs[i].ctx = init_evp_cipher_ctx("des-ede3-cbc", deskey,
2788                                                   sizeof(deskey));
2789             st = loopargs[i].ctx != NULL;
2790         }
2791         algindex = D_EDE3_DES;
2792         for (testnum = 0; st && testnum < size_num; testnum++) {
2793             if (!check_block_size(loopargs[0].ctx, lengths[testnum]))
2794                 break;
2795             print_message(names[D_EDE3_DES], lengths[testnum], seconds.sym);
2796             Time_F(START);
2797             count =
2798                 run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2799             d = Time_F(STOP);
2800             print_result(D_EDE3_DES, testnum, count, d);
2801         }
2802         for (i = 0; i < loopargs_len; i++)
2803             EVP_CIPHER_CTX_free(loopargs[i].ctx);
2804     }
2805 
2806     for (k = 0; k < 3; k++) {
2807         algindex = D_CBC_128_AES + k;
2808         if (doit[algindex]) {
2809             int st = 1;
2810 
2811             keylen = 16 + k * 8;
2812             for (i = 0; st && i < loopargs_len; i++) {
2813                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2814                                                       key32, keylen);
2815                 st = loopargs[i].ctx != NULL;
2816             }
2817 
2818             for (testnum = 0; st && testnum < size_num; testnum++) {
2819                 if (!check_block_size(loopargs[0].ctx, lengths[testnum]))
2820                     break;
2821                 print_message(names[algindex], lengths[testnum], seconds.sym);
2822                 Time_F(START);
2823                 count =
2824                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2825                 d = Time_F(STOP);
2826                 print_result(algindex, testnum, count, d);
2827             }
2828             for (i = 0; i < loopargs_len; i++)
2829                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2830         }
2831     }
2832 
2833     for (k = 0; k < 3; k++) {
2834         algindex = D_CBC_128_CML + k;
2835         if (doit[algindex]) {
2836             int st = 1;
2837 
2838             keylen = 16 + k * 8;
2839             for (i = 0; st && i < loopargs_len; i++) {
2840                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2841                                                       key32, keylen);
2842                 st = loopargs[i].ctx != NULL;
2843             }
2844 
2845             for (testnum = 0; st && testnum < size_num; testnum++) {
2846                 if (!check_block_size(loopargs[0].ctx, lengths[testnum]))
2847                     break;
2848                 print_message(names[algindex], lengths[testnum], seconds.sym);
2849                 Time_F(START);
2850                 count =
2851                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2852                 d = Time_F(STOP);
2853                 print_result(algindex, testnum, count, d);
2854             }
2855             for (i = 0; i < loopargs_len; i++)
2856                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2857         }
2858     }
2859 
2860     for (algindex = D_RC4; algindex <= D_CBC_CAST; algindex++) {
2861         if (doit[algindex]) {
2862             int st = 1;
2863 
2864             keylen = 16;
2865             for (i = 0; st && i < loopargs_len; i++) {
2866                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2867                                                       key32, keylen);
2868                 st = loopargs[i].ctx != NULL;
2869             }
2870 
2871             for (testnum = 0; st && testnum < size_num; testnum++) {
2872                 if (!check_block_size(loopargs[0].ctx, lengths[testnum]))
2873                     break;
2874                 print_message(names[algindex], lengths[testnum], seconds.sym);
2875                 Time_F(START);
2876                 count =
2877                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2878                 d = Time_F(STOP);
2879                 print_result(algindex, testnum, count, d);
2880             }
2881             for (i = 0; i < loopargs_len; i++)
2882                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2883         }
2884     }
2885     if (doit[D_GHASH]) {
2886         static const char gmac_iv[] = "0123456789ab";
2887         OSSL_PARAM params[4];
2888 
2889         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER,
2890                                                      "aes-128-gcm", 0);
2891         params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
2892                                                       (char *)gmac_iv,
2893                                                       sizeof(gmac_iv) - 1);
2894         params[2] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
2895                                                       (void *)key32, 16);
2896         params[3] = OSSL_PARAM_construct_end();
2897 
2898         if (mac_setup("GMAC", &mac, params, loopargs, loopargs_len) < 1)
2899             goto end;
2900         /* b/c of the definition of GHASH_loop(), init() calls are needed here */
2901         for (i = 0; i < loopargs_len; i++) {
2902             if (!EVP_MAC_init(loopargs[i].mctx, NULL, 0, NULL))
2903                 goto end;
2904         }
2905         for (testnum = 0; testnum < size_num; testnum++) {
2906             print_message(names[D_GHASH], lengths[testnum], seconds.sym);
2907             Time_F(START);
2908             count = run_benchmark(async_jobs, GHASH_loop, loopargs);
2909             d = Time_F(STOP);
2910             print_result(D_GHASH, testnum, count, d);
2911             if (count < 0)
2912                 break;
2913         }
2914         mac_teardown(&mac, loopargs, loopargs_len);
2915     }
2916 
2917     if (doit[D_RAND]) {
2918         for (testnum = 0; testnum < size_num; testnum++) {
2919             print_message(names[D_RAND], lengths[testnum], seconds.sym);
2920             Time_F(START);
2921             count = run_benchmark(async_jobs, RAND_bytes_loop, loopargs);
2922             d = Time_F(STOP);
2923             print_result(D_RAND, testnum, count, d);
2924         }
2925     }
2926 
2927     /*-
2928      * There are three scenarios for D_EVP:
2929      * 1- Using authenticated encryption (AE) e.g. CCM, GCM, OCB etc.
2930      * 2- Using AE + associated data (AD) i.e. AEAD using CCM, GCM, OCB etc.
2931      * 3- Not using AE or AD e.g. ECB, CBC, CFB etc.
2932      */
2933     if (doit[D_EVP]) {
2934         if (evp_cipher != NULL) {
2935             int (*loopfunc) (void *);
2936             int outlen = 0;
2937             unsigned int ae_mode = 0;
2938 
2939             if (multiblock && (EVP_CIPHER_get_flags(evp_cipher)
2940                                & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
2941                 multiblock_speed(evp_cipher, lengths_single, &seconds);
2942                 ret = 0;
2943                 goto end;
2944             }
2945 
2946             names[D_EVP] = EVP_CIPHER_get0_name(evp_cipher);
2947 
2948             mode_op = EVP_CIPHER_get_mode(evp_cipher);
2949 
2950             if (aead) {
2951                 if (lengths == lengths_list) {
2952                     lengths = aead_lengths_list;
2953                     size_num = OSSL_NELEM(aead_lengths_list);
2954                 }
2955             }
2956             if (mode_op == EVP_CIPH_GCM_MODE
2957                 || mode_op == EVP_CIPH_CCM_MODE
2958                 || mode_op == EVP_CIPH_OCB_MODE
2959                 || mode_op == EVP_CIPH_SIV_MODE
2960                 || mode_op == EVP_CIPH_GCM_SIV_MODE) {
2961                 ae_mode = 1;
2962                 if (decrypt)
2963                     loopfunc = EVP_Update_loop_aead_dec;
2964                 else
2965                     loopfunc = EVP_Update_loop_aead_enc;
2966             } else {
2967                 loopfunc = EVP_Update_loop;
2968             }
2969 
2970             for (testnum = 0; testnum < size_num; testnum++) {
2971                 print_message(names[D_EVP], lengths[testnum], seconds.sym);
2972 
2973                 for (k = 0; k < loopargs_len; k++) {
2974                     loopargs[k].ctx = EVP_CIPHER_CTX_new();
2975                     if (loopargs[k].ctx == NULL) {
2976                         BIO_printf(bio_err, "\nEVP_CIPHER_CTX_new failure\n");
2977                         exit(1);
2978                     }
2979 
2980                     /*
2981                      * For AE modes, we must first encrypt the data to get
2982                      * a valid tag that enables us to decrypt. If we don't
2983                      * encrypt first, we won't have a valid tag that enables
2984                      * authenticity and hence decryption will fail.
2985                      */
2986                     if (!EVP_CipherInit_ex(loopargs[k].ctx, evp_cipher, NULL,
2987                                            NULL, NULL, ae_mode ? 1 : !decrypt)) {
2988                         BIO_printf(bio_err, "\nCouldn't init the context\n");
2989                         dofail();
2990                         exit(1);
2991                     }
2992 
2993                     /* Padding isn't needed */
2994                     EVP_CIPHER_CTX_set_padding(loopargs[k].ctx, 0);
2995 
2996                     keylen = EVP_CIPHER_CTX_get_key_length(loopargs[k].ctx);
2997                     loopargs[k].key = app_malloc(keylen, "evp_cipher key");
2998                     EVP_CIPHER_CTX_rand_key(loopargs[k].ctx, loopargs[k].key);
2999 
3000                     if (!ae_mode) {
3001                         if (!EVP_CipherInit_ex(loopargs[k].ctx, NULL, NULL,
3002                                                loopargs[k].key, NULL, -1)) {
3003                             BIO_printf(bio_err, "\nFailed to set the key\n");
3004                             dofail();
3005                             exit(1);
3006                         }
3007                     } else if (mode_op == EVP_CIPH_SIV_MODE
3008                                || mode_op == EVP_CIPH_GCM_SIV_MODE) {
3009                         EVP_CIPHER_CTX_ctrl(loopargs[k].ctx,
3010                                             EVP_CTRL_SET_SPEED, 1, NULL);
3011                     }
3012                     if (ae_mode && decrypt) {
3013                         /* Set length of iv (Doesn't apply to SIV mode) */
3014                         if (mode_op != EVP_CIPH_SIV_MODE) {
3015                             if (!EVP_CIPHER_CTX_ctrl(loopargs[k].ctx,
3016                                                      EVP_CTRL_AEAD_SET_IVLEN,
3017                                                      aead_ivlen, NULL)) {
3018                                 BIO_printf(bio_err, "\nFailed to set iv length\n");
3019                                 dofail();
3020                                 exit(1);
3021                             }
3022                         }
3023                         /* Set tag_len (Not for GCM/SIV at encryption stage) */
3024                         if (mode_op != EVP_CIPH_GCM_MODE
3025                             && mode_op != EVP_CIPH_SIV_MODE
3026                             && mode_op != EVP_CIPH_GCM_SIV_MODE) {
3027                             if (!EVP_CIPHER_CTX_ctrl(loopargs[k].ctx,
3028                                                      EVP_CTRL_AEAD_SET_TAG,
3029                                                      TAG_LEN, NULL)) {
3030                                 BIO_printf(bio_err,
3031                                            "\nFailed to set tag length\n");
3032                                 dofail();
3033                                 exit(1);
3034                             }
3035                         }
3036                         if (!EVP_CipherInit_ex(loopargs[k].ctx, NULL, NULL,
3037                                                loopargs[k].key, aead_iv, -1)) {
3038                             BIO_printf(bio_err, "\nFailed to set the key\n");
3039                             dofail();
3040                             exit(1);
3041                         }
3042                         /* Set total length of input. Only required for CCM */
3043                         if (mode_op == EVP_CIPH_CCM_MODE) {
3044                             if (!EVP_EncryptUpdate(loopargs[k].ctx, NULL,
3045                                                    &outlen, NULL,
3046                                                    lengths[testnum])) {
3047                                 BIO_printf(bio_err,
3048                                            "\nCouldn't set input text length\n");
3049                                 dofail();
3050                                 exit(1);
3051                             }
3052                         }
3053                         if (aead) {
3054                             if (!EVP_EncryptUpdate(loopargs[k].ctx, NULL,
3055                                                    &outlen, aad, sizeof(aad))) {
3056                                 BIO_printf(bio_err,
3057                                            "\nCouldn't insert AAD when encrypting\n");
3058                                 dofail();
3059                                 exit(1);
3060                             }
3061                         }
3062                         if (!EVP_EncryptUpdate(loopargs[k].ctx, loopargs[k].buf,
3063                                                &outlen, loopargs[k].buf,
3064                                                lengths[testnum])) {
3065                             BIO_printf(bio_err,
3066                                        "\nFailed to to encrypt the data\n");
3067                             dofail();
3068                             exit(1);
3069                         }
3070 
3071                         if (!EVP_EncryptFinal_ex(loopargs[k].ctx,
3072                                                  loopargs[k].buf, &outlen)) {
3073                             BIO_printf(bio_err,
3074                                        "\nFailed finalize the encryption\n");
3075                             dofail();
3076                             exit(1);
3077                         }
3078 
3079                         if (!EVP_CIPHER_CTX_ctrl(loopargs[k].ctx, EVP_CTRL_AEAD_GET_TAG,
3080                                                  TAG_LEN, &loopargs[k].tag)) {
3081                             BIO_printf(bio_err, "\nFailed to get the tag\n");
3082                             dofail();
3083                             exit(1);
3084                         }
3085 
3086                         EVP_CIPHER_CTX_free(loopargs[k].ctx);
3087                         loopargs[k].ctx = EVP_CIPHER_CTX_new();
3088                         if (loopargs[k].ctx == NULL) {
3089                             BIO_printf(bio_err,
3090                                        "\nEVP_CIPHER_CTX_new failure\n");
3091                             exit(1);
3092                         }
3093                         if (!EVP_CipherInit_ex(loopargs[k].ctx, evp_cipher,
3094                                                NULL, NULL, NULL, 0)) {
3095                             BIO_printf(bio_err,
3096                                        "\nFailed initializing the context\n");
3097                             dofail();
3098                             exit(1);
3099                         }
3100 
3101                         EVP_CIPHER_CTX_set_padding(loopargs[k].ctx, 0);
3102 
3103                         /* GCM-SIV/SIV only allows for a single Update operation */
3104                         if (mode_op == EVP_CIPH_SIV_MODE
3105                             || mode_op == EVP_CIPH_GCM_SIV_MODE)
3106                             EVP_CIPHER_CTX_ctrl(loopargs[k].ctx,
3107                                                 EVP_CTRL_SET_SPEED, 1, NULL);
3108                     }
3109                 }
3110 
3111                 Time_F(START);
3112                 count = run_benchmark(async_jobs, loopfunc, loopargs);
3113                 d = Time_F(STOP);
3114                 for (k = 0; k < loopargs_len; k++) {
3115                     OPENSSL_clear_free(loopargs[k].key, keylen);
3116                     EVP_CIPHER_CTX_free(loopargs[k].ctx);
3117                 }
3118                 print_result(D_EVP, testnum, count, d);
3119             }
3120         } else if (evp_md_name != NULL) {
3121             names[D_EVP] = evp_md_name;
3122 
3123             for (testnum = 0; testnum < size_num; testnum++) {
3124                 print_message(names[D_EVP], lengths[testnum], seconds.sym);
3125                 Time_F(START);
3126                 count = run_benchmark(async_jobs, EVP_Digest_md_loop, loopargs);
3127                 d = Time_F(STOP);
3128                 print_result(D_EVP, testnum, count, d);
3129                 if (count < 0)
3130                     break;
3131             }
3132         }
3133     }
3134 
3135     if (doit[D_EVP_CMAC]) {
3136         size_t len = sizeof("cmac()") + strlen(evp_mac_ciphername);
3137         OSSL_PARAM params[3];
3138         EVP_CIPHER *cipher = NULL;
3139 
3140         if (!opt_cipher(evp_mac_ciphername, &cipher))
3141             goto end;
3142 
3143         keylen = EVP_CIPHER_get_key_length(cipher);
3144         EVP_CIPHER_free(cipher);
3145         if (keylen <= 0 || keylen > (int)sizeof(key32)) {
3146             BIO_printf(bio_err, "\nRequested CMAC cipher with unsupported key length.\n");
3147             goto end;
3148         }
3149         evp_cmac_name = app_malloc(len, "CMAC name");
3150         BIO_snprintf(evp_cmac_name, len, "cmac(%s)", evp_mac_ciphername);
3151         names[D_EVP_CMAC] = evp_cmac_name;
3152 
3153         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER,
3154                                                      evp_mac_ciphername, 0);
3155         params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
3156                                                       (char *)key32, keylen);
3157         params[2] = OSSL_PARAM_construct_end();
3158 
3159         if (mac_setup("CMAC", &mac, params, loopargs, loopargs_len) < 1)
3160             goto end;
3161         for (testnum = 0; testnum < size_num; testnum++) {
3162             print_message(names[D_EVP_CMAC], lengths[testnum], seconds.sym);
3163             Time_F(START);
3164             count = run_benchmark(async_jobs, CMAC_loop, loopargs);
3165             d = Time_F(STOP);
3166             print_result(D_EVP_CMAC, testnum, count, d);
3167             if (count < 0)
3168                 break;
3169         }
3170         mac_teardown(&mac, loopargs, loopargs_len);
3171     }
3172 
3173     if (doit[D_KMAC128]) {
3174         OSSL_PARAM params[2];
3175 
3176         params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
3177                                                       (void *)key32, 16);
3178         params[1] = OSSL_PARAM_construct_end();
3179 
3180         if (mac_setup("KMAC-128", &mac, params, loopargs, loopargs_len) < 1)
3181             goto end;
3182         for (testnum = 0; testnum < size_num; testnum++) {
3183             print_message(names[D_KMAC128], lengths[testnum], seconds.sym);
3184             Time_F(START);
3185             count = run_benchmark(async_jobs, KMAC128_loop, loopargs);
3186             d = Time_F(STOP);
3187             print_result(D_KMAC128, testnum, count, d);
3188             if (count < 0)
3189                 break;
3190         }
3191         mac_teardown(&mac, loopargs, loopargs_len);
3192     }
3193 
3194     if (doit[D_KMAC256]) {
3195         OSSL_PARAM params[2];
3196 
3197         params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
3198                                                       (void *)key32, 32);
3199         params[1] = OSSL_PARAM_construct_end();
3200 
3201         if (mac_setup("KMAC-256", &mac, params, loopargs, loopargs_len) < 1)
3202             goto end;
3203         for (testnum = 0; testnum < size_num; testnum++) {
3204             print_message(names[D_KMAC256], lengths[testnum], seconds.sym);
3205             Time_F(START);
3206             count = run_benchmark(async_jobs, KMAC256_loop, loopargs);
3207             d = Time_F(STOP);
3208             print_result(D_KMAC256, testnum, count, d);
3209             if (count < 0)
3210                 break;
3211         }
3212         mac_teardown(&mac, loopargs, loopargs_len);
3213     }
3214 
3215     for (i = 0; i < loopargs_len; i++)
3216         if (RAND_bytes(loopargs[i].buf, 36) <= 0)
3217             goto end;
3218 
3219     for (testnum = 0; testnum < RSA_NUM; testnum++) {
3220         EVP_PKEY *rsa_key = NULL;
3221         int st = 0;
3222 
3223         if (!rsa_doit[testnum])
3224             continue;
3225 
3226         if (primes > RSA_DEFAULT_PRIME_NUM) {
3227             /* we haven't set keys yet,  generate multi-prime RSA keys */
3228             bn = BN_new();
3229             st = bn != NULL
3230                 && BN_set_word(bn, RSA_F4)
3231                 && init_gen_str(&genctx, "RSA", NULL, 0, NULL, NULL)
3232                 && EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, rsa_keys[testnum].bits) > 0
3233                 && EVP_PKEY_CTX_set1_rsa_keygen_pubexp(genctx, bn) > 0
3234                 && EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) > 0
3235                 && EVP_PKEY_keygen(genctx, &rsa_key);
3236             BN_free(bn);
3237             bn = NULL;
3238             EVP_PKEY_CTX_free(genctx);
3239             genctx = NULL;
3240         } else {
3241             const unsigned char *p = rsa_keys[testnum].data;
3242 
3243             st = (rsa_key = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p,
3244                                            rsa_keys[testnum].length)) != NULL;
3245         }
3246 
3247         for (i = 0; st && i < loopargs_len; i++) {
3248             loopargs[i].rsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL);
3249             loopargs[i].sigsize = loopargs[i].buflen;
3250             if (loopargs[i].rsa_sign_ctx[testnum] == NULL
3251                 || EVP_PKEY_sign_init(loopargs[i].rsa_sign_ctx[testnum]) <= 0
3252                 || EVP_PKEY_sign(loopargs[i].rsa_sign_ctx[testnum],
3253                                  loopargs[i].buf2,
3254                                  &loopargs[i].sigsize,
3255                                  loopargs[i].buf, 36) <= 0)
3256                 st = 0;
3257         }
3258         if (!st) {
3259             BIO_printf(bio_err,
3260                        "RSA sign setup failure.  No RSA sign will be done.\n");
3261             dofail();
3262             op_count = 1;
3263         } else {
3264             pkey_print_message("private", "rsa sign",
3265                                rsa_keys[testnum].bits, seconds.rsa);
3266             /* RSA_blinding_on(rsa_key[testnum],NULL); */
3267             Time_F(START);
3268             count = run_benchmark(async_jobs, RSA_sign_loop, loopargs);
3269             d = Time_F(STOP);
3270             BIO_printf(bio_err,
3271                        mr ? "+R1:%ld:%d:%.2f\n"
3272                        : "%ld %u bits private RSA sign ops in %.2fs\n",
3273                        count, rsa_keys[testnum].bits, d);
3274             rsa_results[testnum][0] = (double)count / d;
3275             op_count = count;
3276         }
3277 
3278         for (i = 0; st && i < loopargs_len; i++) {
3279             loopargs[i].rsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key,
3280                                                                    NULL);
3281             if (loopargs[i].rsa_verify_ctx[testnum] == NULL
3282                 || EVP_PKEY_verify_init(loopargs[i].rsa_verify_ctx[testnum]) <= 0
3283                 || EVP_PKEY_verify(loopargs[i].rsa_verify_ctx[testnum],
3284                                    loopargs[i].buf2,
3285                                    loopargs[i].sigsize,
3286                                    loopargs[i].buf, 36) <= 0)
3287                 st = 0;
3288         }
3289         if (!st) {
3290             BIO_printf(bio_err,
3291                        "RSA verify setup failure.  No RSA verify will be done.\n");
3292             dofail();
3293             rsa_doit[testnum] = 0;
3294         } else {
3295             pkey_print_message("public", "rsa verify",
3296                                rsa_keys[testnum].bits, seconds.rsa);
3297             Time_F(START);
3298             count = run_benchmark(async_jobs, RSA_verify_loop, loopargs);
3299             d = Time_F(STOP);
3300             BIO_printf(bio_err,
3301                        mr ? "+R2:%ld:%d:%.2f\n"
3302                        : "%ld %u bits public RSA verify ops in %.2fs\n",
3303                        count, rsa_keys[testnum].bits, d);
3304             rsa_results[testnum][1] = (double)count / d;
3305         }
3306 
3307         for (i = 0; st && i < loopargs_len; i++) {
3308             loopargs[i].rsa_encrypt_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL);
3309             loopargs[i].encsize = loopargs[i].buflen;
3310             if (loopargs[i].rsa_encrypt_ctx[testnum] == NULL
3311                 || EVP_PKEY_encrypt_init(loopargs[i].rsa_encrypt_ctx[testnum]) <= 0
3312                 || EVP_PKEY_encrypt(loopargs[i].rsa_encrypt_ctx[testnum],
3313                                     loopargs[i].buf2,
3314                                     &loopargs[i].encsize,
3315                                     loopargs[i].buf, 36) <= 0)
3316                 st = 0;
3317         }
3318         if (!st) {
3319             BIO_printf(bio_err,
3320                        "RSA encrypt setup failure.  No RSA encrypt will be done.\n");
3321             dofail();
3322             op_count = 1;
3323         } else {
3324             pkey_print_message("public", "rsa encrypt",
3325                                rsa_keys[testnum].bits, seconds.rsa);
3326             /* RSA_blinding_on(rsa_key[testnum],NULL); */
3327             Time_F(START);
3328             count = run_benchmark(async_jobs, RSA_encrypt_loop, loopargs);
3329             d = Time_F(STOP);
3330             BIO_printf(bio_err,
3331                        mr ? "+R3:%ld:%d:%.2f\n"
3332                        : "%ld %u bits public RSA encrypt ops in %.2fs\n",
3333                        count, rsa_keys[testnum].bits, d);
3334             rsa_results[testnum][2] = (double)count / d;
3335             op_count = count;
3336         }
3337 
3338         for (i = 0; st && i < loopargs_len; i++) {
3339             loopargs[i].rsa_decrypt_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL);
3340             declen = loopargs[i].buflen;
3341             if (loopargs[i].rsa_decrypt_ctx[testnum] == NULL
3342                 || EVP_PKEY_decrypt_init(loopargs[i].rsa_decrypt_ctx[testnum]) <= 0
3343                 || EVP_PKEY_decrypt(loopargs[i].rsa_decrypt_ctx[testnum],
3344                                     loopargs[i].buf,
3345                                     &declen,
3346                                     loopargs[i].buf2,
3347                                     loopargs[i].encsize) <= 0)
3348                 st = 0;
3349         }
3350         if (!st) {
3351             BIO_printf(bio_err,
3352                        "RSA decrypt setup failure.  No RSA decrypt will be done.\n");
3353             dofail();
3354             op_count = 1;
3355         } else {
3356             pkey_print_message("private", "rsa decrypt",
3357                                rsa_keys[testnum].bits, seconds.rsa);
3358             /* RSA_blinding_on(rsa_key[testnum],NULL); */
3359             Time_F(START);
3360             count = run_benchmark(async_jobs, RSA_decrypt_loop, loopargs);
3361             d = Time_F(STOP);
3362             BIO_printf(bio_err,
3363                        mr ? "+R4:%ld:%d:%.2f\n"
3364                        : "%ld %u bits private RSA decrypt ops in %.2fs\n",
3365                        count, rsa_keys[testnum].bits, d);
3366             rsa_results[testnum][3] = (double)count / d;
3367             op_count = count;
3368         }
3369 
3370         if (op_count <= 1) {
3371             /* if longer than 10s, don't do any more */
3372             stop_it(rsa_doit, testnum);
3373         }
3374         EVP_PKEY_free(rsa_key);
3375     }
3376 
3377 #ifndef OPENSSL_NO_DSA
3378     for (testnum = 0; testnum < DSA_NUM; testnum++) {
3379         EVP_PKEY *dsa_key = NULL;
3380         int st;
3381 
3382         if (!dsa_doit[testnum])
3383             continue;
3384 
3385         st = (dsa_key = get_dsa(dsa_bits[testnum])) != NULL;
3386 
3387         for (i = 0; st && i < loopargs_len; i++) {
3388             loopargs[i].dsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key,
3389                                                                  NULL);
3390             loopargs[i].sigsize = loopargs[i].buflen;
3391             if (loopargs[i].dsa_sign_ctx[testnum] == NULL
3392                 || EVP_PKEY_sign_init(loopargs[i].dsa_sign_ctx[testnum]) <= 0
3393                 || EVP_PKEY_sign(loopargs[i].dsa_sign_ctx[testnum],
3394                                  loopargs[i].buf2,
3395                                  &loopargs[i].sigsize,
3396                                  loopargs[i].buf, 20) <= 0)
3397                 st = 0;
3398         }
3399         if (!st) {
3400             BIO_printf(bio_err,
3401                        "DSA sign setup failure.  No DSA sign will be done.\n");
3402             dofail();
3403             op_count = 1;
3404         } else {
3405             pkey_print_message("sign", "dsa",
3406                                dsa_bits[testnum], seconds.dsa);
3407             Time_F(START);
3408             count = run_benchmark(async_jobs, DSA_sign_loop, loopargs);
3409             d = Time_F(STOP);
3410             BIO_printf(bio_err,
3411                        mr ? "+R5:%ld:%u:%.2f\n"
3412                        : "%ld %u bits DSA sign ops in %.2fs\n",
3413                        count, dsa_bits[testnum], d);
3414             dsa_results[testnum][0] = (double)count / d;
3415             op_count = count;
3416         }
3417 
3418         for (i = 0; st && i < loopargs_len; i++) {
3419             loopargs[i].dsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key,
3420                                                                    NULL);
3421             if (loopargs[i].dsa_verify_ctx[testnum] == NULL
3422                 || EVP_PKEY_verify_init(loopargs[i].dsa_verify_ctx[testnum]) <= 0
3423                 || EVP_PKEY_verify(loopargs[i].dsa_verify_ctx[testnum],
3424                                    loopargs[i].buf2,
3425                                    loopargs[i].sigsize,
3426                                    loopargs[i].buf, 36) <= 0)
3427                 st = 0;
3428         }
3429         if (!st) {
3430             BIO_printf(bio_err,
3431                        "DSA verify setup failure.  No DSA verify will be done.\n");
3432             dofail();
3433             dsa_doit[testnum] = 0;
3434         } else {
3435             pkey_print_message("verify", "dsa",
3436                                dsa_bits[testnum], seconds.dsa);
3437             Time_F(START);
3438             count = run_benchmark(async_jobs, DSA_verify_loop, loopargs);
3439             d = Time_F(STOP);
3440             BIO_printf(bio_err,
3441                        mr ? "+R6:%ld:%u:%.2f\n"
3442                        : "%ld %u bits DSA verify ops in %.2fs\n",
3443                        count, dsa_bits[testnum], d);
3444             dsa_results[testnum][1] = (double)count / d;
3445         }
3446 
3447         if (op_count <= 1) {
3448             /* if longer than 10s, don't do any more */
3449             stop_it(dsa_doit, testnum);
3450         }
3451         EVP_PKEY_free(dsa_key);
3452     }
3453 #endif /* OPENSSL_NO_DSA */
3454 
3455     for (testnum = 0; testnum < ECDSA_NUM; testnum++) {
3456         EVP_PKEY *ecdsa_key = NULL;
3457         int st;
3458 
3459         if (!ecdsa_doit[testnum])
3460             continue;
3461 
3462         st = (ecdsa_key = get_ecdsa(&ec_curves[testnum])) != NULL;
3463 
3464         for (i = 0; st && i < loopargs_len; i++) {
3465             loopargs[i].ecdsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key,
3466                                                                    NULL);
3467             loopargs[i].sigsize = loopargs[i].buflen;
3468             if (loopargs[i].ecdsa_sign_ctx[testnum] == NULL
3469                 || EVP_PKEY_sign_init(loopargs[i].ecdsa_sign_ctx[testnum]) <= 0
3470                 || EVP_PKEY_sign(loopargs[i].ecdsa_sign_ctx[testnum],
3471                                  loopargs[i].buf2,
3472                                  &loopargs[i].sigsize,
3473                                  loopargs[i].buf, 20) <= 0)
3474                 st = 0;
3475         }
3476         if (!st) {
3477             BIO_printf(bio_err,
3478                        "ECDSA sign setup failure.  No ECDSA sign will be done.\n");
3479             dofail();
3480             op_count = 1;
3481         } else {
3482             pkey_print_message("sign", "ecdsa",
3483                                ec_curves[testnum].bits, seconds.ecdsa);
3484             Time_F(START);
3485             count = run_benchmark(async_jobs, ECDSA_sign_loop, loopargs);
3486             d = Time_F(STOP);
3487             BIO_printf(bio_err,
3488                        mr ? "+R7:%ld:%u:%.2f\n"
3489                        : "%ld %u bits ECDSA sign ops in %.2fs\n",
3490                        count, ec_curves[testnum].bits, d);
3491             ecdsa_results[testnum][0] = (double)count / d;
3492             op_count = count;
3493         }
3494 
3495         for (i = 0; st && i < loopargs_len; i++) {
3496             loopargs[i].ecdsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key,
3497                                                                      NULL);
3498             if (loopargs[i].ecdsa_verify_ctx[testnum] == NULL
3499                 || EVP_PKEY_verify_init(loopargs[i].ecdsa_verify_ctx[testnum]) <= 0
3500                 || EVP_PKEY_verify(loopargs[i].ecdsa_verify_ctx[testnum],
3501                                    loopargs[i].buf2,
3502                                    loopargs[i].sigsize,
3503                                    loopargs[i].buf, 20) <= 0)
3504                 st = 0;
3505         }
3506         if (!st) {
3507             BIO_printf(bio_err,
3508                        "ECDSA verify setup failure.  No ECDSA verify will be done.\n");
3509             dofail();
3510             ecdsa_doit[testnum] = 0;
3511         } else {
3512             pkey_print_message("verify", "ecdsa",
3513                                ec_curves[testnum].bits, seconds.ecdsa);
3514             Time_F(START);
3515             count = run_benchmark(async_jobs, ECDSA_verify_loop, loopargs);
3516             d = Time_F(STOP);
3517             BIO_printf(bio_err,
3518                        mr ? "+R8:%ld:%u:%.2f\n"
3519                        : "%ld %u bits ECDSA verify ops in %.2fs\n",
3520                        count, ec_curves[testnum].bits, d);
3521             ecdsa_results[testnum][1] = (double)count / d;
3522         }
3523 
3524         if (op_count <= 1) {
3525             /* if longer than 10s, don't do any more */
3526             stop_it(ecdsa_doit, testnum);
3527         }
3528         EVP_PKEY_free(ecdsa_key);
3529     }
3530 
3531     for (testnum = 0; testnum < EC_NUM; testnum++) {
3532         int ecdh_checks = 1;
3533 
3534         if (!ecdh_doit[testnum])
3535             continue;
3536 
3537         for (i = 0; i < loopargs_len; i++) {
3538             EVP_PKEY_CTX *test_ctx = NULL;
3539             EVP_PKEY_CTX *ctx = NULL;
3540             EVP_PKEY *key_A = NULL;
3541             EVP_PKEY *key_B = NULL;
3542             size_t outlen;
3543             size_t test_outlen;
3544 
3545             if ((key_A = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key A */
3546                 || (key_B = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key B */
3547                 || (ctx = EVP_PKEY_CTX_new(key_A, NULL)) == NULL /* derivation ctx from skeyA */
3548                 || EVP_PKEY_derive_init(ctx) <= 0 /* init derivation ctx */
3549                 || EVP_PKEY_derive_set_peer(ctx, key_B) <= 0 /* set peer pubkey in ctx */
3550                 || EVP_PKEY_derive(ctx, NULL, &outlen) <= 0 /* determine max length */
3551                 || outlen == 0 /* ensure outlen is a valid size */
3552                 || outlen > MAX_ECDH_SIZE /* avoid buffer overflow */) {
3553                 ecdh_checks = 0;
3554                 BIO_printf(bio_err, "ECDH key generation failure.\n");
3555                 dofail();
3556                 op_count = 1;
3557                 break;
3558             }
3559 
3560             /*
3561              * Here we perform a test run, comparing the output of a*B and b*A;
3562              * we try this here and assume that further EVP_PKEY_derive calls
3563              * never fail, so we can skip checks in the actually benchmarked
3564              * code, for maximum performance.
3565              */
3566             if ((test_ctx = EVP_PKEY_CTX_new(key_B, NULL)) == NULL /* test ctx from skeyB */
3567                 || EVP_PKEY_derive_init(test_ctx) <= 0 /* init derivation test_ctx */
3568                 || EVP_PKEY_derive_set_peer(test_ctx, key_A) <= 0 /* set peer pubkey in test_ctx */
3569                 || EVP_PKEY_derive(test_ctx, NULL, &test_outlen) <= 0 /* determine max length */
3570                 || EVP_PKEY_derive(ctx, loopargs[i].secret_a, &outlen) <= 0 /* compute a*B */
3571                 || EVP_PKEY_derive(test_ctx, loopargs[i].secret_b, &test_outlen) <= 0 /* compute b*A */
3572                 || test_outlen != outlen /* compare output length */) {
3573                 ecdh_checks = 0;
3574                 BIO_printf(bio_err, "ECDH computation failure.\n");
3575                 dofail();
3576                 op_count = 1;
3577                 break;
3578             }
3579 
3580             /* Compare the computation results: CRYPTO_memcmp() returns 0 if equal */
3581             if (CRYPTO_memcmp(loopargs[i].secret_a,
3582                               loopargs[i].secret_b, outlen)) {
3583                 ecdh_checks = 0;
3584                 BIO_printf(bio_err, "ECDH computations don't match.\n");
3585                 dofail();
3586                 op_count = 1;
3587                 break;
3588             }
3589 
3590             loopargs[i].ecdh_ctx[testnum] = ctx;
3591             loopargs[i].outlen[testnum] = outlen;
3592 
3593             EVP_PKEY_free(key_A);
3594             EVP_PKEY_free(key_B);
3595             EVP_PKEY_CTX_free(test_ctx);
3596             test_ctx = NULL;
3597         }
3598         if (ecdh_checks != 0) {
3599             pkey_print_message("", "ecdh",
3600                                ec_curves[testnum].bits, seconds.ecdh);
3601             Time_F(START);
3602             count =
3603                 run_benchmark(async_jobs, ECDH_EVP_derive_key_loop, loopargs);
3604             d = Time_F(STOP);
3605             BIO_printf(bio_err,
3606                        mr ? "+R9:%ld:%d:%.2f\n" :
3607                        "%ld %u-bits ECDH ops in %.2fs\n", count,
3608                        ec_curves[testnum].bits, d);
3609             ecdh_results[testnum][0] = (double)count / d;
3610             op_count = count;
3611         }
3612 
3613         if (op_count <= 1) {
3614             /* if longer than 10s, don't do any more */
3615             stop_it(ecdh_doit, testnum);
3616         }
3617     }
3618 
3619 #ifndef OPENSSL_NO_ECX
3620     for (testnum = 0; testnum < EdDSA_NUM; testnum++) {
3621         int st = 1;
3622         EVP_PKEY *ed_pkey = NULL;
3623         EVP_PKEY_CTX *ed_pctx = NULL;
3624 
3625         if (!eddsa_doit[testnum])
3626             continue;           /* Ignore Curve */
3627         for (i = 0; i < loopargs_len; i++) {
3628             loopargs[i].eddsa_ctx[testnum] = EVP_MD_CTX_new();
3629             if (loopargs[i].eddsa_ctx[testnum] == NULL) {
3630                 st = 0;
3631                 break;
3632             }
3633             loopargs[i].eddsa_ctx2[testnum] = EVP_MD_CTX_new();
3634             if (loopargs[i].eddsa_ctx2[testnum] == NULL) {
3635                 st = 0;
3636                 break;
3637             }
3638 
3639             if ((ed_pctx = EVP_PKEY_CTX_new_id(ed_curves[testnum].nid,
3640                                                NULL)) == NULL
3641                 || EVP_PKEY_keygen_init(ed_pctx) <= 0
3642                 || EVP_PKEY_keygen(ed_pctx, &ed_pkey) <= 0) {
3643                 st = 0;
3644                 EVP_PKEY_CTX_free(ed_pctx);
3645                 break;
3646             }
3647             EVP_PKEY_CTX_free(ed_pctx);
3648 
3649             if (!EVP_DigestSignInit(loopargs[i].eddsa_ctx[testnum], NULL, NULL,
3650                                     NULL, ed_pkey)) {
3651                 st = 0;
3652                 EVP_PKEY_free(ed_pkey);
3653                 break;
3654             }
3655             if (!EVP_DigestVerifyInit(loopargs[i].eddsa_ctx2[testnum], NULL,
3656                                       NULL, NULL, ed_pkey)) {
3657                 st = 0;
3658                 EVP_PKEY_free(ed_pkey);
3659                 break;
3660             }
3661 
3662             EVP_PKEY_free(ed_pkey);
3663             ed_pkey = NULL;
3664         }
3665         if (st == 0) {
3666             BIO_printf(bio_err, "EdDSA failure.\n");
3667             dofail();
3668             op_count = 1;
3669         } else {
3670             for (i = 0; i < loopargs_len; i++) {
3671                 /* Perform EdDSA signature test */
3672                 loopargs[i].sigsize = ed_curves[testnum].sigsize;
3673                 st = EVP_DigestSign(loopargs[i].eddsa_ctx[testnum],
3674                                     loopargs[i].buf2, &loopargs[i].sigsize,
3675                                     loopargs[i].buf, 20);
3676                 if (st == 0)
3677                     break;
3678             }
3679             if (st == 0) {
3680                 BIO_printf(bio_err,
3681                            "EdDSA sign failure.  No EdDSA sign will be done.\n");
3682                 dofail();
3683                 op_count = 1;
3684             } else {
3685                 pkey_print_message("sign", ed_curves[testnum].name,
3686                                    ed_curves[testnum].bits, seconds.eddsa);
3687                 Time_F(START);
3688                 count = run_benchmark(async_jobs, EdDSA_sign_loop, loopargs);
3689                 d = Time_F(STOP);
3690 
3691                 BIO_printf(bio_err,
3692                            mr ? "+R10:%ld:%u:%s:%.2f\n" :
3693                            "%ld %u bits %s sign ops in %.2fs \n",
3694                            count, ed_curves[testnum].bits,
3695                            ed_curves[testnum].name, d);
3696                 eddsa_results[testnum][0] = (double)count / d;
3697                 op_count = count;
3698             }
3699             /* Perform EdDSA verification test */
3700             for (i = 0; i < loopargs_len; i++) {
3701                 st = EVP_DigestVerify(loopargs[i].eddsa_ctx2[testnum],
3702                                       loopargs[i].buf2, loopargs[i].sigsize,
3703                                       loopargs[i].buf, 20);
3704                 if (st != 1)
3705                     break;
3706             }
3707             if (st != 1) {
3708                 BIO_printf(bio_err,
3709                            "EdDSA verify failure.  No EdDSA verify will be done.\n");
3710                 dofail();
3711                 eddsa_doit[testnum] = 0;
3712             } else {
3713                 pkey_print_message("verify", ed_curves[testnum].name,
3714                                    ed_curves[testnum].bits, seconds.eddsa);
3715                 Time_F(START);
3716                 count = run_benchmark(async_jobs, EdDSA_verify_loop, loopargs);
3717                 d = Time_F(STOP);
3718                 BIO_printf(bio_err,
3719                            mr ? "+R11:%ld:%u:%s:%.2f\n"
3720                            : "%ld %u bits %s verify ops in %.2fs\n",
3721                            count, ed_curves[testnum].bits,
3722                            ed_curves[testnum].name, d);
3723                 eddsa_results[testnum][1] = (double)count / d;
3724             }
3725 
3726             if (op_count <= 1) {
3727                 /* if longer than 10s, don't do any more */
3728                 stop_it(eddsa_doit, testnum);
3729             }
3730         }
3731     }
3732 #endif /* OPENSSL_NO_ECX */
3733 
3734 #ifndef OPENSSL_NO_SM2
3735     for (testnum = 0; testnum < SM2_NUM; testnum++) {
3736         int st = 1;
3737         EVP_PKEY *sm2_pkey = NULL;
3738 
3739         if (!sm2_doit[testnum])
3740             continue;           /* Ignore Curve */
3741         /* Init signing and verification */
3742         for (i = 0; i < loopargs_len; i++) {
3743             EVP_PKEY_CTX *sm2_pctx = NULL;
3744             EVP_PKEY_CTX *sm2_vfy_pctx = NULL;
3745             EVP_PKEY_CTX *pctx = NULL;
3746             st = 0;
3747 
3748             loopargs[i].sm2_ctx[testnum] = EVP_MD_CTX_new();
3749             loopargs[i].sm2_vfy_ctx[testnum] = EVP_MD_CTX_new();
3750             if (loopargs[i].sm2_ctx[testnum] == NULL
3751                     || loopargs[i].sm2_vfy_ctx[testnum] == NULL)
3752                 break;
3753 
3754             sm2_pkey = NULL;
3755 
3756             st = !((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SM2, NULL)) == NULL
3757                 || EVP_PKEY_keygen_init(pctx) <= 0
3758                 || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
3759                     sm2_curves[testnum].nid) <= 0
3760                 || EVP_PKEY_keygen(pctx, &sm2_pkey) <= 0);
3761             EVP_PKEY_CTX_free(pctx);
3762             if (st == 0)
3763                 break;
3764 
3765             st = 0; /* set back to zero */
3766             /* attach it sooner to rely on main final cleanup */
3767             loopargs[i].sm2_pkey[testnum] = sm2_pkey;
3768             loopargs[i].sigsize = EVP_PKEY_get_size(sm2_pkey);
3769 
3770             sm2_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL);
3771             sm2_vfy_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL);
3772             if (sm2_pctx == NULL || sm2_vfy_pctx == NULL) {
3773                 EVP_PKEY_CTX_free(sm2_vfy_pctx);
3774                 break;
3775             }
3776 
3777             /* attach them directly to respective ctx */
3778             EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_ctx[testnum], sm2_pctx);
3779             EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_vfy_ctx[testnum], sm2_vfy_pctx);
3780 
3781             /*
3782              * No need to allow user to set an explicit ID here, just use
3783              * the one defined in the 'draft-yang-tls-tl13-sm-suites' I-D.
3784              */
3785             if (EVP_PKEY_CTX_set1_id(sm2_pctx, SM2_ID, SM2_ID_LEN) != 1
3786                 || EVP_PKEY_CTX_set1_id(sm2_vfy_pctx, SM2_ID, SM2_ID_LEN) != 1)
3787                 break;
3788 
3789             if (!EVP_DigestSignInit(loopargs[i].sm2_ctx[testnum], NULL,
3790                                     EVP_sm3(), NULL, sm2_pkey))
3791                 break;
3792             if (!EVP_DigestVerifyInit(loopargs[i].sm2_vfy_ctx[testnum], NULL,
3793                                       EVP_sm3(), NULL, sm2_pkey))
3794                 break;
3795             st = 1;         /* mark loop as succeeded */
3796         }
3797         if (st == 0) {
3798             BIO_printf(bio_err, "SM2 init failure.\n");
3799             dofail();
3800             op_count = 1;
3801         } else {
3802             for (i = 0; i < loopargs_len; i++) {
3803                 /* Perform SM2 signature test */
3804                 st = EVP_DigestSign(loopargs[i].sm2_ctx[testnum],
3805                                     loopargs[i].buf2, &loopargs[i].sigsize,
3806                                     loopargs[i].buf, 20);
3807                 if (st == 0)
3808                     break;
3809             }
3810             if (st == 0) {
3811                 BIO_printf(bio_err,
3812                            "SM2 sign failure.  No SM2 sign will be done.\n");
3813                 dofail();
3814                 op_count = 1;
3815             } else {
3816                 pkey_print_message("sign", sm2_curves[testnum].name,
3817                                    sm2_curves[testnum].bits, seconds.sm2);
3818                 Time_F(START);
3819                 count = run_benchmark(async_jobs, SM2_sign_loop, loopargs);
3820                 d = Time_F(STOP);
3821 
3822                 BIO_printf(bio_err,
3823                            mr ? "+R12:%ld:%u:%s:%.2f\n" :
3824                            "%ld %u bits %s sign ops in %.2fs \n",
3825                            count, sm2_curves[testnum].bits,
3826                            sm2_curves[testnum].name, d);
3827                 sm2_results[testnum][0] = (double)count / d;
3828                 op_count = count;
3829             }
3830 
3831             /* Perform SM2 verification test */
3832             for (i = 0; i < loopargs_len; i++) {
3833                 st = EVP_DigestVerify(loopargs[i].sm2_vfy_ctx[testnum],
3834                                       loopargs[i].buf2, loopargs[i].sigsize,
3835                                       loopargs[i].buf, 20);
3836                 if (st != 1)
3837                     break;
3838             }
3839             if (st != 1) {
3840                 BIO_printf(bio_err,
3841                            "SM2 verify failure.  No SM2 verify will be done.\n");
3842                 dofail();
3843                 sm2_doit[testnum] = 0;
3844             } else {
3845                 pkey_print_message("verify", sm2_curves[testnum].name,
3846                                    sm2_curves[testnum].bits, seconds.sm2);
3847                 Time_F(START);
3848                 count = run_benchmark(async_jobs, SM2_verify_loop, loopargs);
3849                 d = Time_F(STOP);
3850                 BIO_printf(bio_err,
3851                            mr ? "+R13:%ld:%u:%s:%.2f\n"
3852                            : "%ld %u bits %s verify ops in %.2fs\n",
3853                            count, sm2_curves[testnum].bits,
3854                            sm2_curves[testnum].name, d);
3855                 sm2_results[testnum][1] = (double)count / d;
3856             }
3857 
3858             if (op_count <= 1) {
3859                 /* if longer than 10s, don't do any more */
3860                 for (testnum++; testnum < SM2_NUM; testnum++)
3861                     sm2_doit[testnum] = 0;
3862             }
3863         }
3864     }
3865 #endif                         /* OPENSSL_NO_SM2 */
3866 
3867 #ifndef OPENSSL_NO_DH
3868     for (testnum = 0; testnum < FFDH_NUM; testnum++) {
3869         int ffdh_checks = 1;
3870 
3871         if (!ffdh_doit[testnum])
3872             continue;
3873 
3874         for (i = 0; i < loopargs_len; i++) {
3875             EVP_PKEY *pkey_A = NULL;
3876             EVP_PKEY *pkey_B = NULL;
3877             EVP_PKEY_CTX *ffdh_ctx = NULL;
3878             EVP_PKEY_CTX *test_ctx = NULL;
3879             size_t secret_size;
3880             size_t test_out;
3881 
3882             /* Ensure that the error queue is empty */
3883             if (ERR_peek_error()) {
3884                 BIO_printf(bio_err,
3885                            "WARNING: the error queue contains previous unhandled errors.\n");
3886                 dofail();
3887             }
3888 
3889             pkey_A = EVP_PKEY_new();
3890             if (!pkey_A) {
3891                 BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n");
3892                 dofail();
3893                 op_count = 1;
3894                 ffdh_checks = 0;
3895                 break;
3896             }
3897             pkey_B = EVP_PKEY_new();
3898             if (!pkey_B) {
3899                 BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n");
3900                 dofail();
3901                 op_count = 1;
3902                 ffdh_checks = 0;
3903                 break;
3904             }
3905 
3906             ffdh_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, NULL);
3907             if (!ffdh_ctx) {
3908                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
3909                 dofail();
3910                 op_count = 1;
3911                 ffdh_checks = 0;
3912                 break;
3913             }
3914 
3915             if (EVP_PKEY_keygen_init(ffdh_ctx) <= 0) {
3916                 BIO_printf(bio_err, "Error while initialising EVP_PKEY_CTX.\n");
3917                 dofail();
3918                 op_count = 1;
3919                 ffdh_checks = 0;
3920                 break;
3921             }
3922             if (EVP_PKEY_CTX_set_dh_nid(ffdh_ctx, ffdh_params[testnum].nid) <= 0) {
3923                 BIO_printf(bio_err, "Error setting DH key size for keygen.\n");
3924                 dofail();
3925                 op_count = 1;
3926                 ffdh_checks = 0;
3927                 break;
3928             }
3929 
3930             if (EVP_PKEY_keygen(ffdh_ctx, &pkey_A) <= 0 ||
3931                 EVP_PKEY_keygen(ffdh_ctx, &pkey_B) <= 0) {
3932                 BIO_printf(bio_err, "FFDH key generation failure.\n");
3933                 dofail();
3934                 op_count = 1;
3935                 ffdh_checks = 0;
3936                 break;
3937             }
3938 
3939             EVP_PKEY_CTX_free(ffdh_ctx);
3940 
3941             /*
3942              * check if the derivation works correctly both ways so that
3943              * we know if future derive calls will fail, and we can skip
3944              * error checking in benchmarked code
3945              */
3946             ffdh_ctx = EVP_PKEY_CTX_new(pkey_A, NULL);
3947             if (ffdh_ctx == NULL) {
3948                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
3949                 dofail();
3950                 op_count = 1;
3951                 ffdh_checks = 0;
3952                 break;
3953             }
3954             if (EVP_PKEY_derive_init(ffdh_ctx) <= 0) {
3955                 BIO_printf(bio_err, "FFDH derivation context init failure.\n");
3956                 dofail();
3957                 op_count = 1;
3958                 ffdh_checks = 0;
3959                 break;
3960             }
3961             if (EVP_PKEY_derive_set_peer(ffdh_ctx, pkey_B) <= 0) {
3962                 BIO_printf(bio_err, "Assigning peer key for derivation failed.\n");
3963                 dofail();
3964                 op_count = 1;
3965                 ffdh_checks = 0;
3966                 break;
3967             }
3968             if (EVP_PKEY_derive(ffdh_ctx, NULL, &secret_size) <= 0) {
3969                 BIO_printf(bio_err, "Checking size of shared secret failed.\n");
3970                 dofail();
3971                 op_count = 1;
3972                 ffdh_checks = 0;
3973                 break;
3974             }
3975             if (secret_size > MAX_FFDH_SIZE) {
3976                 BIO_printf(bio_err, "Assertion failure: shared secret too large.\n");
3977                 op_count = 1;
3978                 ffdh_checks = 0;
3979                 break;
3980             }
3981             if (EVP_PKEY_derive(ffdh_ctx,
3982                                 loopargs[i].secret_ff_a,
3983                                 &secret_size) <= 0) {
3984                 BIO_printf(bio_err, "Shared secret derive failure.\n");
3985                 dofail();
3986                 op_count = 1;
3987                 ffdh_checks = 0;
3988                 break;
3989             }
3990             /* Now check from side B */
3991             test_ctx = EVP_PKEY_CTX_new(pkey_B, NULL);
3992             if (!test_ctx) {
3993                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
3994                 dofail();
3995                 op_count = 1;
3996                 ffdh_checks = 0;
3997                 break;
3998             }
3999             if (EVP_PKEY_derive_init(test_ctx) <= 0 ||
4000                 EVP_PKEY_derive_set_peer(test_ctx, pkey_A) <= 0 ||
4001                 EVP_PKEY_derive(test_ctx, NULL, &test_out) <= 0 ||
4002                 EVP_PKEY_derive(test_ctx, loopargs[i].secret_ff_b, &test_out) <= 0 ||
4003                 test_out != secret_size) {
4004                 BIO_printf(bio_err, "FFDH computation failure.\n");
4005                 op_count = 1;
4006                 ffdh_checks = 0;
4007                 break;
4008             }
4009 
4010             /* compare the computed secrets */
4011             if (CRYPTO_memcmp(loopargs[i].secret_ff_a,
4012                               loopargs[i].secret_ff_b, secret_size)) {
4013                 BIO_printf(bio_err, "FFDH computations don't match.\n");
4014                 dofail();
4015                 op_count = 1;
4016                 ffdh_checks = 0;
4017                 break;
4018             }
4019 
4020             loopargs[i].ffdh_ctx[testnum] = ffdh_ctx;
4021 
4022             EVP_PKEY_free(pkey_A);
4023             pkey_A = NULL;
4024             EVP_PKEY_free(pkey_B);
4025             pkey_B = NULL;
4026             EVP_PKEY_CTX_free(test_ctx);
4027             test_ctx = NULL;
4028         }
4029         if (ffdh_checks != 0) {
4030             pkey_print_message("", "ffdh",
4031                                ffdh_params[testnum].bits, seconds.ffdh);
4032             Time_F(START);
4033             count =
4034                 run_benchmark(async_jobs, FFDH_derive_key_loop, loopargs);
4035             d = Time_F(STOP);
4036             BIO_printf(bio_err,
4037                        mr ? "+R14:%ld:%d:%.2f\n" :
4038                        "%ld %u-bits FFDH ops in %.2fs\n", count,
4039                        ffdh_params[testnum].bits, d);
4040             ffdh_results[testnum][0] = (double)count / d;
4041             op_count = count;
4042         }
4043         if (op_count <= 1) {
4044             /* if longer than 10s, don't do any more */
4045             stop_it(ffdh_doit, testnum);
4046         }
4047     }
4048 #endif  /* OPENSSL_NO_DH */
4049 
4050     for (testnum = 0; testnum < kems_algs_len; testnum++) {
4051         int kem_checks = 1;
4052         const char *kem_name = kems_algname[testnum];
4053 
4054         if (!kems_doit[testnum] || !do_kems)
4055             continue;
4056 
4057         for (i = 0; i < loopargs_len; i++) {
4058             EVP_PKEY *pkey = NULL;
4059             EVP_PKEY_CTX *kem_gen_ctx = NULL;
4060             EVP_PKEY_CTX *kem_encaps_ctx = NULL;
4061             EVP_PKEY_CTX *kem_decaps_ctx = NULL;
4062             size_t send_secret_len, out_len;
4063             size_t rcv_secret_len;
4064             unsigned char *out = NULL, *send_secret = NULL, *rcv_secret;
4065             unsigned int bits;
4066             char *name;
4067             char sfx[MAX_ALGNAME_SUFFIX];
4068             OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
4069             int use_params = 0;
4070             enum kem_type_t { KEM_RSA = 1, KEM_EC, KEM_X25519, KEM_X448 } kem_type;
4071 
4072             /* no string after rsa<bitcnt> permitted: */
4073             if (strlen(kem_name) < MAX_ALGNAME_SUFFIX + 4 /* rsa+digit */
4074                 && sscanf(kem_name, "rsa%u%s", &bits, sfx) == 1)
4075                 kem_type = KEM_RSA;
4076             else if (strncmp(kem_name, "EC", 2) == 0)
4077                 kem_type = KEM_EC;
4078             else if (strcmp(kem_name, "X25519") == 0)
4079                 kem_type = KEM_X25519;
4080             else if (strcmp(kem_name, "X448") == 0)
4081                 kem_type = KEM_X448;
4082             else kem_type = 0;
4083 
4084             if (ERR_peek_error()) {
4085                 BIO_printf(bio_err,
4086                            "WARNING: the error queue contains previous unhandled errors.\n");
4087                 dofail();
4088             }
4089 
4090             if (kem_type == KEM_RSA) {
4091                 params[0] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_RSA_BITS,
4092                                                       &bits);
4093                 use_params = 1;
4094             } else if (kem_type == KEM_EC) {
4095                 name = (char *)(kem_name + 2);
4096                 params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
4097                                                   name, 0);
4098                 use_params = 1;
4099             }
4100 
4101             kem_gen_ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
4102                                                (kem_type == KEM_RSA) ? "RSA":
4103                                                 (kem_type == KEM_EC) ? "EC":
4104                                                  kem_name,
4105                                                app_get0_propq());
4106 
4107             if ((!kem_gen_ctx || EVP_PKEY_keygen_init(kem_gen_ctx) <= 0)
4108                 || (use_params
4109                     && EVP_PKEY_CTX_set_params(kem_gen_ctx, params) <= 0)) {
4110                 BIO_printf(bio_err, "Error initializing keygen ctx for %s.\n",
4111                            kem_name);
4112                 goto kem_err_break;
4113             }
4114             if (EVP_PKEY_keygen(kem_gen_ctx, &pkey) <= 0) {
4115                 BIO_printf(bio_err, "Error while generating KEM EVP_PKEY.\n");
4116                 goto kem_err_break;
4117             }
4118             /* Now prepare encaps data structs */
4119             kem_encaps_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
4120                                                         pkey,
4121                                                         app_get0_propq());
4122             if (kem_encaps_ctx == NULL
4123                 || EVP_PKEY_encapsulate_init(kem_encaps_ctx, NULL) <= 0
4124                 || (kem_type == KEM_RSA
4125                     && EVP_PKEY_CTX_set_kem_op(kem_encaps_ctx, "RSASVE") <= 0)
4126                 || ((kem_type == KEM_EC
4127                     || kem_type == KEM_X25519
4128                     || kem_type == KEM_X448)
4129                    && EVP_PKEY_CTX_set_kem_op(kem_encaps_ctx, "DHKEM") <= 0)
4130                 || EVP_PKEY_encapsulate(kem_encaps_ctx, NULL, &out_len,
4131                                       NULL, &send_secret_len) <= 0) {
4132                 BIO_printf(bio_err,
4133                            "Error while initializing encaps data structs for %s.\n",
4134                            kem_name);
4135                 goto kem_err_break;
4136             }
4137             out = app_malloc(out_len, "encaps result");
4138             send_secret = app_malloc(send_secret_len, "encaps secret");
4139             if (out == NULL || send_secret == NULL) {
4140                 BIO_printf(bio_err, "MemAlloc error in encaps for %s.\n", kem_name);
4141                 goto kem_err_break;
4142             }
4143             if (EVP_PKEY_encapsulate(kem_encaps_ctx, out, &out_len,
4144                                      send_secret, &send_secret_len) <= 0) {
4145                 BIO_printf(bio_err, "Encaps error for %s.\n", kem_name);
4146                 goto kem_err_break;
4147             }
4148             /* Now prepare decaps data structs */
4149             kem_decaps_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
4150                                                         pkey,
4151                                                         app_get0_propq());
4152             if (kem_decaps_ctx == NULL
4153                 || EVP_PKEY_decapsulate_init(kem_decaps_ctx, NULL) <= 0
4154                 || (kem_type == KEM_RSA
4155                   && EVP_PKEY_CTX_set_kem_op(kem_decaps_ctx, "RSASVE") <= 0)
4156                 || ((kem_type == KEM_EC
4157                      || kem_type == KEM_X25519
4158                      || kem_type == KEM_X448)
4159                   && EVP_PKEY_CTX_set_kem_op(kem_decaps_ctx, "DHKEM") <= 0)
4160                 || EVP_PKEY_decapsulate(kem_decaps_ctx, NULL, &rcv_secret_len,
4161                                         out, out_len) <= 0) {
4162                 BIO_printf(bio_err,
4163                            "Error while initializing decaps data structs for %s.\n",
4164                            kem_name);
4165                 goto kem_err_break;
4166             }
4167             rcv_secret = app_malloc(rcv_secret_len, "KEM decaps secret");
4168             if (rcv_secret == NULL) {
4169                 BIO_printf(bio_err, "MemAlloc failure in decaps for %s.\n",
4170                            kem_name);
4171                 goto kem_err_break;
4172             }
4173             if (EVP_PKEY_decapsulate(kem_decaps_ctx, rcv_secret,
4174                                      &rcv_secret_len, out, out_len) <= 0
4175                 || rcv_secret_len != send_secret_len
4176                 || memcmp(send_secret, rcv_secret, send_secret_len)) {
4177                 BIO_printf(bio_err, "Decaps error for %s.\n", kem_name);
4178                 goto kem_err_break;
4179             }
4180             loopargs[i].kem_gen_ctx[testnum] = kem_gen_ctx;
4181             loopargs[i].kem_encaps_ctx[testnum] = kem_encaps_ctx;
4182             loopargs[i].kem_decaps_ctx[testnum] = kem_decaps_ctx;
4183             loopargs[i].kem_out_len[testnum] = out_len;
4184             loopargs[i].kem_secret_len[testnum] = send_secret_len;
4185             loopargs[i].kem_out[testnum] = out;
4186             loopargs[i].kem_send_secret[testnum] = send_secret;
4187             loopargs[i].kem_rcv_secret[testnum] = rcv_secret;
4188             EVP_PKEY_free(pkey);
4189             pkey = NULL;
4190             continue;
4191 
4192         kem_err_break:
4193             dofail();
4194             EVP_PKEY_free(pkey);
4195             op_count = 1;
4196             kem_checks = 0;
4197             break;
4198         }
4199         if (kem_checks != 0) {
4200             kskey_print_message(kem_name, "keygen", seconds.kem);
4201             Time_F(START);
4202             count =
4203                 run_benchmark(async_jobs, KEM_keygen_loop, loopargs);
4204             d = Time_F(STOP);
4205             BIO_printf(bio_err,
4206                        mr ? "+R15:%ld:%s:%.2f\n" :
4207                        "%ld %s KEM keygen ops in %.2fs\n", count,
4208                        kem_name, d);
4209             kems_results[testnum][0] = (double)count / d;
4210             op_count = count;
4211             kskey_print_message(kem_name, "encaps", seconds.kem);
4212             Time_F(START);
4213             count =
4214                 run_benchmark(async_jobs, KEM_encaps_loop, loopargs);
4215             d = Time_F(STOP);
4216             BIO_printf(bio_err,
4217                        mr ? "+R16:%ld:%s:%.2f\n" :
4218                        "%ld %s KEM encaps ops in %.2fs\n", count,
4219                        kem_name, d);
4220             kems_results[testnum][1] = (double)count / d;
4221             op_count = count;
4222             kskey_print_message(kem_name, "decaps", seconds.kem);
4223             Time_F(START);
4224             count =
4225                 run_benchmark(async_jobs, KEM_decaps_loop, loopargs);
4226             d = Time_F(STOP);
4227             BIO_printf(bio_err,
4228                        mr ? "+R17:%ld:%s:%.2f\n" :
4229                        "%ld %s KEM decaps ops in %.2fs\n", count,
4230                        kem_name, d);
4231             kems_results[testnum][2] = (double)count / d;
4232             op_count = count;
4233         }
4234         if (op_count <= 1) {
4235             /* if longer than 10s, don't do any more */
4236             stop_it(kems_doit, testnum);
4237         }
4238     }
4239 
4240     for (testnum = 0; testnum < sigs_algs_len; testnum++) {
4241         int sig_checks = 1;
4242         const char *sig_name = sigs_algname[testnum];
4243 
4244         if (!sigs_doit[testnum] || !do_sigs)
4245             continue;
4246 
4247         for (i = 0; i < loopargs_len; i++) {
4248             EVP_PKEY *pkey = NULL;
4249             EVP_PKEY_CTX *ctx_params = NULL;
4250             EVP_PKEY* pkey_params = NULL;
4251             EVP_PKEY_CTX *sig_gen_ctx = NULL;
4252             EVP_PKEY_CTX *sig_sign_ctx = NULL;
4253             EVP_PKEY_CTX *sig_verify_ctx = NULL;
4254             unsigned char md[SHA256_DIGEST_LENGTH];
4255             unsigned char *sig;
4256             char sfx[MAX_ALGNAME_SUFFIX];
4257             size_t md_len = SHA256_DIGEST_LENGTH;
4258             size_t max_sig_len, sig_len;
4259             unsigned int bits;
4260             OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
4261             int use_params = 0;
4262 
4263             /* only sign little data to avoid measuring digest performance */
4264             memset(md, 0, SHA256_DIGEST_LENGTH);
4265 
4266             if (ERR_peek_error()) {
4267                 BIO_printf(bio_err,
4268                            "WARNING: the error queue contains previous unhandled errors.\n");
4269                 dofail();
4270             }
4271 
4272             /* no string after rsa<bitcnt> permitted: */
4273             if (strlen(sig_name) < MAX_ALGNAME_SUFFIX + 4 /* rsa+digit */
4274                 && sscanf(sig_name, "rsa%u%s", &bits, sfx) == 1) {
4275                 params[0] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_RSA_BITS,
4276                                                       &bits);
4277                 use_params = 1;
4278             }
4279 
4280             if (strncmp(sig_name, "dsa", 3) == 0) {
4281                 ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, NULL);
4282                 if (ctx_params == NULL
4283                     || EVP_PKEY_paramgen_init(ctx_params) <= 0
4284                     || EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx_params,
4285                                                         atoi(sig_name + 3)) <= 0
4286                     || EVP_PKEY_paramgen(ctx_params, &pkey_params) <= 0
4287                     || (sig_gen_ctx = EVP_PKEY_CTX_new(pkey_params, NULL)) == NULL
4288                     || EVP_PKEY_keygen_init(sig_gen_ctx) <= 0) {
4289                     BIO_printf(bio_err,
4290                                "Error initializing classic keygen ctx for %s.\n",
4291                                sig_name);
4292                     goto sig_err_break;
4293                 }
4294             }
4295 
4296             if (sig_gen_ctx == NULL)
4297                 sig_gen_ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
4298                                       use_params == 1 ? "RSA" : sig_name,
4299                                       app_get0_propq());
4300 
4301             if (!sig_gen_ctx || EVP_PKEY_keygen_init(sig_gen_ctx) <= 0
4302                 || (use_params &&
4303                     EVP_PKEY_CTX_set_params(sig_gen_ctx, params) <= 0)) {
4304                 BIO_printf(bio_err, "Error initializing keygen ctx for %s.\n",
4305                            sig_name);
4306                 goto sig_err_break;
4307             }
4308             if (EVP_PKEY_keygen(sig_gen_ctx, &pkey) <= 0) {
4309                 BIO_printf(bio_err,
4310                            "Error while generating signature EVP_PKEY for %s.\n",
4311                            sig_name);
4312                 goto sig_err_break;
4313             }
4314             /* Now prepare signature data structs */
4315             sig_sign_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
4316                                                       pkey,
4317                                                       app_get0_propq());
4318             if (sig_sign_ctx == NULL
4319                 || EVP_PKEY_sign_init(sig_sign_ctx) <= 0
4320                 || (use_params == 1
4321                     && (EVP_PKEY_CTX_set_rsa_padding(sig_sign_ctx,
4322                                                      RSA_PKCS1_PADDING) <= 0))
4323                 || EVP_PKEY_sign(sig_sign_ctx, NULL, &max_sig_len,
4324                                  md, md_len) <= 0) {
4325                     BIO_printf(bio_err,
4326                                "Error while initializing signing data structs for %s.\n",
4327                                sig_name);
4328                     goto sig_err_break;
4329             }
4330             sig = app_malloc(sig_len = max_sig_len, "signature buffer");
4331             if (sig == NULL) {
4332                 BIO_printf(bio_err, "MemAlloc error in sign for %s.\n", sig_name);
4333                 goto sig_err_break;
4334             }
4335             if (EVP_PKEY_sign(sig_sign_ctx, sig, &sig_len, md, md_len) <= 0) {
4336                 BIO_printf(bio_err, "Signing error for %s.\n", sig_name);
4337                 goto sig_err_break;
4338             }
4339             /* Now prepare verify data structs */
4340             memset(md, 0, SHA256_DIGEST_LENGTH);
4341             sig_verify_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
4342                                                         pkey,
4343                                                         app_get0_propq());
4344             if (sig_verify_ctx == NULL
4345                 || EVP_PKEY_verify_init(sig_verify_ctx) <= 0
4346                 || (use_params == 1
4347                   && (EVP_PKEY_CTX_set_rsa_padding(sig_verify_ctx,
4348                                                    RSA_PKCS1_PADDING) <= 0))) {
4349                 BIO_printf(bio_err,
4350                            "Error while initializing verify data structs for %s.\n",
4351                            sig_name);
4352                 goto sig_err_break;
4353             }
4354             if (EVP_PKEY_verify(sig_verify_ctx, sig, sig_len, md, md_len) <= 0) {
4355                 BIO_printf(bio_err, "Verify error for %s.\n", sig_name);
4356                 goto sig_err_break;
4357             }
4358             if (EVP_PKEY_verify(sig_verify_ctx, sig, sig_len, md, md_len) <= 0) {
4359                 BIO_printf(bio_err, "Verify 2 error for %s.\n", sig_name);
4360                 goto sig_err_break;
4361             }
4362             loopargs[i].sig_gen_ctx[testnum] = sig_gen_ctx;
4363             loopargs[i].sig_sign_ctx[testnum] = sig_sign_ctx;
4364             loopargs[i].sig_verify_ctx[testnum] = sig_verify_ctx;
4365             loopargs[i].sig_max_sig_len[testnum] = max_sig_len;
4366             loopargs[i].sig_act_sig_len[testnum] = sig_len;
4367             loopargs[i].sig_sig[testnum] = sig;
4368             EVP_PKEY_free(pkey);
4369             pkey = NULL;
4370             continue;
4371 
4372         sig_err_break:
4373             dofail();
4374             EVP_PKEY_free(pkey);
4375             op_count = 1;
4376             sig_checks = 0;
4377             break;
4378         }
4379 
4380         if (sig_checks != 0) {
4381             kskey_print_message(sig_name, "keygen", seconds.sig);
4382             Time_F(START);
4383             count = run_benchmark(async_jobs, SIG_keygen_loop, loopargs);
4384             d = Time_F(STOP);
4385             BIO_printf(bio_err,
4386                        mr ? "+R18:%ld:%s:%.2f\n" :
4387                        "%ld %s signature keygen ops in %.2fs\n", count,
4388                        sig_name, d);
4389             sigs_results[testnum][0] = (double)count / d;
4390             op_count = count;
4391             kskey_print_message(sig_name, "signs", seconds.sig);
4392             Time_F(START);
4393             count =
4394                 run_benchmark(async_jobs, SIG_sign_loop, loopargs);
4395             d = Time_F(STOP);
4396             BIO_printf(bio_err,
4397                        mr ? "+R19:%ld:%s:%.2f\n" :
4398                        "%ld %s signature sign ops in %.2fs\n", count,
4399                        sig_name, d);
4400             sigs_results[testnum][1] = (double)count / d;
4401             op_count = count;
4402 
4403             kskey_print_message(sig_name, "verify", seconds.sig);
4404             Time_F(START);
4405             count =
4406                 run_benchmark(async_jobs, SIG_verify_loop, loopargs);
4407             d = Time_F(STOP);
4408             BIO_printf(bio_err,
4409                        mr ? "+R20:%ld:%s:%.2f\n" :
4410                        "%ld %s signature verify ops in %.2fs\n", count,
4411                        sig_name, d);
4412             sigs_results[testnum][2] = (double)count / d;
4413             op_count = count;
4414         }
4415         if (op_count <= 1)
4416             stop_it(sigs_doit, testnum);
4417     }
4418 
4419 #ifndef NO_FORK
4420  show_res:
4421 #endif
4422     if (!mr) {
4423         printf("version: %s\n", OpenSSL_version(OPENSSL_FULL_VERSION_STRING));
4424         printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON));
4425         printf("options: %s\n", BN_options());
4426         printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS));
4427         printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO));
4428     }
4429 
4430     if (pr_header) {
4431         if (mr) {
4432             printf("+H");
4433         } else {
4434             printf("The 'numbers' are in 1000s of bytes per second processed.\n");
4435             printf("type        ");
4436         }
4437         for (testnum = 0; testnum < size_num; testnum++)
4438             printf(mr ? ":%d" : "%7d bytes", lengths[testnum]);
4439         printf("\n");
4440     }
4441 
4442     for (k = 0; k < ALGOR_NUM; k++) {
4443         const char *alg_name = names[k];
4444 
4445         if (!doit[k])
4446             continue;
4447 
4448         if (k == D_EVP) {
4449             if (evp_cipher == NULL)
4450                 alg_name = evp_md_name;
4451             else if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL)
4452                 app_bail_out("failed to get name of cipher '%s'\n", evp_cipher);
4453         }
4454 
4455         if (mr)
4456             printf("+F:%u:%s", k, alg_name);
4457         else
4458             printf("%-13s", alg_name);
4459         for (testnum = 0; testnum < size_num; testnum++) {
4460             if (results[k][testnum] > 10000 && !mr)
4461                 printf(" %11.2fk", results[k][testnum] / 1e3);
4462             else
4463                 printf(mr ? ":%.2f" : " %11.2f ", results[k][testnum]);
4464         }
4465         printf("\n");
4466     }
4467     testnum = 1;
4468     for (k = 0; k < RSA_NUM; k++) {
4469         if (!rsa_doit[k])
4470             continue;
4471         if (testnum && !mr) {
4472             printf("%19ssign    verify    encrypt   decrypt   sign/s verify/s  encr./s  decr./s\n", " ");
4473             testnum = 0;
4474         }
4475         if (mr)
4476             printf("+F2:%u:%u:%f:%f:%f:%f\n",
4477                    k, rsa_keys[k].bits, rsa_results[k][0], rsa_results[k][1],
4478                    rsa_results[k][2], rsa_results[k][3]);
4479         else
4480             printf("rsa %5u bits %8.6fs %8.6fs %8.6fs %8.6fs %8.1f %8.1f %8.1f %8.1f\n",
4481                    rsa_keys[k].bits, 1.0 / rsa_results[k][0],
4482                    1.0 / rsa_results[k][1], 1.0 / rsa_results[k][2],
4483                    1.0 / rsa_results[k][3],
4484                    rsa_results[k][0], rsa_results[k][1],
4485                    rsa_results[k][2], rsa_results[k][3]);
4486     }
4487     testnum = 1;
4488 #ifndef OPENSSL_NO_DSA
4489     for (k = 0; k < DSA_NUM; k++) {
4490         if (!dsa_doit[k])
4491             continue;
4492         if (testnum && !mr) {
4493             printf("%18ssign    verify    sign/s verify/s\n", " ");
4494             testnum = 0;
4495         }
4496         if (mr)
4497             printf("+F3:%u:%u:%f:%f\n",
4498                    k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]);
4499         else
4500             printf("dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
4501                    dsa_bits[k], 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1],
4502                    dsa_results[k][0], dsa_results[k][1]);
4503     }
4504 #endif /* OPENSSL_NO_DSA */
4505     testnum = 1;
4506     for (k = 0; k < OSSL_NELEM(ecdsa_doit); k++) {
4507         if (!ecdsa_doit[k])
4508             continue;
4509         if (testnum && !mr) {
4510             printf("%30ssign    verify    sign/s verify/s\n", " ");
4511             testnum = 0;
4512         }
4513 
4514         if (mr)
4515             printf("+F4:%u:%u:%f:%f\n",
4516                    k, ec_curves[k].bits,
4517                    ecdsa_results[k][0], ecdsa_results[k][1]);
4518         else
4519             printf("%4u bits ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
4520                    ec_curves[k].bits, ec_curves[k].name,
4521                    1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1],
4522                    ecdsa_results[k][0], ecdsa_results[k][1]);
4523     }
4524 
4525     testnum = 1;
4526     for (k = 0; k < EC_NUM; k++) {
4527         if (!ecdh_doit[k])
4528             continue;
4529         if (testnum && !mr) {
4530             printf("%30sop      op/s\n", " ");
4531             testnum = 0;
4532         }
4533         if (mr)
4534             printf("+F5:%u:%u:%f:%f\n",
4535                    k, ec_curves[k].bits,
4536                    ecdh_results[k][0], 1.0 / ecdh_results[k][0]);
4537 
4538         else
4539             printf("%4u bits ecdh (%s) %8.4fs %8.1f\n",
4540                    ec_curves[k].bits, ec_curves[k].name,
4541                    1.0 / ecdh_results[k][0], ecdh_results[k][0]);
4542     }
4543 
4544 #ifndef OPENSSL_NO_ECX
4545     testnum = 1;
4546     for (k = 0; k < OSSL_NELEM(eddsa_doit); k++) {
4547         if (!eddsa_doit[k])
4548             continue;
4549         if (testnum && !mr) {
4550             printf("%30ssign    verify    sign/s verify/s\n", " ");
4551             testnum = 0;
4552         }
4553 
4554         if (mr)
4555             printf("+F6:%u:%u:%s:%f:%f\n",
4556                    k, ed_curves[k].bits, ed_curves[k].name,
4557                    eddsa_results[k][0], eddsa_results[k][1]);
4558         else
4559             printf("%4u bits EdDSA (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
4560                    ed_curves[k].bits, ed_curves[k].name,
4561                    1.0 / eddsa_results[k][0], 1.0 / eddsa_results[k][1],
4562                    eddsa_results[k][0], eddsa_results[k][1]);
4563     }
4564 #endif /* OPENSSL_NO_ECX */
4565 
4566 #ifndef OPENSSL_NO_SM2
4567     testnum = 1;
4568     for (k = 0; k < OSSL_NELEM(sm2_doit); k++) {
4569         if (!sm2_doit[k])
4570             continue;
4571         if (testnum && !mr) {
4572             printf("%30ssign    verify    sign/s verify/s\n", " ");
4573             testnum = 0;
4574         }
4575 
4576         if (mr)
4577             printf("+F7:%u:%u:%s:%f:%f\n",
4578                    k, sm2_curves[k].bits, sm2_curves[k].name,
4579                    sm2_results[k][0], sm2_results[k][1]);
4580         else
4581             printf("%4u bits SM2 (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
4582                    sm2_curves[k].bits, sm2_curves[k].name,
4583                    1.0 / sm2_results[k][0], 1.0 / sm2_results[k][1],
4584                    sm2_results[k][0], sm2_results[k][1]);
4585     }
4586 #endif
4587 #ifndef OPENSSL_NO_DH
4588     testnum = 1;
4589     for (k = 0; k < FFDH_NUM; k++) {
4590         if (!ffdh_doit[k])
4591             continue;
4592         if (testnum && !mr) {
4593             printf("%23sop     op/s\n", " ");
4594             testnum = 0;
4595         }
4596         if (mr)
4597             printf("+F8:%u:%u:%f:%f\n",
4598                    k, ffdh_params[k].bits,
4599                    ffdh_results[k][0], 1.0 / ffdh_results[k][0]);
4600 
4601         else
4602             printf("%4u bits ffdh %8.4fs %8.1f\n",
4603                    ffdh_params[k].bits,
4604                    1.0 / ffdh_results[k][0], ffdh_results[k][0]);
4605     }
4606 #endif /* OPENSSL_NO_DH */
4607 
4608     testnum = 1;
4609     for (k = 0; k < kems_algs_len; k++) {
4610         const char *kem_name = kems_algname[k];
4611 
4612         if (!kems_doit[k] || !do_kems)
4613             continue;
4614         if (testnum && !mr) {
4615             printf("%31skeygen    encaps    decaps keygens/s  encaps/s  decaps/s\n", " ");
4616             testnum = 0;
4617         }
4618         if (mr)
4619             printf("+F9:%u:%f:%f:%f\n",
4620                    k, kems_results[k][0], kems_results[k][1],
4621                    kems_results[k][2]);
4622         else
4623             printf("%27s %8.6fs %8.6fs %8.6fs %9.1f %9.1f %9.1f\n", kem_name,
4624                    1.0 / kems_results[k][0],
4625                    1.0 / kems_results[k][1], 1.0 / kems_results[k][2],
4626                    kems_results[k][0], kems_results[k][1], kems_results[k][2]);
4627     }
4628     ret = 0;
4629 
4630     testnum = 1;
4631     for (k = 0; k < sigs_algs_len; k++) {
4632         const char *sig_name = sigs_algname[k];
4633 
4634         if (!sigs_doit[k] || !do_sigs)
4635             continue;
4636         if (testnum && !mr) {
4637             printf("%31skeygen     signs    verify keygens/s    sign/s  verify/s\n", " ");
4638             testnum = 0;
4639         }
4640         if (mr)
4641             printf("+F10:%u:%f:%f:%f\n",
4642                    k, sigs_results[k][0], sigs_results[k][1],
4643                    sigs_results[k][2]);
4644         else
4645             printf("%27s %8.6fs %8.6fs %8.6fs %9.1f %9.1f %9.1f\n", sig_name,
4646                    1.0 / sigs_results[k][0], 1.0 / sigs_results[k][1],
4647                    1.0 / sigs_results[k][2], sigs_results[k][0],
4648                    sigs_results[k][1], sigs_results[k][2]);
4649     }
4650     ret = 0;
4651 
4652  end:
4653     if (ret == 0 && testmode)
4654         ret = testmoderesult;
4655     ERR_print_errors(bio_err);
4656     for (i = 0; i < loopargs_len; i++) {
4657         OPENSSL_free(loopargs[i].buf_malloc);
4658         OPENSSL_free(loopargs[i].buf2_malloc);
4659 
4660         BN_free(bn);
4661         EVP_PKEY_CTX_free(genctx);
4662         for (k = 0; k < RSA_NUM; k++) {
4663             EVP_PKEY_CTX_free(loopargs[i].rsa_sign_ctx[k]);
4664             EVP_PKEY_CTX_free(loopargs[i].rsa_verify_ctx[k]);
4665             EVP_PKEY_CTX_free(loopargs[i].rsa_encrypt_ctx[k]);
4666             EVP_PKEY_CTX_free(loopargs[i].rsa_decrypt_ctx[k]);
4667         }
4668 #ifndef OPENSSL_NO_DH
4669         OPENSSL_free(loopargs[i].secret_ff_a);
4670         OPENSSL_free(loopargs[i].secret_ff_b);
4671         for (k = 0; k < FFDH_NUM; k++)
4672             EVP_PKEY_CTX_free(loopargs[i].ffdh_ctx[k]);
4673 #endif
4674 #ifndef OPENSSL_NO_DSA
4675         for (k = 0; k < DSA_NUM; k++) {
4676             EVP_PKEY_CTX_free(loopargs[i].dsa_sign_ctx[k]);
4677             EVP_PKEY_CTX_free(loopargs[i].dsa_verify_ctx[k]);
4678         }
4679 #endif
4680         for (k = 0; k < ECDSA_NUM; k++) {
4681             EVP_PKEY_CTX_free(loopargs[i].ecdsa_sign_ctx[k]);
4682             EVP_PKEY_CTX_free(loopargs[i].ecdsa_verify_ctx[k]);
4683         }
4684         for (k = 0; k < EC_NUM; k++)
4685             EVP_PKEY_CTX_free(loopargs[i].ecdh_ctx[k]);
4686 #ifndef OPENSSL_NO_ECX
4687         for (k = 0; k < EdDSA_NUM; k++) {
4688             EVP_MD_CTX_free(loopargs[i].eddsa_ctx[k]);
4689             EVP_MD_CTX_free(loopargs[i].eddsa_ctx2[k]);
4690         }
4691 #endif /* OPENSSL_NO_ECX */
4692 #ifndef OPENSSL_NO_SM2
4693         for (k = 0; k < SM2_NUM; k++) {
4694             EVP_PKEY_CTX *pctx = NULL;
4695 
4696             /* free signing ctx */
4697             if (loopargs[i].sm2_ctx[k] != NULL
4698                 && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_ctx[k])) != NULL)
4699                 EVP_PKEY_CTX_free(pctx);
4700             EVP_MD_CTX_free(loopargs[i].sm2_ctx[k]);
4701             /* free verification ctx */
4702             if (loopargs[i].sm2_vfy_ctx[k] != NULL
4703                 && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_vfy_ctx[k])) != NULL)
4704                 EVP_PKEY_CTX_free(pctx);
4705             EVP_MD_CTX_free(loopargs[i].sm2_vfy_ctx[k]);
4706             /* free pkey */
4707             EVP_PKEY_free(loopargs[i].sm2_pkey[k]);
4708         }
4709 #endif
4710         for (k = 0; k < kems_algs_len; k++) {
4711             EVP_PKEY_CTX_free(loopargs[i].kem_gen_ctx[k]);
4712             EVP_PKEY_CTX_free(loopargs[i].kem_encaps_ctx[k]);
4713             EVP_PKEY_CTX_free(loopargs[i].kem_decaps_ctx[k]);
4714             OPENSSL_free(loopargs[i].kem_out[k]);
4715             OPENSSL_free(loopargs[i].kem_send_secret[k]);
4716             OPENSSL_free(loopargs[i].kem_rcv_secret[k]);
4717         }
4718         for (k = 0; k < sigs_algs_len; k++) {
4719             EVP_PKEY_CTX_free(loopargs[i].sig_gen_ctx[k]);
4720             EVP_PKEY_CTX_free(loopargs[i].sig_sign_ctx[k]);
4721             EVP_PKEY_CTX_free(loopargs[i].sig_verify_ctx[k]);
4722             OPENSSL_free(loopargs[i].sig_sig[k]);
4723         }
4724         OPENSSL_free(loopargs[i].secret_a);
4725         OPENSSL_free(loopargs[i].secret_b);
4726     }
4727     OPENSSL_free(evp_hmac_name);
4728     OPENSSL_free(evp_cmac_name);
4729     for (k = 0; k < kems_algs_len; k++)
4730         OPENSSL_free(kems_algname[k]);
4731     if (kem_stack != NULL)
4732         sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free);
4733     for (k = 0; k < sigs_algs_len; k++)
4734         OPENSSL_free(sigs_algname[k]);
4735     if (sig_stack != NULL)
4736         sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free);
4737 
4738     if (async_jobs > 0) {
4739         for (i = 0; i < loopargs_len; i++)
4740             ASYNC_WAIT_CTX_free(loopargs[i].wait_ctx);
4741     }
4742 
4743     if (async_init) {
4744         ASYNC_cleanup_thread();
4745     }
4746     OPENSSL_free(loopargs);
4747     release_engine(e);
4748     EVP_CIPHER_free(evp_cipher);
4749     EVP_MAC_free(mac);
4750     NCONF_free(conf);
4751     return ret;
4752 }
4753 
print_message(const char * s,int length,int tm)4754 static void print_message(const char *s, int length, int tm)
4755 {
4756     BIO_printf(bio_err,
4757                mr ? "+DT:%s:%d:%d\n"
4758                : "Doing %s ops for %ds on %d size blocks: ", s, tm, length);
4759     (void)BIO_flush(bio_err);
4760     run = 1;
4761     alarm(tm);
4762 }
4763 
pkey_print_message(const char * str,const char * str2,unsigned int bits,int tm)4764 static void pkey_print_message(const char *str, const char *str2, unsigned int bits,
4765                                int tm)
4766 {
4767     BIO_printf(bio_err,
4768                mr ? "+DTP:%d:%s:%s:%d\n"
4769                : "Doing %u bits %s %s ops for %ds: ", bits, str, str2, tm);
4770     (void)BIO_flush(bio_err);
4771     run = 1;
4772     alarm(tm);
4773 }
4774 
kskey_print_message(const char * str,const char * str2,int tm)4775 static void kskey_print_message(const char *str, const char *str2, int tm)
4776 {
4777     BIO_printf(bio_err,
4778                mr ? "+DTP:%s:%s:%d\n"
4779                : "Doing %s %s ops for %ds: ", str, str2, tm);
4780     (void)BIO_flush(bio_err);
4781     run = 1;
4782     alarm(tm);
4783 }
4784 
print_result(int alg,int run_no,int count,double time_used)4785 static void print_result(int alg, int run_no, int count, double time_used)
4786 {
4787     if (count == -1) {
4788         BIO_printf(bio_err, "%s error!\n", names[alg]);
4789         dofail();
4790         return;
4791     }
4792     BIO_printf(bio_err,
4793                mr ? "+R:%d:%s:%f\n"
4794                : "%d %s ops in %.2fs\n", count, names[alg], time_used);
4795     results[alg][run_no] = ((double)count) / time_used * lengths[run_no];
4796 }
4797 
4798 #ifndef NO_FORK
sstrsep(char ** string,const char * delim)4799 static char *sstrsep(char **string, const char *delim)
4800 {
4801     char isdelim[256];
4802     char *token = *string;
4803 
4804     memset(isdelim, 0, sizeof(isdelim));
4805     isdelim[0] = 1;
4806 
4807     while (*delim) {
4808         isdelim[(unsigned char)(*delim)] = 1;
4809         delim++;
4810     }
4811 
4812     while (!isdelim[(unsigned char)(**string)])
4813         (*string)++;
4814 
4815     if (**string) {
4816         **string = 0;
4817         (*string)++;
4818     }
4819 
4820     return token;
4821 }
4822 
strtoint(const char * str,const int min_val,const int upper_val,int * res)4823 static int strtoint(const char *str, const int min_val, const int upper_val,
4824                     int *res)
4825 {
4826     char *end = NULL;
4827     long int val = 0;
4828 
4829     errno = 0;
4830     val = strtol(str, &end, 10);
4831     if (errno == 0 && end != str && *end == 0
4832         && min_val <= val && val < upper_val) {
4833         *res = (int)val;
4834         return 1;
4835     } else {
4836         return 0;
4837     }
4838 }
4839 
do_multi(int multi,int size_num)4840 static int do_multi(int multi, int size_num)
4841 {
4842     int n;
4843     int fd[2];
4844     int *fds;
4845     int status;
4846     static char sep[] = ":";
4847 
4848     fds = app_malloc(sizeof(*fds) * multi, "fd buffer for do_multi");
4849     for (n = 0; n < multi; ++n) {
4850         if (pipe(fd) == -1) {
4851             BIO_printf(bio_err, "pipe failure\n");
4852             exit(1);
4853         }
4854         fflush(stdout);
4855         (void)BIO_flush(bio_err);
4856         if (fork()) {
4857             close(fd[1]);
4858             fds[n] = fd[0];
4859         } else {
4860             close(fd[0]);
4861             close(1);
4862             if (dup(fd[1]) == -1) {
4863                 BIO_printf(bio_err, "dup failed\n");
4864                 exit(1);
4865             }
4866             close(fd[1]);
4867             mr = 1;
4868             usertime = 0;
4869             OPENSSL_free(fds);
4870             return 0;
4871         }
4872         printf("Forked child %d\n", n);
4873     }
4874 
4875     /* for now, assume the pipe is long enough to take all the output */
4876     for (n = 0; n < multi; ++n) {
4877         FILE *f;
4878         char buf[1024];
4879         char *p;
4880         char *tk;
4881         int k;
4882         double d;
4883 
4884         if ((f = fdopen(fds[n], "r")) == NULL) {
4885             BIO_printf(bio_err, "fdopen failure with 0x%x\n",
4886                        errno);
4887             OPENSSL_free(fds);
4888             return 1;
4889         }
4890         while (fgets(buf, sizeof(buf), f)) {
4891             p = strchr(buf, '\n');
4892             if (p)
4893                 *p = '\0';
4894             if (buf[0] != '+') {
4895                 BIO_printf(bio_err,
4896                            "Don't understand line '%s' from child %d\n", buf,
4897                            n);
4898                 continue;
4899             }
4900             printf("Got: %s from %d\n", buf, n);
4901             p = buf;
4902             if (CHECK_AND_SKIP_PREFIX(p, "+F:")) {
4903                 int alg;
4904                 int j;
4905 
4906                 if (strtoint(sstrsep(&p, sep), 0, ALGOR_NUM, &alg)) {
4907                     sstrsep(&p, sep);
4908                     for (j = 0; j < size_num; ++j)
4909                         results[alg][j] += atof(sstrsep(&p, sep));
4910                 }
4911             } else if (CHECK_AND_SKIP_PREFIX(p, "+F2:")) {
4912                 tk = sstrsep(&p, sep);
4913                 if (strtoint(tk, 0, OSSL_NELEM(rsa_results), &k)) {
4914                     sstrsep(&p, sep);
4915 
4916                     d = atof(sstrsep(&p, sep));
4917                     rsa_results[k][0] += d;
4918 
4919                     d = atof(sstrsep(&p, sep));
4920                     rsa_results[k][1] += d;
4921 
4922                     d = atof(sstrsep(&p, sep));
4923                     rsa_results[k][2] += d;
4924 
4925                     d = atof(sstrsep(&p, sep));
4926                     rsa_results[k][3] += d;
4927                 }
4928 # ifndef OPENSSL_NO_DSA
4929             } else if (CHECK_AND_SKIP_PREFIX(p, "+F3:")) {
4930                 tk = sstrsep(&p, sep);
4931                 if (strtoint(tk, 0, OSSL_NELEM(dsa_results), &k)) {
4932                     sstrsep(&p, sep);
4933 
4934                     d = atof(sstrsep(&p, sep));
4935                     dsa_results[k][0] += d;
4936 
4937                     d = atof(sstrsep(&p, sep));
4938                     dsa_results[k][1] += d;
4939                 }
4940 # endif /* OPENSSL_NO_DSA */
4941             } else if (CHECK_AND_SKIP_PREFIX(p, "+F4:")) {
4942                 tk = sstrsep(&p, sep);
4943                 if (strtoint(tk, 0, OSSL_NELEM(ecdsa_results), &k)) {
4944                     sstrsep(&p, sep);
4945 
4946                     d = atof(sstrsep(&p, sep));
4947                     ecdsa_results[k][0] += d;
4948 
4949                     d = atof(sstrsep(&p, sep));
4950                     ecdsa_results[k][1] += d;
4951                 }
4952             } else if (CHECK_AND_SKIP_PREFIX(p, "+F5:")) {
4953                 tk = sstrsep(&p, sep);
4954                 if (strtoint(tk, 0, OSSL_NELEM(ecdh_results), &k)) {
4955                     sstrsep(&p, sep);
4956 
4957                     d = atof(sstrsep(&p, sep));
4958                     ecdh_results[k][0] += d;
4959                 }
4960 # ifndef OPENSSL_NO_ECX
4961             } else if (CHECK_AND_SKIP_PREFIX(p, "+F6:")) {
4962                 tk = sstrsep(&p, sep);
4963                 if (strtoint(tk, 0, OSSL_NELEM(eddsa_results), &k)) {
4964                     sstrsep(&p, sep);
4965                     sstrsep(&p, sep);
4966 
4967                     d = atof(sstrsep(&p, sep));
4968                     eddsa_results[k][0] += d;
4969 
4970                     d = atof(sstrsep(&p, sep));
4971                     eddsa_results[k][1] += d;
4972                 }
4973 # endif /* OPENSSL_NO_ECX */
4974 # ifndef OPENSSL_NO_SM2
4975             } else if (CHECK_AND_SKIP_PREFIX(p, "+F7:")) {
4976                 tk = sstrsep(&p, sep);
4977                 if (strtoint(tk, 0, OSSL_NELEM(sm2_results), &k)) {
4978                     sstrsep(&p, sep);
4979                     sstrsep(&p, sep);
4980 
4981                     d = atof(sstrsep(&p, sep));
4982                     sm2_results[k][0] += d;
4983 
4984                     d = atof(sstrsep(&p, sep));
4985                     sm2_results[k][1] += d;
4986                 }
4987 # endif /* OPENSSL_NO_SM2 */
4988 # ifndef OPENSSL_NO_DH
4989             } else if (CHECK_AND_SKIP_PREFIX(p, "+F8:")) {
4990                 tk = sstrsep(&p, sep);
4991                 if (strtoint(tk, 0, OSSL_NELEM(ffdh_results), &k)) {
4992                     sstrsep(&p, sep);
4993 
4994                     d = atof(sstrsep(&p, sep));
4995                     ffdh_results[k][0] += d;
4996                 }
4997 # endif /* OPENSSL_NO_DH */
4998             } else if (CHECK_AND_SKIP_PREFIX(p, "+F9:")) {
4999                 tk = sstrsep(&p, sep);
5000                 if (strtoint(tk, 0, OSSL_NELEM(kems_results), &k)) {
5001                     d = atof(sstrsep(&p, sep));
5002                     kems_results[k][0] += d;
5003 
5004                     d = atof(sstrsep(&p, sep));
5005                     kems_results[k][1] += d;
5006 
5007                     d = atof(sstrsep(&p, sep));
5008                     kems_results[k][2] += d;
5009                 }
5010             } else if (CHECK_AND_SKIP_PREFIX(p, "+F10:")) {
5011                 tk = sstrsep(&p, sep);
5012                 if (strtoint(tk, 0, OSSL_NELEM(sigs_results), &k)) {
5013                     d = atof(sstrsep(&p, sep));
5014                     sigs_results[k][0] += d;
5015 
5016                     d = atof(sstrsep(&p, sep));
5017                     sigs_results[k][1] += d;
5018 
5019                     d = atof(sstrsep(&p, sep));
5020                     sigs_results[k][2] += d;
5021                 }
5022             } else if (!HAS_PREFIX(buf, "+H:")) {
5023                 BIO_printf(bio_err, "Unknown type '%s' from child %d\n", buf,
5024                            n);
5025             }
5026         }
5027 
5028         fclose(f);
5029     }
5030     OPENSSL_free(fds);
5031     for (n = 0; n < multi; ++n) {
5032         while (wait(&status) == -1)
5033             if (errno != EINTR) {
5034                 BIO_printf(bio_err, "Waitng for child failed with 0x%x\n",
5035                            errno);
5036                 return 1;
5037             }
5038         if (WIFEXITED(status) && WEXITSTATUS(status)) {
5039             BIO_printf(bio_err, "Child exited with %d\n", WEXITSTATUS(status));
5040         } else if (WIFSIGNALED(status)) {
5041             BIO_printf(bio_err, "Child terminated by signal %d\n",
5042                        WTERMSIG(status));
5043         }
5044     }
5045     return 1;
5046 }
5047 #endif
5048 
multiblock_speed(const EVP_CIPHER * evp_cipher,int lengths_single,const openssl_speed_sec_t * seconds)5049 static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single,
5050                              const openssl_speed_sec_t *seconds)
5051 {
5052     static const int mblengths_list[] = {
5053         8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024
5054     };
5055     const int *mblengths = mblengths_list;
5056     int j, count, keylen, num = OSSL_NELEM(mblengths_list), ciph_success = 1;
5057     const char *alg_name;
5058     unsigned char *inp = NULL, *out = NULL, *key, no_key[32], no_iv[16];
5059     EVP_CIPHER_CTX *ctx = NULL;
5060     double d = 0.0;
5061 
5062     if (lengths_single) {
5063         mblengths = &lengths_single;
5064         num = 1;
5065     }
5066 
5067     inp = app_malloc(mblengths[num - 1], "multiblock input buffer");
5068     out = app_malloc(mblengths[num - 1] + 1024, "multiblock output buffer");
5069     if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
5070         app_bail_out("failed to allocate cipher context\n");
5071     if (!EVP_EncryptInit_ex(ctx, evp_cipher, NULL, NULL, no_iv))
5072         app_bail_out("failed to initialise cipher context\n");
5073 
5074     if ((keylen = EVP_CIPHER_CTX_get_key_length(ctx)) < 0) {
5075         BIO_printf(bio_err, "Impossible negative key length: %d\n", keylen);
5076         goto err;
5077     }
5078     key = app_malloc(keylen, "evp_cipher key");
5079     if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
5080         app_bail_out("failed to generate random cipher key\n");
5081     if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL))
5082         app_bail_out("failed to set cipher key\n");
5083     OPENSSL_clear_free(key, keylen);
5084 
5085     if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
5086                              sizeof(no_key), no_key) <= 0)
5087         app_bail_out("failed to set AEAD key\n");
5088     if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL)
5089         app_bail_out("failed to get cipher name\n");
5090 
5091     for (j = 0; j < num; j++) {
5092         print_message(alg_name, mblengths[j], seconds->sym);
5093         Time_F(START);
5094         for (count = 0; run && COND(count); count++) {
5095             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
5096             size_t len = mblengths[j];
5097             int packlen;
5098 
5099             memset(aad, 0, 8);  /* avoid uninitialized values */
5100             aad[8] = 23;        /* SSL3_RT_APPLICATION_DATA */
5101             aad[9] = 3;         /* version */
5102             aad[10] = 2;
5103             aad[11] = 0;        /* length */
5104             aad[12] = 0;
5105             mb_param.out = NULL;
5106             mb_param.inp = aad;
5107             mb_param.len = len;
5108             mb_param.interleave = 8;
5109 
5110             packlen = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
5111                                           sizeof(mb_param), &mb_param);
5112 
5113             if (packlen > 0) {
5114                 mb_param.out = out;
5115                 mb_param.inp = inp;
5116                 mb_param.len = len;
5117                 (void)EVP_CIPHER_CTX_ctrl(ctx,
5118                                           EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
5119                                           sizeof(mb_param), &mb_param);
5120             } else {
5121                 int pad;
5122 
5123                 if (RAND_bytes(inp, 16) <= 0)
5124                     app_bail_out("error setting random bytes\n");
5125                 len += 16;
5126                 aad[11] = (unsigned char)(len >> 8);
5127                 aad[12] = (unsigned char)(len);
5128                 pad = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD,
5129                                           EVP_AEAD_TLS1_AAD_LEN, aad);
5130                 ciph_success = EVP_Cipher(ctx, out, inp, len + pad);
5131             }
5132         }
5133         d = Time_F(STOP);
5134         BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n"
5135                    : "%d %s ops in %.2fs\n", count, "evp", d);
5136         if ((ciph_success <= 0) && (mr == 0))
5137             BIO_printf(bio_err, "Error performing cipher op\n");
5138         results[D_EVP][j] = ((double)count) / d * mblengths[j];
5139     }
5140 
5141     if (mr) {
5142         fprintf(stdout, "+H");
5143         for (j = 0; j < num; j++)
5144             fprintf(stdout, ":%d", mblengths[j]);
5145         fprintf(stdout, "\n");
5146         fprintf(stdout, "+F:%d:%s", D_EVP, alg_name);
5147         for (j = 0; j < num; j++)
5148             fprintf(stdout, ":%.2f", results[D_EVP][j]);
5149         fprintf(stdout, "\n");
5150     } else {
5151         fprintf(stdout,
5152                 "The 'numbers' are in 1000s of bytes per second processed.\n");
5153         fprintf(stdout, "type                    ");
5154         for (j = 0; j < num; j++)
5155             fprintf(stdout, "%7d bytes", mblengths[j]);
5156         fprintf(stdout, "\n");
5157         fprintf(stdout, "%-24s", alg_name);
5158 
5159         for (j = 0; j < num; j++) {
5160             if (results[D_EVP][j] > 10000)
5161                 fprintf(stdout, " %11.2fk", results[D_EVP][j] / 1e3);
5162             else
5163                 fprintf(stdout, " %11.2f ", results[D_EVP][j]);
5164         }
5165         fprintf(stdout, "\n");
5166     }
5167 
5168  err:
5169     OPENSSL_free(inp);
5170     OPENSSL_free(out);
5171     EVP_CIPHER_CTX_free(ctx);
5172 }
5173