xref: /openssl/apps/speed.c (revision 56233ba8)
1 /*
2  * Copyright 1995-2022 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 
23 /* We need to use some deprecated APIs */
24 #define OPENSSL_SUPPRESS_DEPRECATED
25 
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <math.h>
30 #include "apps.h"
31 #include "progs.h"
32 #include "internal/numbers.h"
33 #include <openssl/crypto.h>
34 #include <openssl/rand.h>
35 #include <openssl/err.h>
36 #include <openssl/evp.h>
37 #include <openssl/objects.h>
38 #include <openssl/core_names.h>
39 #include <openssl/async.h>
40 #if !defined(OPENSSL_SYS_MSDOS)
41 # include <unistd.h>
42 #endif
43 
44 #if defined(__TANDEM)
45 # if defined(OPENSSL_TANDEM_FLOSS)
46 #  include <floss.h(floss_fork)>
47 # endif
48 #endif
49 
50 #if defined(_WIN32)
51 # include <windows.h>
52 #endif
53 
54 #include <openssl/bn.h>
55 #include <openssl/rsa.h>
56 #include "./testrsa.h"
57 #ifndef OPENSSL_NO_DH
58 # include <openssl/dh.h>
59 #endif
60 #include <openssl/x509.h>
61 #include <openssl/dsa.h>
62 #include "./testdsa.h"
63 #include <openssl/modes.h>
64 
65 #ifndef HAVE_FORK
66 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_VXWORKS)
67 #  define HAVE_FORK 0
68 # else
69 #  define HAVE_FORK 1
70 #  include <sys/wait.h>
71 # endif
72 #endif
73 
74 #if HAVE_FORK
75 # undef NO_FORK
76 #else
77 # define NO_FORK
78 #endif
79 
80 #define MAX_MISALIGNMENT 63
81 #define MAX_ECDH_SIZE   256
82 #define MISALIGN        64
83 #define MAX_FFDH_SIZE 1024
84 
85 #ifndef RSA_DEFAULT_PRIME_NUM
86 # define RSA_DEFAULT_PRIME_NUM 2
87 #endif
88 
89 typedef struct openssl_speed_sec_st {
90     int sym;
91     int rsa;
92     int dsa;
93     int ecdsa;
94     int ecdh;
95     int eddsa;
96     int sm2;
97     int ffdh;
98 } openssl_speed_sec_t;
99 
100 static volatile int run = 0;
101 
102 static int mr = 0;  /* machine-readeable output format to merge fork results */
103 static int usertime = 1;
104 
105 static double Time_F(int s);
106 static void print_message(const char *s, long num, int length, int tm);
107 static void pkey_print_message(const char *str, const char *str2,
108                                long num, unsigned int bits, int sec);
109 static void print_result(int alg, int run_no, int count, double time_used);
110 #ifndef NO_FORK
111 static int do_multi(int multi, int size_num);
112 #endif
113 
114 static const int lengths_list[] = {
115     16, 64, 256, 1024, 8 * 1024, 16 * 1024
116 };
117 #define SIZE_NUM         OSSL_NELEM(lengths_list)
118 static const int *lengths = lengths_list;
119 
120 static const int aead_lengths_list[] = {
121     2, 31, 136, 1024, 8 * 1024, 16 * 1024
122 };
123 
124 #define START   0
125 #define STOP    1
126 
127 #ifdef SIGALRM
128 
alarmed(int sig)129 static void alarmed(int sig)
130 {
131     signal(SIGALRM, alarmed);
132     run = 0;
133 }
134 
Time_F(int s)135 static double Time_F(int s)
136 {
137     double ret = app_tminterval(s, usertime);
138     if (s == STOP)
139         alarm(0);
140     return ret;
141 }
142 
143 #elif defined(_WIN32)
144 
145 # define SIGALRM -1
146 
147 static unsigned int lapse;
148 static volatile unsigned int schlock;
alarm_win32(unsigned int secs)149 static void alarm_win32(unsigned int secs)
150 {
151     lapse = secs * 1000;
152 }
153 
154 # define alarm alarm_win32
155 
sleepy(VOID * arg)156 static DWORD WINAPI sleepy(VOID * arg)
157 {
158     schlock = 1;
159     Sleep(lapse);
160     run = 0;
161     return 0;
162 }
163 
Time_F(int s)164 static double Time_F(int s)
165 {
166     double ret;
167     static HANDLE thr;
168 
169     if (s == START) {
170         schlock = 0;
171         thr = CreateThread(NULL, 4096, sleepy, NULL, 0, NULL);
172         if (thr == NULL) {
173             DWORD err = GetLastError();
174             BIO_printf(bio_err, "unable to CreateThread (%lu)", err);
175             ExitProcess(err);
176         }
177         while (!schlock)
178             Sleep(0);           /* scheduler spinlock */
179         ret = app_tminterval(s, usertime);
180     } else {
181         ret = app_tminterval(s, usertime);
182         if (run)
183             TerminateThread(thr, 0);
184         CloseHandle(thr);
185     }
186 
187     return ret;
188 }
189 #else
190 # error "SIGALRM not defined and the platform is not Windows"
191 #endif
192 
193 static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single,
194                              const openssl_speed_sec_t *seconds);
195 
opt_found(const char * name,unsigned int * result,const OPT_PAIR pairs[],unsigned int nbelem)196 static int opt_found(const char *name, unsigned int *result,
197                      const OPT_PAIR pairs[], unsigned int nbelem)
198 {
199     unsigned int idx;
200 
201     for (idx = 0; idx < nbelem; ++idx, pairs++)
202         if (strcmp(name, pairs->name) == 0) {
203             *result = pairs->retval;
204             return 1;
205         }
206     return 0;
207 }
208 #define opt_found(value, pairs, result)\
209     opt_found(value, result, pairs, OSSL_NELEM(pairs))
210 
211 typedef enum OPTION_choice {
212     OPT_COMMON,
213     OPT_ELAPSED, OPT_EVP, OPT_HMAC, OPT_DECRYPT, OPT_ENGINE, OPT_MULTI,
214     OPT_MR, OPT_MB, OPT_MISALIGN, OPT_ASYNCJOBS, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG,
215     OPT_PRIMES, OPT_SECONDS, OPT_BYTES, OPT_AEAD, OPT_CMAC
216 } OPTION_CHOICE;
217 
218 const OPTIONS speed_options[] = {
219     {OPT_HELP_STR, 1, '-',
220      "Usage: %s [options] [algorithm...]\n"
221      "All +int options consider prefix '0' as base-8 input, "
222      "prefix '0x'/'0X' as base-16 input.\n"
223     },
224 
225     OPT_SECTION("General"),
226     {"help", OPT_HELP, '-', "Display this summary"},
227     {"mb", OPT_MB, '-',
228      "Enable (tls1>=1) multi-block mode on EVP-named cipher"},
229     {"mr", OPT_MR, '-', "Produce machine readable output"},
230 #ifndef NO_FORK
231     {"multi", OPT_MULTI, 'p', "Run benchmarks in parallel"},
232 #endif
233 #ifndef OPENSSL_NO_ASYNC
234     {"async_jobs", OPT_ASYNCJOBS, 'p',
235      "Enable async mode and start specified number of jobs"},
236 #endif
237 #ifndef OPENSSL_NO_ENGINE
238     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
239 #endif
240     {"primes", OPT_PRIMES, 'p', "Specify number of primes (for RSA only)"},
241     OPT_CONFIG_OPTION,
242 
243     OPT_SECTION("Selection"),
244     {"evp", OPT_EVP, 's', "Use EVP-named cipher or digest"},
245     {"hmac", OPT_HMAC, 's', "HMAC using EVP-named digest"},
246     {"cmac", OPT_CMAC, 's', "CMAC using EVP-named cipher"},
247     {"decrypt", OPT_DECRYPT, '-',
248      "Time decryption instead of encryption (only EVP)"},
249     {"aead", OPT_AEAD, '-',
250      "Benchmark EVP-named AEAD cipher in TLS-like sequence"},
251 
252     OPT_SECTION("Timing"),
253     {"elapsed", OPT_ELAPSED, '-',
254      "Use wall-clock time instead of CPU user time as divisor"},
255     {"seconds", OPT_SECONDS, 'p',
256      "Run benchmarks for specified amount of seconds"},
257     {"bytes", OPT_BYTES, 'p',
258      "Run [non-PKI] benchmarks on custom-sized buffer"},
259     {"misalign", OPT_MISALIGN, 'p',
260      "Use specified offset to mis-align buffers"},
261 
262     OPT_R_OPTIONS,
263     OPT_PROV_OPTIONS,
264 
265     OPT_PARAMETERS(),
266     {"algorithm", 0, 0, "Algorithm(s) to test (optional; otherwise tests all)"},
267     {NULL}
268 };
269 
270 enum {
271     D_MD2, D_MDC2, D_MD4, D_MD5, D_SHA1, D_RMD160,
272     D_SHA256, D_SHA512, D_WHIRLPOOL, D_HMAC,
273     D_CBC_DES, D_EDE3_DES, D_RC4, D_CBC_IDEA, D_CBC_SEED,
274     D_CBC_RC2, D_CBC_RC5, D_CBC_BF, D_CBC_CAST,
275     D_CBC_128_AES, D_CBC_192_AES, D_CBC_256_AES,
276     D_CBC_128_CML, D_CBC_192_CML, D_CBC_256_CML,
277     D_EVP, D_GHASH, D_RAND, D_EVP_CMAC, ALGOR_NUM
278 };
279 /* name of algorithms to test. MUST BE KEEP IN SYNC with above enum ! */
280 static const char *names[ALGOR_NUM] = {
281     "md2", "mdc2", "md4", "md5", "sha1", "rmd160",
282     "sha256", "sha512", "whirlpool", "hmac(md5)",
283     "des-cbc", "des-ede3", "rc4", "idea-cbc", "seed-cbc",
284     "rc2-cbc", "rc5-cbc", "blowfish", "cast-cbc",
285     "aes-128-cbc", "aes-192-cbc", "aes-256-cbc",
286     "camellia-128-cbc", "camellia-192-cbc", "camellia-256-cbc",
287     "evp", "ghash", "rand", "cmac"
288 };
289 
290 /* list of configured algorithm (remaining), with some few alias */
291 static const OPT_PAIR doit_choices[] = {
292     {"md2", D_MD2},
293     {"mdc2", D_MDC2},
294     {"md4", D_MD4},
295     {"md5", D_MD5},
296     {"hmac", D_HMAC},
297     {"sha1", D_SHA1},
298     {"sha256", D_SHA256},
299     {"sha512", D_SHA512},
300     {"whirlpool", D_WHIRLPOOL},
301     {"ripemd", D_RMD160},
302     {"rmd160", D_RMD160},
303     {"ripemd160", D_RMD160},
304     {"rc4", D_RC4},
305     {"des-cbc", D_CBC_DES},
306     {"des-ede3", D_EDE3_DES},
307     {"aes-128-cbc", D_CBC_128_AES},
308     {"aes-192-cbc", D_CBC_192_AES},
309     {"aes-256-cbc", D_CBC_256_AES},
310     {"camellia-128-cbc", D_CBC_128_CML},
311     {"camellia-192-cbc", D_CBC_192_CML},
312     {"camellia-256-cbc", D_CBC_256_CML},
313     {"rc2-cbc", D_CBC_RC2},
314     {"rc2", D_CBC_RC2},
315     {"rc5-cbc", D_CBC_RC5},
316     {"rc5", D_CBC_RC5},
317     {"idea-cbc", D_CBC_IDEA},
318     {"idea", D_CBC_IDEA},
319     {"seed-cbc", D_CBC_SEED},
320     {"seed", D_CBC_SEED},
321     {"bf-cbc", D_CBC_BF},
322     {"blowfish", D_CBC_BF},
323     {"bf", D_CBC_BF},
324     {"cast-cbc", D_CBC_CAST},
325     {"cast", D_CBC_CAST},
326     {"cast5", D_CBC_CAST},
327     {"ghash", D_GHASH},
328     {"rand", D_RAND}
329 };
330 
331 static double results[ALGOR_NUM][SIZE_NUM];
332 
333 enum { R_DSA_512, R_DSA_1024, R_DSA_2048, DSA_NUM };
334 static const OPT_PAIR dsa_choices[DSA_NUM] = {
335     {"dsa512", R_DSA_512},
336     {"dsa1024", R_DSA_1024},
337     {"dsa2048", R_DSA_2048}
338 };
339 static double dsa_results[DSA_NUM][2];  /* 2 ops: sign then verify */
340 
341 enum {
342     R_RSA_512, R_RSA_1024, R_RSA_2048, R_RSA_3072, R_RSA_4096, R_RSA_7680,
343     R_RSA_15360, RSA_NUM
344 };
345 static const OPT_PAIR rsa_choices[RSA_NUM] = {
346     {"rsa512", R_RSA_512},
347     {"rsa1024", R_RSA_1024},
348     {"rsa2048", R_RSA_2048},
349     {"rsa3072", R_RSA_3072},
350     {"rsa4096", R_RSA_4096},
351     {"rsa7680", R_RSA_7680},
352     {"rsa15360", R_RSA_15360}
353 };
354 
355 static double rsa_results[RSA_NUM][2];  /* 2 ops: sign then verify */
356 
357 #ifndef OPENSSL_NO_DH
358 enum ff_params_t {
359     R_FFDH_2048, R_FFDH_3072, R_FFDH_4096, R_FFDH_6144, R_FFDH_8192, FFDH_NUM
360 };
361 
362 static const OPT_PAIR ffdh_choices[FFDH_NUM] = {
363     {"ffdh2048", R_FFDH_2048},
364     {"ffdh3072", R_FFDH_3072},
365     {"ffdh4096", R_FFDH_4096},
366     {"ffdh6144", R_FFDH_6144},
367     {"ffdh8192", R_FFDH_8192},
368 };
369 
370 static double ffdh_results[FFDH_NUM][1];  /* 1 op: derivation */
371 #endif /* OPENSSL_NO_DH */
372 
373 enum ec_curves_t {
374     R_EC_P160, R_EC_P192, R_EC_P224, R_EC_P256, R_EC_P384, R_EC_P521,
375 #ifndef OPENSSL_NO_EC2M
376     R_EC_K163, R_EC_K233, R_EC_K283, R_EC_K409, R_EC_K571,
377     R_EC_B163, R_EC_B233, R_EC_B283, R_EC_B409, R_EC_B571,
378 #endif
379     R_EC_BRP256R1, R_EC_BRP256T1, R_EC_BRP384R1, R_EC_BRP384T1,
380     R_EC_BRP512R1, R_EC_BRP512T1, ECDSA_NUM
381 };
382 /* list of ecdsa curves */
383 static const OPT_PAIR ecdsa_choices[ECDSA_NUM] = {
384     {"ecdsap160", R_EC_P160},
385     {"ecdsap192", R_EC_P192},
386     {"ecdsap224", R_EC_P224},
387     {"ecdsap256", R_EC_P256},
388     {"ecdsap384", R_EC_P384},
389     {"ecdsap521", R_EC_P521},
390 #ifndef OPENSSL_NO_EC2M
391     {"ecdsak163", R_EC_K163},
392     {"ecdsak233", R_EC_K233},
393     {"ecdsak283", R_EC_K283},
394     {"ecdsak409", R_EC_K409},
395     {"ecdsak571", R_EC_K571},
396     {"ecdsab163", R_EC_B163},
397     {"ecdsab233", R_EC_B233},
398     {"ecdsab283", R_EC_B283},
399     {"ecdsab409", R_EC_B409},
400     {"ecdsab571", R_EC_B571},
401 #endif
402     {"ecdsabrp256r1", R_EC_BRP256R1},
403     {"ecdsabrp256t1", R_EC_BRP256T1},
404     {"ecdsabrp384r1", R_EC_BRP384R1},
405     {"ecdsabrp384t1", R_EC_BRP384T1},
406     {"ecdsabrp512r1", R_EC_BRP512R1},
407     {"ecdsabrp512t1", R_EC_BRP512T1}
408 };
409 enum { R_EC_X25519 = ECDSA_NUM, R_EC_X448, EC_NUM };
410 /* list of ecdh curves, extension of |ecdsa_choices| list above */
411 static const OPT_PAIR ecdh_choices[EC_NUM] = {
412     {"ecdhp160", R_EC_P160},
413     {"ecdhp192", R_EC_P192},
414     {"ecdhp224", R_EC_P224},
415     {"ecdhp256", R_EC_P256},
416     {"ecdhp384", R_EC_P384},
417     {"ecdhp521", R_EC_P521},
418 #ifndef OPENSSL_NO_EC2M
419     {"ecdhk163", R_EC_K163},
420     {"ecdhk233", R_EC_K233},
421     {"ecdhk283", R_EC_K283},
422     {"ecdhk409", R_EC_K409},
423     {"ecdhk571", R_EC_K571},
424     {"ecdhb163", R_EC_B163},
425     {"ecdhb233", R_EC_B233},
426     {"ecdhb283", R_EC_B283},
427     {"ecdhb409", R_EC_B409},
428     {"ecdhb571", R_EC_B571},
429 #endif
430     {"ecdhbrp256r1", R_EC_BRP256R1},
431     {"ecdhbrp256t1", R_EC_BRP256T1},
432     {"ecdhbrp384r1", R_EC_BRP384R1},
433     {"ecdhbrp384t1", R_EC_BRP384T1},
434     {"ecdhbrp512r1", R_EC_BRP512R1},
435     {"ecdhbrp512t1", R_EC_BRP512T1},
436     {"ecdhx25519", R_EC_X25519},
437     {"ecdhx448", R_EC_X448}
438 };
439 
440 static double ecdh_results[EC_NUM][1];      /* 1 op: derivation */
441 static double ecdsa_results[ECDSA_NUM][2];  /* 2 ops: sign then verify */
442 
443 enum { R_EC_Ed25519, R_EC_Ed448, EdDSA_NUM };
444 static const OPT_PAIR eddsa_choices[EdDSA_NUM] = {
445     {"ed25519", R_EC_Ed25519},
446     {"ed448", R_EC_Ed448}
447 
448 };
449 static double eddsa_results[EdDSA_NUM][2];    /* 2 ops: sign then verify */
450 
451 #ifndef OPENSSL_NO_SM2
452 enum { R_EC_CURVESM2, SM2_NUM };
453 static const OPT_PAIR sm2_choices[SM2_NUM] = {
454     {"curveSM2", R_EC_CURVESM2}
455 };
456 # define SM2_ID        "TLSv1.3+GM+Cipher+Suite"
457 # define SM2_ID_LEN    sizeof("TLSv1.3+GM+Cipher+Suite") - 1
458 static double sm2_results[SM2_NUM][2];    /* 2 ops: sign then verify */
459 #endif /* OPENSSL_NO_SM2 */
460 
461 #define COND(unused_cond) (run && count < INT_MAX)
462 #define COUNT(d) (count)
463 
464 typedef struct loopargs_st {
465     ASYNC_JOB *inprogress_job;
466     ASYNC_WAIT_CTX *wait_ctx;
467     unsigned char *buf;
468     unsigned char *buf2;
469     unsigned char *buf_malloc;
470     unsigned char *buf2_malloc;
471     unsigned char *key;
472     size_t buflen;
473     size_t sigsize;
474     EVP_PKEY_CTX *rsa_sign_ctx[RSA_NUM];
475     EVP_PKEY_CTX *rsa_verify_ctx[RSA_NUM];
476     EVP_PKEY_CTX *dsa_sign_ctx[DSA_NUM];
477     EVP_PKEY_CTX *dsa_verify_ctx[DSA_NUM];
478     EVP_PKEY_CTX *ecdsa_sign_ctx[ECDSA_NUM];
479     EVP_PKEY_CTX *ecdsa_verify_ctx[ECDSA_NUM];
480     EVP_PKEY_CTX *ecdh_ctx[EC_NUM];
481     EVP_MD_CTX *eddsa_ctx[EdDSA_NUM];
482     EVP_MD_CTX *eddsa_ctx2[EdDSA_NUM];
483 #ifndef OPENSSL_NO_SM2
484     EVP_MD_CTX *sm2_ctx[SM2_NUM];
485     EVP_MD_CTX *sm2_vfy_ctx[SM2_NUM];
486     EVP_PKEY *sm2_pkey[SM2_NUM];
487 #endif
488     unsigned char *secret_a;
489     unsigned char *secret_b;
490     size_t outlen[EC_NUM];
491 #ifndef OPENSSL_NO_DH
492     EVP_PKEY_CTX *ffdh_ctx[FFDH_NUM];
493     unsigned char *secret_ff_a;
494     unsigned char *secret_ff_b;
495 #endif
496     EVP_CIPHER_CTX *ctx;
497     EVP_MAC_CTX *mctx;
498 } loopargs_t;
499 static int run_benchmark(int async_jobs, int (*loop_function) (void *),
500                          loopargs_t * loopargs);
501 
502 static unsigned int testnum;
503 
504 /* Nb of iterations to do per algorithm and key-size */
505 static long c[ALGOR_NUM][SIZE_NUM];
506 
507 static char *evp_mac_mdname = "md5";
508 static char *evp_hmac_name = NULL;
509 static const char *evp_md_name = NULL;
510 static char *evp_mac_ciphername = "aes-128-cbc";
511 static char *evp_cmac_name = NULL;
512 
have_md(const char * name)513 static int have_md(const char *name)
514 {
515     int ret = 0;
516     EVP_MD *md = NULL;
517 
518     if (opt_md_silent(name, &md)) {
519         EVP_MD_CTX *ctx = EVP_MD_CTX_new();
520 
521         if (ctx != NULL && EVP_DigestInit(ctx, md) > 0)
522             ret = 1;
523         EVP_MD_CTX_free(ctx);
524         EVP_MD_free(md);
525     }
526     return ret;
527 }
528 
have_cipher(const char * name)529 static int have_cipher(const char *name)
530 {
531     int ret = 0;
532     EVP_CIPHER *cipher = NULL;
533 
534     if (opt_cipher_silent(name, &cipher)) {
535         EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
536 
537         if (ctx != NULL
538             && EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1) > 0)
539             ret = 1;
540         EVP_CIPHER_CTX_free(ctx);
541         EVP_CIPHER_free(cipher);
542     }
543     return ret;
544 }
545 
EVP_Digest_loop(const char * mdname,int algindex,void * args)546 static int EVP_Digest_loop(const char *mdname, int algindex, void *args)
547 {
548     loopargs_t *tempargs = *(loopargs_t **) args;
549     unsigned char *buf = tempargs->buf;
550     unsigned char digest[EVP_MAX_MD_SIZE];
551     int count;
552     EVP_MD *md = NULL;
553 
554     if (!opt_md_silent(mdname, &md))
555         return -1;
556     for (count = 0; COND(c[algindex][testnum]); count++) {
557         if (!EVP_Digest(buf, (size_t)lengths[testnum], digest, NULL, md,
558                         NULL)) {
559             count = -1;
560             break;
561         }
562     }
563     EVP_MD_free(md);
564     return count;
565 }
566 
EVP_Digest_md_loop(void * args)567 static int EVP_Digest_md_loop(void *args)
568 {
569     return EVP_Digest_loop(evp_md_name, D_EVP, args);
570 }
571 
EVP_Digest_MD2_loop(void * args)572 static int EVP_Digest_MD2_loop(void *args)
573 {
574     return EVP_Digest_loop("md2", D_MD2, args);
575 }
576 
EVP_Digest_MDC2_loop(void * args)577 static int EVP_Digest_MDC2_loop(void *args)
578 {
579     return EVP_Digest_loop("mdc2", D_MDC2, args);
580 }
581 
EVP_Digest_MD4_loop(void * args)582 static int EVP_Digest_MD4_loop(void *args)
583 {
584     return EVP_Digest_loop("md4", D_MD4, args);
585 }
586 
MD5_loop(void * args)587 static int MD5_loop(void *args)
588 {
589     return EVP_Digest_loop("md5", D_MD5, args);
590 }
591 
EVP_MAC_loop(int algindex,void * args)592 static int EVP_MAC_loop(int algindex, void *args)
593 {
594     loopargs_t *tempargs = *(loopargs_t **) args;
595     unsigned char *buf = tempargs->buf;
596     EVP_MAC_CTX *mctx = tempargs->mctx;
597     unsigned char mac[EVP_MAX_MD_SIZE];
598     int count;
599 
600     for (count = 0; COND(c[algindex][testnum]); count++) {
601         size_t outl;
602 
603         if (!EVP_MAC_init(mctx, NULL, 0, NULL)
604             || !EVP_MAC_update(mctx, buf, lengths[testnum])
605             || !EVP_MAC_final(mctx, mac, &outl, sizeof(mac)))
606             return -1;
607     }
608     return count;
609 }
610 
HMAC_loop(void * args)611 static int HMAC_loop(void *args)
612 {
613     return EVP_MAC_loop(D_HMAC, args);
614 }
615 
CMAC_loop(void * args)616 static int CMAC_loop(void *args)
617 {
618     return EVP_MAC_loop(D_EVP_CMAC, args);
619 }
620 
SHA1_loop(void * args)621 static int SHA1_loop(void *args)
622 {
623     return EVP_Digest_loop("sha1", D_SHA1, args);
624 }
625 
SHA256_loop(void * args)626 static int SHA256_loop(void *args)
627 {
628     return EVP_Digest_loop("sha256", D_SHA256, args);
629 }
630 
SHA512_loop(void * args)631 static int SHA512_loop(void *args)
632 {
633     return EVP_Digest_loop("sha512", D_SHA512, args);
634 }
635 
WHIRLPOOL_loop(void * args)636 static int WHIRLPOOL_loop(void *args)
637 {
638     return EVP_Digest_loop("whirlpool", D_WHIRLPOOL, args);
639 }
640 
EVP_Digest_RMD160_loop(void * args)641 static int EVP_Digest_RMD160_loop(void *args)
642 {
643     return EVP_Digest_loop("ripemd160", D_RMD160, args);
644 }
645 
646 static int algindex;
647 
EVP_Cipher_loop(void * args)648 static int EVP_Cipher_loop(void *args)
649 {
650     loopargs_t *tempargs = *(loopargs_t **) args;
651     unsigned char *buf = tempargs->buf;
652     int count;
653 
654     if (tempargs->ctx == NULL)
655         return -1;
656     for (count = 0; COND(c[algindex][testnum]); count++)
657         if (EVP_Cipher(tempargs->ctx, buf, buf, (size_t)lengths[testnum]) <= 0)
658             return -1;
659     return count;
660 }
661 
GHASH_loop(void * args)662 static int GHASH_loop(void *args)
663 {
664     loopargs_t *tempargs = *(loopargs_t **) args;
665     unsigned char *buf = tempargs->buf;
666     EVP_MAC_CTX *mctx = tempargs->mctx;
667     int count;
668 
669     /* just do the update in the loop to be comparable with 1.1.1 */
670     for (count = 0; COND(c[D_GHASH][testnum]); count++) {
671         if (!EVP_MAC_update(mctx, buf, lengths[testnum]))
672             return -1;
673     }
674     return count;
675 }
676 
677 #define MAX_BLOCK_SIZE 128
678 
679 static unsigned char iv[2 * MAX_BLOCK_SIZE / 8];
680 
init_evp_cipher_ctx(const char * ciphername,const unsigned char * key,int keylen)681 static EVP_CIPHER_CTX *init_evp_cipher_ctx(const char *ciphername,
682                                            const unsigned char *key,
683                                            int keylen)
684 {
685     EVP_CIPHER_CTX *ctx = NULL;
686     EVP_CIPHER *cipher = NULL;
687 
688     if (!opt_cipher_silent(ciphername, &cipher))
689         return NULL;
690 
691     if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
692         goto end;
693 
694     if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1)) {
695         EVP_CIPHER_CTX_free(ctx);
696         ctx = NULL;
697         goto end;
698     }
699 
700     if (EVP_CIPHER_CTX_set_key_length(ctx, keylen) <= 0) {
701         EVP_CIPHER_CTX_free(ctx);
702         ctx = NULL;
703         goto end;
704     }
705 
706     if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1)) {
707         EVP_CIPHER_CTX_free(ctx);
708         ctx = NULL;
709         goto end;
710     }
711 
712 end:
713     EVP_CIPHER_free(cipher);
714     return ctx;
715 }
716 
RAND_bytes_loop(void * args)717 static int RAND_bytes_loop(void *args)
718 {
719     loopargs_t *tempargs = *(loopargs_t **) args;
720     unsigned char *buf = tempargs->buf;
721     int count;
722 
723     for (count = 0; COND(c[D_RAND][testnum]); count++)
724         RAND_bytes(buf, lengths[testnum]);
725     return count;
726 }
727 
728 static int decrypt = 0;
EVP_Update_loop(void * args)729 static int EVP_Update_loop(void *args)
730 {
731     loopargs_t *tempargs = *(loopargs_t **) args;
732     unsigned char *buf = tempargs->buf;
733     EVP_CIPHER_CTX *ctx = tempargs->ctx;
734     int outl, count, rc;
735 
736     if (decrypt) {
737         for (count = 0; COND(c[D_EVP][testnum]); count++) {
738             rc = EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
739             if (rc != 1) {
740                 /* reset iv in case of counter overflow */
741                 (void)EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1);
742             }
743         }
744     } else {
745         for (count = 0; COND(c[D_EVP][testnum]); count++) {
746             rc = EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
747             if (rc != 1) {
748                 /* reset iv in case of counter overflow */
749                 (void)EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1);
750             }
751         }
752     }
753     if (decrypt)
754         EVP_DecryptFinal_ex(ctx, buf, &outl);
755     else
756         EVP_EncryptFinal_ex(ctx, buf, &outl);
757     return count;
758 }
759 
760 /*
761  * CCM does not support streaming. For the purpose of performance measurement,
762  * each message is encrypted using the same (key,iv)-pair. Do not use this
763  * code in your application.
764  */
EVP_Update_loop_ccm(void * args)765 static int EVP_Update_loop_ccm(void *args)
766 {
767     loopargs_t *tempargs = *(loopargs_t **) args;
768     unsigned char *buf = tempargs->buf;
769     EVP_CIPHER_CTX *ctx = tempargs->ctx;
770     int outl, count;
771     unsigned char tag[12];
772 
773     if (decrypt) {
774         for (count = 0; COND(c[D_EVP][testnum]); count++) {
775             (void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(tag),
776                                       tag);
777             /* reset iv */
778             (void)EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv);
779             /* counter is reset on every update */
780             (void)EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
781         }
782     } else {
783         for (count = 0; COND(c[D_EVP][testnum]); count++) {
784             /* restore iv length field */
785             (void)EVP_EncryptUpdate(ctx, NULL, &outl, NULL, lengths[testnum]);
786             /* counter is reset on every update */
787             (void)EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
788         }
789     }
790     if (decrypt)
791         (void)EVP_DecryptFinal_ex(ctx, buf, &outl);
792     else
793         (void)EVP_EncryptFinal_ex(ctx, buf, &outl);
794     return count;
795 }
796 
797 /*
798  * To make AEAD benchmarking more relevant perform TLS-like operations,
799  * 13-byte AAD followed by payload. But don't use TLS-formatted AAD, as
800  * payload length is not actually limited by 16KB...
801  */
EVP_Update_loop_aead(void * args)802 static int EVP_Update_loop_aead(void *args)
803 {
804     loopargs_t *tempargs = *(loopargs_t **) args;
805     unsigned char *buf = tempargs->buf;
806     EVP_CIPHER_CTX *ctx = tempargs->ctx;
807     int outl, count;
808     unsigned char aad[13] = { 0xcc };
809     unsigned char faketag[16] = { 0xcc };
810 
811     if (decrypt) {
812         for (count = 0; COND(c[D_EVP][testnum]); count++) {
813             (void)EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv);
814             (void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
815                                       sizeof(faketag), faketag);
816             (void)EVP_DecryptUpdate(ctx, NULL, &outl, aad, sizeof(aad));
817             (void)EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
818             (void)EVP_DecryptFinal_ex(ctx, buf + outl, &outl);
819         }
820     } else {
821         for (count = 0; COND(c[D_EVP][testnum]); count++) {
822             (void)EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv);
823             (void)EVP_EncryptUpdate(ctx, NULL, &outl, aad, sizeof(aad));
824             (void)EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
825             (void)EVP_EncryptFinal_ex(ctx, buf + outl, &outl);
826         }
827     }
828     return count;
829 }
830 
831 static long rsa_c[RSA_NUM][2];  /* # RSA iteration test */
832 
RSA_sign_loop(void * args)833 static int RSA_sign_loop(void *args)
834 {
835     loopargs_t *tempargs = *(loopargs_t **) args;
836     unsigned char *buf = tempargs->buf;
837     unsigned char *buf2 = tempargs->buf2;
838     size_t *rsa_num = &tempargs->sigsize;
839     EVP_PKEY_CTX **rsa_sign_ctx = tempargs->rsa_sign_ctx;
840     int ret, count;
841 
842     for (count = 0; COND(rsa_c[testnum][0]); count++) {
843         *rsa_num = tempargs->buflen;
844         ret = EVP_PKEY_sign(rsa_sign_ctx[testnum], buf2, rsa_num, buf, 36);
845         if (ret <= 0) {
846             BIO_printf(bio_err, "RSA sign failure\n");
847             ERR_print_errors(bio_err);
848             count = -1;
849             break;
850         }
851     }
852     return count;
853 }
854 
RSA_verify_loop(void * args)855 static int RSA_verify_loop(void *args)
856 {
857     loopargs_t *tempargs = *(loopargs_t **) args;
858     unsigned char *buf = tempargs->buf;
859     unsigned char *buf2 = tempargs->buf2;
860     size_t rsa_num = tempargs->sigsize;
861     EVP_PKEY_CTX **rsa_verify_ctx = tempargs->rsa_verify_ctx;
862     int ret, count;
863 
864     for (count = 0; COND(rsa_c[testnum][1]); count++) {
865         ret = EVP_PKEY_verify(rsa_verify_ctx[testnum], buf2, rsa_num, buf, 36);
866         if (ret <= 0) {
867             BIO_printf(bio_err, "RSA verify failure\n");
868             ERR_print_errors(bio_err);
869             count = -1;
870             break;
871         }
872     }
873     return count;
874 }
875 
876 #ifndef OPENSSL_NO_DH
877 static long ffdh_c[FFDH_NUM][1];
878 
FFDH_derive_key_loop(void * args)879 static int FFDH_derive_key_loop(void *args)
880 {
881     loopargs_t *tempargs = *(loopargs_t **) args;
882     EVP_PKEY_CTX *ffdh_ctx = tempargs->ffdh_ctx[testnum];
883     unsigned char *derived_secret = tempargs->secret_ff_a;
884     int count;
885 
886     for (count = 0; COND(ffdh_c[testnum][0]); count++) {
887         /* outlen can be overwritten with a too small value (no padding used) */
888         size_t outlen = MAX_FFDH_SIZE;
889 
890         EVP_PKEY_derive(ffdh_ctx, derived_secret, &outlen);
891     }
892     return count;
893 }
894 #endif /* OPENSSL_NO_DH */
895 
896 static long dsa_c[DSA_NUM][2];
DSA_sign_loop(void * args)897 static int DSA_sign_loop(void *args)
898 {
899     loopargs_t *tempargs = *(loopargs_t **) args;
900     unsigned char *buf = tempargs->buf;
901     unsigned char *buf2 = tempargs->buf2;
902     size_t *dsa_num = &tempargs->sigsize;
903     EVP_PKEY_CTX **dsa_sign_ctx = tempargs->dsa_sign_ctx;
904     int ret, count;
905 
906     for (count = 0; COND(dsa_c[testnum][0]); count++) {
907         *dsa_num = tempargs->buflen;
908         ret = EVP_PKEY_sign(dsa_sign_ctx[testnum], buf2, dsa_num, buf, 20);
909         if (ret <= 0) {
910             BIO_printf(bio_err, "DSA sign failure\n");
911             ERR_print_errors(bio_err);
912             count = -1;
913             break;
914         }
915     }
916     return count;
917 }
918 
DSA_verify_loop(void * args)919 static int DSA_verify_loop(void *args)
920 {
921     loopargs_t *tempargs = *(loopargs_t **) args;
922     unsigned char *buf = tempargs->buf;
923     unsigned char *buf2 = tempargs->buf2;
924     size_t dsa_num = tempargs->sigsize;
925     EVP_PKEY_CTX **dsa_verify_ctx = tempargs->dsa_verify_ctx;
926     int ret, count;
927 
928     for (count = 0; COND(dsa_c[testnum][1]); count++) {
929         ret = EVP_PKEY_verify(dsa_verify_ctx[testnum], buf2, dsa_num, buf, 20);
930         if (ret <= 0) {
931             BIO_printf(bio_err, "DSA verify failure\n");
932             ERR_print_errors(bio_err);
933             count = -1;
934             break;
935         }
936     }
937     return count;
938 }
939 
940 static long ecdsa_c[ECDSA_NUM][2];
ECDSA_sign_loop(void * args)941 static int ECDSA_sign_loop(void *args)
942 {
943     loopargs_t *tempargs = *(loopargs_t **) args;
944     unsigned char *buf = tempargs->buf;
945     unsigned char *buf2 = tempargs->buf2;
946     size_t *ecdsa_num = &tempargs->sigsize;
947     EVP_PKEY_CTX **ecdsa_sign_ctx = tempargs->ecdsa_sign_ctx;
948     int ret, count;
949 
950     for (count = 0; COND(ecdsa_c[testnum][0]); count++) {
951         *ecdsa_num = tempargs->buflen;
952         ret = EVP_PKEY_sign(ecdsa_sign_ctx[testnum], buf2, ecdsa_num, buf, 20);
953         if (ret <= 0) {
954             BIO_printf(bio_err, "ECDSA sign failure\n");
955             ERR_print_errors(bio_err);
956             count = -1;
957             break;
958         }
959     }
960     return count;
961 }
962 
ECDSA_verify_loop(void * args)963 static int ECDSA_verify_loop(void *args)
964 {
965     loopargs_t *tempargs = *(loopargs_t **) args;
966     unsigned char *buf = tempargs->buf;
967     unsigned char *buf2 = tempargs->buf2;
968     size_t ecdsa_num = tempargs->sigsize;
969     EVP_PKEY_CTX **ecdsa_verify_ctx = tempargs->ecdsa_verify_ctx;
970     int ret, count;
971 
972     for (count = 0; COND(ecdsa_c[testnum][1]); count++) {
973         ret = EVP_PKEY_verify(ecdsa_verify_ctx[testnum], buf2, ecdsa_num,
974                               buf, 20);
975         if (ret <= 0) {
976             BIO_printf(bio_err, "ECDSA verify failure\n");
977             ERR_print_errors(bio_err);
978             count = -1;
979             break;
980         }
981     }
982     return count;
983 }
984 
985 /* ******************************************************************** */
986 static long ecdh_c[EC_NUM][1];
987 
ECDH_EVP_derive_key_loop(void * args)988 static int ECDH_EVP_derive_key_loop(void *args)
989 {
990     loopargs_t *tempargs = *(loopargs_t **) args;
991     EVP_PKEY_CTX *ctx = tempargs->ecdh_ctx[testnum];
992     unsigned char *derived_secret = tempargs->secret_a;
993     int count;
994     size_t *outlen = &(tempargs->outlen[testnum]);
995 
996     for (count = 0; COND(ecdh_c[testnum][0]); count++)
997         EVP_PKEY_derive(ctx, derived_secret, outlen);
998 
999     return count;
1000 }
1001 
1002 static long eddsa_c[EdDSA_NUM][2];
EdDSA_sign_loop(void * args)1003 static int EdDSA_sign_loop(void *args)
1004 {
1005     loopargs_t *tempargs = *(loopargs_t **) args;
1006     unsigned char *buf = tempargs->buf;
1007     EVP_MD_CTX **edctx = tempargs->eddsa_ctx;
1008     unsigned char *eddsasig = tempargs->buf2;
1009     size_t *eddsasigsize = &tempargs->sigsize;
1010     int ret, count;
1011 
1012     for (count = 0; COND(eddsa_c[testnum][0]); count++) {
1013         ret = EVP_DigestSign(edctx[testnum], eddsasig, eddsasigsize, buf, 20);
1014         if (ret == 0) {
1015             BIO_printf(bio_err, "EdDSA sign failure\n");
1016             ERR_print_errors(bio_err);
1017             count = -1;
1018             break;
1019         }
1020     }
1021     return count;
1022 }
1023 
EdDSA_verify_loop(void * args)1024 static int EdDSA_verify_loop(void *args)
1025 {
1026     loopargs_t *tempargs = *(loopargs_t **) args;
1027     unsigned char *buf = tempargs->buf;
1028     EVP_MD_CTX **edctx = tempargs->eddsa_ctx2;
1029     unsigned char *eddsasig = tempargs->buf2;
1030     size_t eddsasigsize = tempargs->sigsize;
1031     int ret, count;
1032 
1033     for (count = 0; COND(eddsa_c[testnum][1]); count++) {
1034         ret = EVP_DigestVerify(edctx[testnum], eddsasig, eddsasigsize, buf, 20);
1035         if (ret != 1) {
1036             BIO_printf(bio_err, "EdDSA verify failure\n");
1037             ERR_print_errors(bio_err);
1038             count = -1;
1039             break;
1040         }
1041     }
1042     return count;
1043 }
1044 
1045 #ifndef OPENSSL_NO_SM2
1046 static long sm2_c[SM2_NUM][2];
SM2_sign_loop(void * args)1047 static int SM2_sign_loop(void *args)
1048 {
1049     loopargs_t *tempargs = *(loopargs_t **) args;
1050     unsigned char *buf = tempargs->buf;
1051     EVP_MD_CTX **sm2ctx = tempargs->sm2_ctx;
1052     unsigned char *sm2sig = tempargs->buf2;
1053     size_t sm2sigsize;
1054     int ret, count;
1055     EVP_PKEY **sm2_pkey = tempargs->sm2_pkey;
1056     const size_t max_size = EVP_PKEY_get_size(sm2_pkey[testnum]);
1057 
1058     for (count = 0; COND(sm2_c[testnum][0]); count++) {
1059         sm2sigsize = max_size;
1060 
1061         if (!EVP_DigestSignInit(sm2ctx[testnum], NULL, EVP_sm3(),
1062                                 NULL, sm2_pkey[testnum])) {
1063             BIO_printf(bio_err, "SM2 init sign failure\n");
1064             ERR_print_errors(bio_err);
1065             count = -1;
1066             break;
1067         }
1068         ret = EVP_DigestSign(sm2ctx[testnum], sm2sig, &sm2sigsize,
1069                              buf, 20);
1070         if (ret == 0) {
1071             BIO_printf(bio_err, "SM2 sign failure\n");
1072             ERR_print_errors(bio_err);
1073             count = -1;
1074             break;
1075         }
1076         /* update the latest returned size and always use the fixed buffer size */
1077         tempargs->sigsize = sm2sigsize;
1078     }
1079 
1080     return count;
1081 }
1082 
SM2_verify_loop(void * args)1083 static int SM2_verify_loop(void *args)
1084 {
1085     loopargs_t *tempargs = *(loopargs_t **) args;
1086     unsigned char *buf = tempargs->buf;
1087     EVP_MD_CTX **sm2ctx = tempargs->sm2_vfy_ctx;
1088     unsigned char *sm2sig = tempargs->buf2;
1089     size_t sm2sigsize = tempargs->sigsize;
1090     int ret, count;
1091     EVP_PKEY **sm2_pkey = tempargs->sm2_pkey;
1092 
1093     for (count = 0; COND(sm2_c[testnum][1]); count++) {
1094         if (!EVP_DigestVerifyInit(sm2ctx[testnum], NULL, EVP_sm3(),
1095                                   NULL, sm2_pkey[testnum])) {
1096             BIO_printf(bio_err, "SM2 verify init failure\n");
1097             ERR_print_errors(bio_err);
1098             count = -1;
1099             break;
1100         }
1101         ret = EVP_DigestVerify(sm2ctx[testnum], sm2sig, sm2sigsize,
1102                                buf, 20);
1103         if (ret != 1) {
1104             BIO_printf(bio_err, "SM2 verify failure\n");
1105             ERR_print_errors(bio_err);
1106             count = -1;
1107             break;
1108         }
1109     }
1110     return count;
1111 }
1112 #endif                         /* OPENSSL_NO_SM2 */
1113 
run_benchmark(int async_jobs,int (* loop_function)(void *),loopargs_t * loopargs)1114 static int run_benchmark(int async_jobs,
1115                          int (*loop_function) (void *), loopargs_t * loopargs)
1116 {
1117     int job_op_count = 0;
1118     int total_op_count = 0;
1119     int num_inprogress = 0;
1120     int error = 0, i = 0, ret = 0;
1121     OSSL_ASYNC_FD job_fd = 0;
1122     size_t num_job_fds = 0;
1123 
1124     if (async_jobs == 0) {
1125         return loop_function((void *)&loopargs);
1126     }
1127 
1128     for (i = 0; i < async_jobs && !error; i++) {
1129         loopargs_t *looparg_item = loopargs + i;
1130 
1131         /* Copy pointer content (looparg_t item address) into async context */
1132         ret = ASYNC_start_job(&loopargs[i].inprogress_job, loopargs[i].wait_ctx,
1133                               &job_op_count, loop_function,
1134                               (void *)&looparg_item, sizeof(looparg_item));
1135         switch (ret) {
1136         case ASYNC_PAUSE:
1137             ++num_inprogress;
1138             break;
1139         case ASYNC_FINISH:
1140             if (job_op_count == -1) {
1141                 error = 1;
1142             } else {
1143                 total_op_count += job_op_count;
1144             }
1145             break;
1146         case ASYNC_NO_JOBS:
1147         case ASYNC_ERR:
1148             BIO_printf(bio_err, "Failure in the job\n");
1149             ERR_print_errors(bio_err);
1150             error = 1;
1151             break;
1152         }
1153     }
1154 
1155     while (num_inprogress > 0) {
1156 #if defined(OPENSSL_SYS_WINDOWS)
1157         DWORD avail = 0;
1158 #elif defined(OPENSSL_SYS_UNIX)
1159         int select_result = 0;
1160         OSSL_ASYNC_FD max_fd = 0;
1161         fd_set waitfdset;
1162 
1163         FD_ZERO(&waitfdset);
1164 
1165         for (i = 0; i < async_jobs && num_inprogress > 0; i++) {
1166             if (loopargs[i].inprogress_job == NULL)
1167                 continue;
1168 
1169             if (!ASYNC_WAIT_CTX_get_all_fds
1170                 (loopargs[i].wait_ctx, NULL, &num_job_fds)
1171                 || num_job_fds > 1) {
1172                 BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n");
1173                 ERR_print_errors(bio_err);
1174                 error = 1;
1175                 break;
1176             }
1177             ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd,
1178                                        &num_job_fds);
1179             FD_SET(job_fd, &waitfdset);
1180             if (job_fd > max_fd)
1181                 max_fd = job_fd;
1182         }
1183 
1184         if (max_fd >= (OSSL_ASYNC_FD)FD_SETSIZE) {
1185             BIO_printf(bio_err,
1186                        "Error: max_fd (%d) must be smaller than FD_SETSIZE (%d). "
1187                        "Decrease the value of async_jobs\n",
1188                        max_fd, FD_SETSIZE);
1189             ERR_print_errors(bio_err);
1190             error = 1;
1191             break;
1192         }
1193 
1194         select_result = select(max_fd + 1, &waitfdset, NULL, NULL, NULL);
1195         if (select_result == -1 && errno == EINTR)
1196             continue;
1197 
1198         if (select_result == -1) {
1199             BIO_printf(bio_err, "Failure in the select\n");
1200             ERR_print_errors(bio_err);
1201             error = 1;
1202             break;
1203         }
1204 
1205         if (select_result == 0)
1206             continue;
1207 #endif
1208 
1209         for (i = 0; i < async_jobs; i++) {
1210             if (loopargs[i].inprogress_job == NULL)
1211                 continue;
1212 
1213             if (!ASYNC_WAIT_CTX_get_all_fds
1214                 (loopargs[i].wait_ctx, NULL, &num_job_fds)
1215                 || num_job_fds > 1) {
1216                 BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n");
1217                 ERR_print_errors(bio_err);
1218                 error = 1;
1219                 break;
1220             }
1221             ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd,
1222                                        &num_job_fds);
1223 
1224 #if defined(OPENSSL_SYS_UNIX)
1225             if (num_job_fds == 1 && !FD_ISSET(job_fd, &waitfdset))
1226                 continue;
1227 #elif defined(OPENSSL_SYS_WINDOWS)
1228             if (num_job_fds == 1
1229                 && !PeekNamedPipe(job_fd, NULL, 0, NULL, &avail, NULL)
1230                 && avail > 0)
1231                 continue;
1232 #endif
1233 
1234             ret = ASYNC_start_job(&loopargs[i].inprogress_job,
1235                                   loopargs[i].wait_ctx, &job_op_count,
1236                                   loop_function, (void *)(loopargs + i),
1237                                   sizeof(loopargs_t));
1238             switch (ret) {
1239             case ASYNC_PAUSE:
1240                 break;
1241             case ASYNC_FINISH:
1242                 if (job_op_count == -1) {
1243                     error = 1;
1244                 } else {
1245                     total_op_count += job_op_count;
1246                 }
1247                 --num_inprogress;
1248                 loopargs[i].inprogress_job = NULL;
1249                 break;
1250             case ASYNC_NO_JOBS:
1251             case ASYNC_ERR:
1252                 --num_inprogress;
1253                 loopargs[i].inprogress_job = NULL;
1254                 BIO_printf(bio_err, "Failure in the job\n");
1255                 ERR_print_errors(bio_err);
1256                 error = 1;
1257                 break;
1258             }
1259         }
1260     }
1261 
1262     return error ? -1 : total_op_count;
1263 }
1264 
1265 typedef struct ec_curve_st {
1266     const char *name;
1267     unsigned int nid;
1268     unsigned int bits;
1269     size_t sigsize; /* only used for EdDSA curves */
1270 } EC_CURVE;
1271 
get_ecdsa(const EC_CURVE * curve)1272 static EVP_PKEY *get_ecdsa(const EC_CURVE *curve)
1273 {
1274     EVP_PKEY_CTX *kctx = NULL;
1275     EVP_PKEY *key = NULL;
1276 
1277     /* Ensure that the error queue is empty */
1278     if (ERR_peek_error()) {
1279         BIO_printf(bio_err,
1280                    "WARNING: the error queue contains previous unhandled errors.\n");
1281         ERR_print_errors(bio_err);
1282     }
1283 
1284     /*
1285      * Let's try to create a ctx directly from the NID: this works for
1286      * curves like Curve25519 that are not implemented through the low
1287      * level EC interface.
1288      * If this fails we try creating a EVP_PKEY_EC generic param ctx,
1289      * then we set the curve by NID before deriving the actual keygen
1290      * ctx for that specific curve.
1291      */
1292     kctx = EVP_PKEY_CTX_new_id(curve->nid, NULL);
1293     if (kctx == NULL) {
1294         EVP_PKEY_CTX *pctx = NULL;
1295         EVP_PKEY *params = NULL;
1296         /*
1297          * If we reach this code EVP_PKEY_CTX_new_id() failed and a
1298          * "int_ctx_new:unsupported algorithm" error was added to the
1299          * error queue.
1300          * We remove it from the error queue as we are handling it.
1301          */
1302         unsigned long error = ERR_peek_error();
1303 
1304         if (error == ERR_peek_last_error() /* oldest and latest errors match */
1305             /* check that the error origin matches */
1306             && ERR_GET_LIB(error) == ERR_LIB_EVP
1307             && (ERR_GET_REASON(error) == EVP_R_UNSUPPORTED_ALGORITHM
1308                 || ERR_GET_REASON(error) == ERR_R_UNSUPPORTED))
1309             ERR_get_error(); /* pop error from queue */
1310         if (ERR_peek_error()) {
1311             BIO_printf(bio_err,
1312                        "Unhandled error in the error queue during EC key setup.\n");
1313             ERR_print_errors(bio_err);
1314             return NULL;
1315         }
1316 
1317         /* Create the context for parameter generation */
1318         if ((pctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) == NULL
1319             || EVP_PKEY_paramgen_init(pctx) <= 0
1320             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
1321                                                       curve->nid) <= 0
1322             || EVP_PKEY_paramgen(pctx, &params) <= 0) {
1323             BIO_printf(bio_err, "EC params init failure.\n");
1324             ERR_print_errors(bio_err);
1325             EVP_PKEY_CTX_free(pctx);
1326             return NULL;
1327         }
1328         EVP_PKEY_CTX_free(pctx);
1329 
1330         /* Create the context for the key generation */
1331         kctx = EVP_PKEY_CTX_new(params, NULL);
1332         EVP_PKEY_free(params);
1333     }
1334     if (kctx == NULL
1335         || EVP_PKEY_keygen_init(kctx) <= 0
1336         || EVP_PKEY_keygen(kctx, &key) <= 0) {
1337         BIO_printf(bio_err, "EC key generation failure.\n");
1338         ERR_print_errors(bio_err);
1339         key = NULL;
1340     }
1341     EVP_PKEY_CTX_free(kctx);
1342     return key;
1343 }
1344 
1345 #define stop_it(do_it, test_num)\
1346     memset(do_it + test_num, 0, OSSL_NELEM(do_it) - test_num);
1347 
speed_main(int argc,char ** argv)1348 int speed_main(int argc, char **argv)
1349 {
1350     CONF *conf = NULL;
1351     ENGINE *e = NULL;
1352     loopargs_t *loopargs = NULL;
1353     const char *prog;
1354     const char *engine_id = NULL;
1355     EVP_CIPHER *evp_cipher = NULL;
1356     EVP_MAC *mac = NULL;
1357     double d = 0.0;
1358     OPTION_CHOICE o;
1359     int async_init = 0, multiblock = 0, pr_header = 0;
1360     uint8_t doit[ALGOR_NUM] = { 0 };
1361     int ret = 1, misalign = 0, lengths_single = 0, aead = 0;
1362     long count = 0;
1363     unsigned int size_num = SIZE_NUM;
1364     unsigned int i, k, loopargs_len = 0, async_jobs = 0;
1365     int keylen;
1366     int buflen;
1367     BIGNUM *bn = NULL;
1368     EVP_PKEY_CTX *genctx = NULL;
1369 #ifndef NO_FORK
1370     int multi = 0;
1371 #endif
1372     long op_count = 1;
1373     openssl_speed_sec_t seconds = { SECONDS, RSA_SECONDS, DSA_SECONDS,
1374                                     ECDSA_SECONDS, ECDH_SECONDS,
1375                                     EdDSA_SECONDS, SM2_SECONDS,
1376                                     FFDH_SECONDS };
1377 
1378     static const unsigned char key32[32] = {
1379         0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
1380         0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
1381         0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
1382         0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56
1383     };
1384     static const unsigned char deskey[] = {
1385         0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, /* key1 */
1386         0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, /* key2 */
1387         0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34  /* key3 */
1388     };
1389     static const struct {
1390         const unsigned char *data;
1391         unsigned int length;
1392         unsigned int bits;
1393     } rsa_keys[] = {
1394         {   test512,   sizeof(test512),   512 },
1395         {  test1024,  sizeof(test1024),  1024 },
1396         {  test2048,  sizeof(test2048),  2048 },
1397         {  test3072,  sizeof(test3072),  3072 },
1398         {  test4096,  sizeof(test4096),  4096 },
1399         {  test7680,  sizeof(test7680),  7680 },
1400         { test15360, sizeof(test15360), 15360 }
1401     };
1402     uint8_t rsa_doit[RSA_NUM] = { 0 };
1403     int primes = RSA_DEFAULT_PRIME_NUM;
1404 #ifndef OPENSSL_NO_DH
1405     typedef struct ffdh_params_st {
1406         const char *name;
1407         unsigned int nid;
1408         unsigned int bits;
1409     } FFDH_PARAMS;
1410 
1411     static const FFDH_PARAMS ffdh_params[FFDH_NUM] = {
1412         {"ffdh2048", NID_ffdhe2048, 2048},
1413         {"ffdh3072", NID_ffdhe3072, 3072},
1414         {"ffdh4096", NID_ffdhe4096, 4096},
1415         {"ffdh6144", NID_ffdhe6144, 6144},
1416         {"ffdh8192", NID_ffdhe8192, 8192}
1417     };
1418     uint8_t ffdh_doit[FFDH_NUM] = { 0 };
1419 
1420 #endif /* OPENSSL_NO_DH */
1421     static const unsigned int dsa_bits[DSA_NUM] = { 512, 1024, 2048 };
1422     uint8_t dsa_doit[DSA_NUM] = { 0 };
1423     /*
1424      * We only test over the following curves as they are representative, To
1425      * add tests over more curves, simply add the curve NID and curve name to
1426      * the following arrays and increase the |ecdh_choices| and |ecdsa_choices|
1427      * lists accordingly.
1428      */
1429     static const EC_CURVE ec_curves[EC_NUM] = {
1430         /* Prime Curves */
1431         {"secp160r1", NID_secp160r1, 160},
1432         {"nistp192", NID_X9_62_prime192v1, 192},
1433         {"nistp224", NID_secp224r1, 224},
1434         {"nistp256", NID_X9_62_prime256v1, 256},
1435         {"nistp384", NID_secp384r1, 384},
1436         {"nistp521", NID_secp521r1, 521},
1437 #ifndef OPENSSL_NO_EC2M
1438         /* Binary Curves */
1439         {"nistk163", NID_sect163k1, 163},
1440         {"nistk233", NID_sect233k1, 233},
1441         {"nistk283", NID_sect283k1, 283},
1442         {"nistk409", NID_sect409k1, 409},
1443         {"nistk571", NID_sect571k1, 571},
1444         {"nistb163", NID_sect163r2, 163},
1445         {"nistb233", NID_sect233r1, 233},
1446         {"nistb283", NID_sect283r1, 283},
1447         {"nistb409", NID_sect409r1, 409},
1448         {"nistb571", NID_sect571r1, 571},
1449 #endif
1450         {"brainpoolP256r1", NID_brainpoolP256r1, 256},
1451         {"brainpoolP256t1", NID_brainpoolP256t1, 256},
1452         {"brainpoolP384r1", NID_brainpoolP384r1, 384},
1453         {"brainpoolP384t1", NID_brainpoolP384t1, 384},
1454         {"brainpoolP512r1", NID_brainpoolP512r1, 512},
1455         {"brainpoolP512t1", NID_brainpoolP512t1, 512},
1456         /* Other and ECDH only ones */
1457         {"X25519", NID_X25519, 253},
1458         {"X448", NID_X448, 448}
1459     };
1460     static const EC_CURVE ed_curves[EdDSA_NUM] = {
1461         /* EdDSA */
1462         {"Ed25519", NID_ED25519, 253, 64},
1463         {"Ed448", NID_ED448, 456, 114}
1464     };
1465 #ifndef OPENSSL_NO_SM2
1466     static const EC_CURVE sm2_curves[SM2_NUM] = {
1467         /* SM2 */
1468         {"CurveSM2", NID_sm2, 256}
1469     };
1470     uint8_t sm2_doit[SM2_NUM] = { 0 };
1471 #endif
1472     uint8_t ecdsa_doit[ECDSA_NUM] = { 0 };
1473     uint8_t ecdh_doit[EC_NUM] = { 0 };
1474     uint8_t eddsa_doit[EdDSA_NUM] = { 0 };
1475 
1476     /* checks declared curves against choices list. */
1477     OPENSSL_assert(ed_curves[EdDSA_NUM - 1].nid == NID_ED448);
1478     OPENSSL_assert(strcmp(eddsa_choices[EdDSA_NUM - 1].name, "ed448") == 0);
1479 
1480     OPENSSL_assert(ec_curves[EC_NUM - 1].nid == NID_X448);
1481     OPENSSL_assert(strcmp(ecdh_choices[EC_NUM - 1].name, "ecdhx448") == 0);
1482 
1483     OPENSSL_assert(ec_curves[ECDSA_NUM - 1].nid == NID_brainpoolP512t1);
1484     OPENSSL_assert(strcmp(ecdsa_choices[ECDSA_NUM - 1].name, "ecdsabrp512t1") == 0);
1485 
1486 #ifndef OPENSSL_NO_SM2
1487     OPENSSL_assert(sm2_curves[SM2_NUM - 1].nid == NID_sm2);
1488     OPENSSL_assert(strcmp(sm2_choices[SM2_NUM - 1].name, "curveSM2") == 0);
1489 #endif
1490 
1491     prog = opt_init(argc, argv, speed_options);
1492     while ((o = opt_next()) != OPT_EOF) {
1493         switch (o) {
1494         case OPT_EOF:
1495         case OPT_ERR:
1496  opterr:
1497             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1498             goto end;
1499         case OPT_HELP:
1500             opt_help(speed_options);
1501             ret = 0;
1502             goto end;
1503         case OPT_ELAPSED:
1504             usertime = 0;
1505             break;
1506         case OPT_EVP:
1507             if (doit[D_EVP]) {
1508                 BIO_printf(bio_err, "%s: -evp option cannot be used more than once\n", prog);
1509                 goto opterr;
1510             }
1511             ERR_set_mark();
1512             if (!opt_cipher_silent(opt_arg(), &evp_cipher)) {
1513                 if (have_md(opt_arg()))
1514                     evp_md_name = opt_arg();
1515             }
1516             if (evp_cipher == NULL && evp_md_name == NULL) {
1517                 ERR_clear_last_mark();
1518                 BIO_printf(bio_err,
1519                            "%s: %s is an unknown cipher or digest\n",
1520                            prog, opt_arg());
1521                 goto end;
1522             }
1523             ERR_pop_to_mark();
1524             doit[D_EVP] = 1;
1525             break;
1526         case OPT_HMAC:
1527             if (!have_md(opt_arg())) {
1528                 BIO_printf(bio_err, "%s: %s is an unknown digest\n",
1529                            prog, opt_arg());
1530                 goto end;
1531             }
1532             evp_mac_mdname = opt_arg();
1533             doit[D_HMAC] = 1;
1534             break;
1535         case OPT_CMAC:
1536             if (!have_cipher(opt_arg())) {
1537                 BIO_printf(bio_err, "%s: %s is an unknown cipher\n",
1538                            prog, opt_arg());
1539                 goto end;
1540             }
1541             evp_mac_ciphername = opt_arg();
1542             doit[D_EVP_CMAC] = 1;
1543             break;
1544         case OPT_DECRYPT:
1545             decrypt = 1;
1546             break;
1547         case OPT_ENGINE:
1548             /*
1549              * In a forked execution, an engine might need to be
1550              * initialised by each child process, not by the parent.
1551              * So store the name here and run setup_engine() later on.
1552              */
1553             engine_id = opt_arg();
1554             break;
1555         case OPT_MULTI:
1556 #ifndef NO_FORK
1557             multi = opt_int_arg();
1558             if ((size_t)multi >= SIZE_MAX / sizeof(int)) {
1559                 BIO_printf(bio_err, "%s: multi argument too large\n", prog);
1560                 return 0;
1561             }
1562 #endif
1563             break;
1564         case OPT_ASYNCJOBS:
1565 #ifndef OPENSSL_NO_ASYNC
1566             async_jobs = opt_int_arg();
1567             if (!ASYNC_is_capable()) {
1568                 BIO_printf(bio_err,
1569                            "%s: async_jobs specified but async not supported\n",
1570                            prog);
1571                 goto opterr;
1572             }
1573             if (async_jobs > 99999) {
1574                 BIO_printf(bio_err, "%s: too many async_jobs\n", prog);
1575                 goto opterr;
1576             }
1577 #endif
1578             break;
1579         case OPT_MISALIGN:
1580             misalign = opt_int_arg();
1581             if (misalign > MISALIGN) {
1582                 BIO_printf(bio_err,
1583                            "%s: Maximum offset is %d\n", prog, MISALIGN);
1584                 goto opterr;
1585             }
1586             break;
1587         case OPT_MR:
1588             mr = 1;
1589             break;
1590         case OPT_MB:
1591             multiblock = 1;
1592 #ifdef OPENSSL_NO_MULTIBLOCK
1593             BIO_printf(bio_err,
1594                        "%s: -mb specified but multi-block support is disabled\n",
1595                        prog);
1596             goto end;
1597 #endif
1598             break;
1599         case OPT_R_CASES:
1600             if (!opt_rand(o))
1601                 goto end;
1602             break;
1603         case OPT_PROV_CASES:
1604             if (!opt_provider(o))
1605                 goto end;
1606             break;
1607         case OPT_CONFIG:
1608             conf = app_load_config_modules(opt_arg());
1609             if (conf == NULL)
1610                 goto end;
1611             break;
1612         case OPT_PRIMES:
1613             primes = opt_int_arg();
1614             break;
1615         case OPT_SECONDS:
1616             seconds.sym = seconds.rsa = seconds.dsa = seconds.ecdsa
1617                         = seconds.ecdh = seconds.eddsa
1618                         = seconds.sm2 = seconds.ffdh = opt_int_arg();
1619             break;
1620         case OPT_BYTES:
1621             lengths_single = opt_int_arg();
1622             lengths = &lengths_single;
1623             size_num = 1;
1624             break;
1625         case OPT_AEAD:
1626             aead = 1;
1627             break;
1628         }
1629     }
1630 
1631     /* Remaining arguments are algorithms. */
1632     argc = opt_num_rest();
1633     argv = opt_rest();
1634 
1635     if (!app_RAND_load())
1636         goto end;
1637 
1638     for (; *argv; argv++) {
1639         const char *algo = *argv;
1640 
1641         if (opt_found(algo, doit_choices, &i)) {
1642             doit[i] = 1;
1643             continue;
1644         }
1645         if (strcmp(algo, "des") == 0) {
1646             doit[D_CBC_DES] = doit[D_EDE3_DES] = 1;
1647             continue;
1648         }
1649         if (strcmp(algo, "sha") == 0) {
1650             doit[D_SHA1] = doit[D_SHA256] = doit[D_SHA512] = 1;
1651             continue;
1652         }
1653 #ifndef OPENSSL_NO_DEPRECATED_3_0
1654         if (strcmp(algo, "openssl") == 0) /* just for compatibility */
1655             continue;
1656 #endif
1657         if (HAS_PREFIX(algo, "rsa")) {
1658             if (algo[sizeof("rsa") - 1] == '\0') {
1659                 memset(rsa_doit, 1, sizeof(rsa_doit));
1660                 continue;
1661             }
1662             if (opt_found(algo, rsa_choices, &i)) {
1663                 rsa_doit[i] = 1;
1664                 continue;
1665             }
1666         }
1667 #ifndef OPENSSL_NO_DH
1668         if (HAS_PREFIX(algo, "ffdh")) {
1669             if (algo[sizeof("ffdh") - 1] == '\0') {
1670                 memset(ffdh_doit, 1, sizeof(ffdh_doit));
1671                 continue;
1672             }
1673             if (opt_found(algo, ffdh_choices, &i)) {
1674                 ffdh_doit[i] = 2;
1675                 continue;
1676             }
1677         }
1678 #endif
1679         if (HAS_PREFIX(algo, "dsa")) {
1680             if (algo[sizeof("dsa") - 1] == '\0') {
1681                 memset(dsa_doit, 1, sizeof(dsa_doit));
1682                 continue;
1683             }
1684             if (opt_found(algo, dsa_choices, &i)) {
1685                 dsa_doit[i] = 2;
1686                 continue;
1687             }
1688         }
1689         if (strcmp(algo, "aes") == 0) {
1690             doit[D_CBC_128_AES] = doit[D_CBC_192_AES] = doit[D_CBC_256_AES] = 1;
1691             continue;
1692         }
1693         if (strcmp(algo, "camellia") == 0) {
1694             doit[D_CBC_128_CML] = doit[D_CBC_192_CML] = doit[D_CBC_256_CML] = 1;
1695             continue;
1696         }
1697         if (HAS_PREFIX(algo, "ecdsa")) {
1698             if (algo[sizeof("ecdsa") - 1] == '\0') {
1699                 memset(ecdsa_doit, 1, sizeof(ecdsa_doit));
1700                 continue;
1701             }
1702             if (opt_found(algo, ecdsa_choices, &i)) {
1703                 ecdsa_doit[i] = 2;
1704                 continue;
1705             }
1706         }
1707         if (HAS_PREFIX(algo, "ecdh")) {
1708             if (algo[sizeof("ecdh") - 1] == '\0') {
1709                 memset(ecdh_doit, 1, sizeof(ecdh_doit));
1710                 continue;
1711             }
1712             if (opt_found(algo, ecdh_choices, &i)) {
1713                 ecdh_doit[i] = 2;
1714                 continue;
1715             }
1716         }
1717         if (strcmp(algo, "eddsa") == 0) {
1718             memset(eddsa_doit, 1, sizeof(eddsa_doit));
1719             continue;
1720         }
1721         if (opt_found(algo, eddsa_choices, &i)) {
1722             eddsa_doit[i] = 2;
1723             continue;
1724         }
1725 #ifndef OPENSSL_NO_SM2
1726         if (strcmp(algo, "sm2") == 0) {
1727             memset(sm2_doit, 1, sizeof(sm2_doit));
1728             continue;
1729         }
1730         if (opt_found(algo, sm2_choices, &i)) {
1731             sm2_doit[i] = 2;
1732             continue;
1733         }
1734 #endif
1735         BIO_printf(bio_err, "%s: Unknown algorithm %s\n", prog, algo);
1736         goto end;
1737     }
1738 
1739     /* Sanity checks */
1740     if (aead) {
1741         if (evp_cipher == NULL) {
1742             BIO_printf(bio_err, "-aead can be used only with an AEAD cipher\n");
1743             goto end;
1744         } else if (!(EVP_CIPHER_get_flags(evp_cipher) &
1745                      EVP_CIPH_FLAG_AEAD_CIPHER)) {
1746             BIO_printf(bio_err, "%s is not an AEAD cipher\n",
1747                        EVP_CIPHER_get0_name(evp_cipher));
1748             goto end;
1749         }
1750     }
1751     if (multiblock) {
1752         if (evp_cipher == NULL) {
1753             BIO_printf(bio_err, "-mb can be used only with a multi-block"
1754                                 " capable cipher\n");
1755             goto end;
1756         } else if (!(EVP_CIPHER_get_flags(evp_cipher) &
1757                      EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
1758             BIO_printf(bio_err, "%s is not a multi-block capable\n",
1759                        EVP_CIPHER_get0_name(evp_cipher));
1760             goto end;
1761         } else if (async_jobs > 0) {
1762             BIO_printf(bio_err, "Async mode is not supported with -mb");
1763             goto end;
1764         }
1765     }
1766 
1767     /* Initialize the job pool if async mode is enabled */
1768     if (async_jobs > 0) {
1769         async_init = ASYNC_init_thread(async_jobs, async_jobs);
1770         if (!async_init) {
1771             BIO_printf(bio_err, "Error creating the ASYNC job pool\n");
1772             goto end;
1773         }
1774     }
1775 
1776     loopargs_len = (async_jobs == 0 ? 1 : async_jobs);
1777     loopargs =
1778         app_malloc(loopargs_len * sizeof(loopargs_t), "array of loopargs");
1779     memset(loopargs, 0, loopargs_len * sizeof(loopargs_t));
1780 
1781     for (i = 0; i < loopargs_len; i++) {
1782         if (async_jobs > 0) {
1783             loopargs[i].wait_ctx = ASYNC_WAIT_CTX_new();
1784             if (loopargs[i].wait_ctx == NULL) {
1785                 BIO_printf(bio_err, "Error creating the ASYNC_WAIT_CTX\n");
1786                 goto end;
1787             }
1788         }
1789 
1790         buflen = lengths[size_num - 1];
1791         if (buflen < 36)    /* size of random vector in RSA benchmark */
1792             buflen = 36;
1793         if (INT_MAX - (MAX_MISALIGNMENT + 1) < buflen) {
1794             BIO_printf(bio_err, "Error: buffer size too large\n");
1795             goto end;
1796         }
1797         buflen += MAX_MISALIGNMENT + 1;
1798         loopargs[i].buf_malloc = app_malloc(buflen, "input buffer");
1799         loopargs[i].buf2_malloc = app_malloc(buflen, "input buffer");
1800         memset(loopargs[i].buf_malloc, 0, buflen);
1801         memset(loopargs[i].buf2_malloc, 0, buflen);
1802 
1803         /* Align the start of buffers on a 64 byte boundary */
1804         loopargs[i].buf = loopargs[i].buf_malloc + misalign;
1805         loopargs[i].buf2 = loopargs[i].buf2_malloc + misalign;
1806         loopargs[i].buflen = buflen - misalign;
1807         loopargs[i].sigsize = buflen - misalign;
1808         loopargs[i].secret_a = app_malloc(MAX_ECDH_SIZE, "ECDH secret a");
1809         loopargs[i].secret_b = app_malloc(MAX_ECDH_SIZE, "ECDH secret b");
1810 #ifndef OPENSSL_NO_DH
1811         loopargs[i].secret_ff_a = app_malloc(MAX_FFDH_SIZE, "FFDH secret a");
1812         loopargs[i].secret_ff_b = app_malloc(MAX_FFDH_SIZE, "FFDH secret b");
1813 #endif
1814     }
1815 
1816 #ifndef NO_FORK
1817     if (multi && do_multi(multi, size_num))
1818         goto show_res;
1819 #endif
1820 
1821     /* Initialize the engine after the fork */
1822     e = setup_engine(engine_id, 0);
1823 
1824     /* No parameters; turn on everything. */
1825     if (argc == 0 && !doit[D_EVP] && !doit[D_HMAC] && !doit[D_EVP_CMAC]) {
1826         memset(doit, 1, sizeof(doit));
1827         doit[D_EVP] = doit[D_EVP_CMAC] = 0;
1828         ERR_set_mark();
1829         for (i = D_MD2; i <= D_WHIRLPOOL; i++) {
1830             if (!have_md(names[i]))
1831                 doit[i] = 0;
1832         }
1833         for (i = D_CBC_DES; i <= D_CBC_256_CML; i++) {
1834             if (!have_cipher(names[i]))
1835                 doit[i] = 0;
1836         }
1837         if ((mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC",
1838                                  app_get0_propq())) != NULL) {
1839             EVP_MAC_free(mac);
1840             mac = NULL;
1841         } else {
1842             doit[D_GHASH] = 0;
1843         }
1844         if ((mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC",
1845                                  app_get0_propq())) != NULL) {
1846             EVP_MAC_free(mac);
1847             mac = NULL;
1848         } else {
1849             doit[D_HMAC] = 0;
1850         }
1851         ERR_pop_to_mark();
1852         memset(rsa_doit, 1, sizeof(rsa_doit));
1853 #ifndef OPENSSL_NO_DH
1854         memset(ffdh_doit, 1, sizeof(ffdh_doit));
1855 #endif
1856         memset(dsa_doit, 1, sizeof(dsa_doit));
1857         memset(ecdsa_doit, 1, sizeof(ecdsa_doit));
1858         memset(ecdh_doit, 1, sizeof(ecdh_doit));
1859         memset(eddsa_doit, 1, sizeof(eddsa_doit));
1860 #ifndef OPENSSL_NO_SM2
1861         memset(sm2_doit, 1, sizeof(sm2_doit));
1862 #endif
1863     }
1864     for (i = 0; i < ALGOR_NUM; i++)
1865         if (doit[i])
1866             pr_header++;
1867 
1868     if (usertime == 0 && !mr)
1869         BIO_printf(bio_err,
1870                    "You have chosen to measure elapsed time "
1871                    "instead of user CPU time.\n");
1872 
1873 #if SIGALRM > 0
1874     signal(SIGALRM, alarmed);
1875 #endif
1876 
1877     if (doit[D_MD2]) {
1878         for (testnum = 0; testnum < size_num; testnum++) {
1879             print_message(names[D_MD2], c[D_MD2][testnum], lengths[testnum],
1880                           seconds.sym);
1881             Time_F(START);
1882             count = run_benchmark(async_jobs, EVP_Digest_MD2_loop, loopargs);
1883             d = Time_F(STOP);
1884             print_result(D_MD2, testnum, count, d);
1885             if (count < 0)
1886                 break;
1887         }
1888     }
1889 
1890     if (doit[D_MDC2]) {
1891         for (testnum = 0; testnum < size_num; testnum++) {
1892             print_message(names[D_MDC2], c[D_MDC2][testnum], lengths[testnum],
1893                           seconds.sym);
1894             Time_F(START);
1895             count = run_benchmark(async_jobs, EVP_Digest_MDC2_loop, loopargs);
1896             d = Time_F(STOP);
1897             print_result(D_MDC2, testnum, count, d);
1898             if (count < 0)
1899                 break;
1900         }
1901     }
1902 
1903     if (doit[D_MD4]) {
1904         for (testnum = 0; testnum < size_num; testnum++) {
1905             print_message(names[D_MD4], c[D_MD4][testnum], lengths[testnum],
1906                           seconds.sym);
1907             Time_F(START);
1908             count = run_benchmark(async_jobs, EVP_Digest_MD4_loop, loopargs);
1909             d = Time_F(STOP);
1910             print_result(D_MD4, testnum, count, d);
1911             if (count < 0)
1912                 break;
1913         }
1914     }
1915 
1916     if (doit[D_MD5]) {
1917         for (testnum = 0; testnum < size_num; testnum++) {
1918             print_message(names[D_MD5], c[D_MD5][testnum], lengths[testnum],
1919                           seconds.sym);
1920             Time_F(START);
1921             count = run_benchmark(async_jobs, MD5_loop, loopargs);
1922             d = Time_F(STOP);
1923             print_result(D_MD5, testnum, count, d);
1924             if (count < 0)
1925                 break;
1926         }
1927     }
1928 
1929     if (doit[D_SHA1]) {
1930         for (testnum = 0; testnum < size_num; testnum++) {
1931             print_message(names[D_SHA1], c[D_SHA1][testnum], lengths[testnum],
1932                           seconds.sym);
1933             Time_F(START);
1934             count = run_benchmark(async_jobs, SHA1_loop, loopargs);
1935             d = Time_F(STOP);
1936             print_result(D_SHA1, testnum, count, d);
1937             if (count < 0)
1938                 break;
1939         }
1940     }
1941 
1942     if (doit[D_SHA256]) {
1943         for (testnum = 0; testnum < size_num; testnum++) {
1944             print_message(names[D_SHA256], c[D_SHA256][testnum],
1945                           lengths[testnum], seconds.sym);
1946             Time_F(START);
1947             count = run_benchmark(async_jobs, SHA256_loop, loopargs);
1948             d = Time_F(STOP);
1949             print_result(D_SHA256, testnum, count, d);
1950             if (count < 0)
1951                 break;
1952         }
1953     }
1954 
1955     if (doit[D_SHA512]) {
1956         for (testnum = 0; testnum < size_num; testnum++) {
1957             print_message(names[D_SHA512], c[D_SHA512][testnum],
1958                           lengths[testnum], seconds.sym);
1959             Time_F(START);
1960             count = run_benchmark(async_jobs, SHA512_loop, loopargs);
1961             d = Time_F(STOP);
1962             print_result(D_SHA512, testnum, count, d);
1963             if (count < 0)
1964                 break;
1965         }
1966     }
1967 
1968     if (doit[D_WHIRLPOOL]) {
1969         for (testnum = 0; testnum < size_num; testnum++) {
1970             print_message(names[D_WHIRLPOOL], c[D_WHIRLPOOL][testnum],
1971                           lengths[testnum], seconds.sym);
1972             Time_F(START);
1973             count = run_benchmark(async_jobs, WHIRLPOOL_loop, loopargs);
1974             d = Time_F(STOP);
1975             print_result(D_WHIRLPOOL, testnum, count, d);
1976             if (count < 0)
1977                 break;
1978         }
1979     }
1980 
1981     if (doit[D_RMD160]) {
1982         for (testnum = 0; testnum < size_num; testnum++) {
1983             print_message(names[D_RMD160], c[D_RMD160][testnum],
1984                           lengths[testnum], seconds.sym);
1985             Time_F(START);
1986             count = run_benchmark(async_jobs, EVP_Digest_RMD160_loop, loopargs);
1987             d = Time_F(STOP);
1988             print_result(D_RMD160, testnum, count, d);
1989             if (count < 0)
1990                 break;
1991         }
1992     }
1993 
1994     if (doit[D_HMAC]) {
1995         static const char hmac_key[] = "This is a key...";
1996         int len = strlen(hmac_key);
1997         OSSL_PARAM params[3];
1998 
1999         mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC", app_get0_propq());
2000         if (mac == NULL || evp_mac_mdname == NULL)
2001             goto end;
2002 
2003         evp_hmac_name = app_malloc(sizeof("hmac()") + strlen(evp_mac_mdname),
2004                                    "HMAC name");
2005         sprintf(evp_hmac_name, "hmac(%s)", evp_mac_mdname);
2006         names[D_HMAC] = evp_hmac_name;
2007 
2008         params[0] =
2009             OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
2010                                              evp_mac_mdname, 0);
2011         params[1] =
2012             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
2013                                               (char *)hmac_key, len);
2014         params[2] = OSSL_PARAM_construct_end();
2015 
2016         for (i = 0; i < loopargs_len; i++) {
2017             loopargs[i].mctx = EVP_MAC_CTX_new(mac);
2018             if (loopargs[i].mctx == NULL)
2019                 goto end;
2020 
2021             if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params))
2022                 goto skip_hmac; /* Digest not found */
2023         }
2024         for (testnum = 0; testnum < size_num; testnum++) {
2025             print_message(names[D_HMAC], c[D_HMAC][testnum], lengths[testnum],
2026                           seconds.sym);
2027             Time_F(START);
2028             count = run_benchmark(async_jobs, HMAC_loop, loopargs);
2029             d = Time_F(STOP);
2030             print_result(D_HMAC, testnum, count, d);
2031             if (count < 0)
2032                 break;
2033         }
2034         for (i = 0; i < loopargs_len; i++)
2035             EVP_MAC_CTX_free(loopargs[i].mctx);
2036         EVP_MAC_free(mac);
2037         mac = NULL;
2038     }
2039 skip_hmac:
2040     if (doit[D_CBC_DES]) {
2041         int st = 1;
2042 
2043         for (i = 0; st && i < loopargs_len; i++) {
2044             loopargs[i].ctx = init_evp_cipher_ctx("des-cbc", deskey,
2045                                                   sizeof(deskey) / 3);
2046             st = loopargs[i].ctx != NULL;
2047         }
2048         algindex = D_CBC_DES;
2049         for (testnum = 0; st && testnum < size_num; testnum++) {
2050             print_message(names[D_CBC_DES], c[D_CBC_DES][testnum],
2051                           lengths[testnum], seconds.sym);
2052             Time_F(START);
2053             count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2054             d = Time_F(STOP);
2055             print_result(D_CBC_DES, testnum, count, d);
2056         }
2057         for (i = 0; i < loopargs_len; i++)
2058             EVP_CIPHER_CTX_free(loopargs[i].ctx);
2059     }
2060 
2061     if (doit[D_EDE3_DES]) {
2062         int st = 1;
2063 
2064         for (i = 0; st && i < loopargs_len; i++) {
2065             loopargs[i].ctx = init_evp_cipher_ctx("des-ede3-cbc", deskey,
2066                                                   sizeof(deskey));
2067             st = loopargs[i].ctx != NULL;
2068         }
2069         algindex = D_EDE3_DES;
2070         for (testnum = 0; st && testnum < size_num; testnum++) {
2071             print_message(names[D_EDE3_DES], c[D_EDE3_DES][testnum],
2072                           lengths[testnum], seconds.sym);
2073             Time_F(START);
2074             count =
2075                 run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2076             d = Time_F(STOP);
2077             print_result(D_EDE3_DES, testnum, count, d);
2078         }
2079         for (i = 0; i < loopargs_len; i++)
2080             EVP_CIPHER_CTX_free(loopargs[i].ctx);
2081     }
2082 
2083     for (k = 0; k < 3; k++) {
2084         algindex = D_CBC_128_AES + k;
2085         if (doit[algindex]) {
2086             int st = 1;
2087 
2088             keylen = 16 + k * 8;
2089             for (i = 0; st && i < loopargs_len; i++) {
2090                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2091                                                       key32, keylen);
2092                 st = loopargs[i].ctx != NULL;
2093             }
2094 
2095             for (testnum = 0; st && testnum < size_num; testnum++) {
2096                 print_message(names[algindex], c[algindex][testnum],
2097                               lengths[testnum], seconds.sym);
2098                 Time_F(START);
2099                 count =
2100                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2101                 d = Time_F(STOP);
2102                 print_result(algindex, testnum, count, d);
2103             }
2104             for (i = 0; i < loopargs_len; i++)
2105                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2106         }
2107     }
2108 
2109     for (k = 0; k < 3; k++) {
2110         algindex = D_CBC_128_CML + k;
2111         if (doit[algindex]) {
2112             int st = 1;
2113 
2114             keylen = 16 + k * 8;
2115             for (i = 0; st && i < loopargs_len; i++) {
2116                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2117                                                       key32, keylen);
2118                 st = loopargs[i].ctx != NULL;
2119             }
2120 
2121             for (testnum = 0; st && testnum < size_num; testnum++) {
2122                 print_message(names[algindex], c[algindex][testnum],
2123                               lengths[testnum], seconds.sym);
2124                 Time_F(START);
2125                 count =
2126                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2127                 d = Time_F(STOP);
2128                 print_result(algindex, testnum, count, d);
2129             }
2130             for (i = 0; i < loopargs_len; i++)
2131                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2132         }
2133     }
2134 
2135     for (algindex = D_RC4; algindex <= D_CBC_CAST; algindex++) {
2136         if (doit[algindex]) {
2137             int st = 1;
2138 
2139             keylen = 16;
2140             for (i = 0; st && i < loopargs_len; i++) {
2141                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2142                                                       key32, keylen);
2143                 st = loopargs[i].ctx != NULL;
2144             }
2145 
2146             for (testnum = 0; st && testnum < size_num; testnum++) {
2147                 print_message(names[algindex], c[algindex][testnum],
2148                               lengths[testnum], seconds.sym);
2149                 Time_F(START);
2150                 count =
2151                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2152                 d = Time_F(STOP);
2153                 print_result(algindex, testnum, count, d);
2154             }
2155             for (i = 0; i < loopargs_len; i++)
2156                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2157         }
2158     }
2159     if (doit[D_GHASH]) {
2160         static const char gmac_iv[] = "0123456789ab";
2161         OSSL_PARAM params[3];
2162 
2163         mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC", app_get0_propq());
2164         if (mac == NULL)
2165             goto end;
2166 
2167         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER,
2168                                                      "aes-128-gcm", 0);
2169         params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
2170                                                       (char *)gmac_iv,
2171                                                       sizeof(gmac_iv) - 1);
2172         params[2] = OSSL_PARAM_construct_end();
2173 
2174         for (i = 0; i < loopargs_len; i++) {
2175             loopargs[i].mctx = EVP_MAC_CTX_new(mac);
2176             if (loopargs[i].mctx == NULL)
2177                 goto end;
2178 
2179             if (!EVP_MAC_init(loopargs[i].mctx, key32, 16, params))
2180                 goto end;
2181         }
2182         for (testnum = 0; testnum < size_num; testnum++) {
2183             print_message(names[D_GHASH], c[D_GHASH][testnum], lengths[testnum],
2184                           seconds.sym);
2185             Time_F(START);
2186             count = run_benchmark(async_jobs, GHASH_loop, loopargs);
2187             d = Time_F(STOP);
2188             print_result(D_GHASH, testnum, count, d);
2189             if (count < 0)
2190                 break;
2191         }
2192         for (i = 0; i < loopargs_len; i++)
2193             EVP_MAC_CTX_free(loopargs[i].mctx);
2194         EVP_MAC_free(mac);
2195         mac = NULL;
2196     }
2197 
2198     if (doit[D_RAND]) {
2199         for (testnum = 0; testnum < size_num; testnum++) {
2200             print_message(names[D_RAND], c[D_RAND][testnum], lengths[testnum],
2201                           seconds.sym);
2202             Time_F(START);
2203             count = run_benchmark(async_jobs, RAND_bytes_loop, loopargs);
2204             d = Time_F(STOP);
2205             print_result(D_RAND, testnum, count, d);
2206         }
2207     }
2208 
2209     if (doit[D_EVP]) {
2210         if (evp_cipher != NULL) {
2211             int (*loopfunc) (void *) = EVP_Update_loop;
2212 
2213             if (multiblock && (EVP_CIPHER_get_flags(evp_cipher) &
2214                                EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
2215                 multiblock_speed(evp_cipher, lengths_single, &seconds);
2216                 ret = 0;
2217                 goto end;
2218             }
2219 
2220             names[D_EVP] = EVP_CIPHER_get0_name(evp_cipher);
2221 
2222             if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_CCM_MODE) {
2223                 loopfunc = EVP_Update_loop_ccm;
2224             } else if (aead && (EVP_CIPHER_get_flags(evp_cipher) &
2225                                 EVP_CIPH_FLAG_AEAD_CIPHER)) {
2226                 loopfunc = EVP_Update_loop_aead;
2227                 if (lengths == lengths_list) {
2228                     lengths = aead_lengths_list;
2229                     size_num = OSSL_NELEM(aead_lengths_list);
2230                 }
2231             }
2232 
2233             for (testnum = 0; testnum < size_num; testnum++) {
2234                 print_message(names[D_EVP], c[D_EVP][testnum], lengths[testnum],
2235                               seconds.sym);
2236 
2237                 for (k = 0; k < loopargs_len; k++) {
2238                     loopargs[k].ctx = EVP_CIPHER_CTX_new();
2239                     if (loopargs[k].ctx == NULL) {
2240                         BIO_printf(bio_err, "\nEVP_CIPHER_CTX_new failure\n");
2241                         exit(1);
2242                     }
2243                     if (!EVP_CipherInit_ex(loopargs[k].ctx, evp_cipher, NULL,
2244                                            NULL, iv, decrypt ? 0 : 1)) {
2245                         BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n");
2246                         ERR_print_errors(bio_err);
2247                         exit(1);
2248                     }
2249 
2250                     EVP_CIPHER_CTX_set_padding(loopargs[k].ctx, 0);
2251 
2252                     keylen = EVP_CIPHER_CTX_get_key_length(loopargs[k].ctx);
2253                     loopargs[k].key = app_malloc(keylen, "evp_cipher key");
2254                     EVP_CIPHER_CTX_rand_key(loopargs[k].ctx, loopargs[k].key);
2255                     if (!EVP_CipherInit_ex(loopargs[k].ctx, NULL, NULL,
2256                                            loopargs[k].key, NULL, -1)) {
2257                         BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n");
2258                         ERR_print_errors(bio_err);
2259                         exit(1);
2260                     }
2261                     OPENSSL_clear_free(loopargs[k].key, keylen);
2262 
2263                     /* GCM-SIV/SIV mode only allows for a single Update operation */
2264                     if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_SIV_MODE
2265                             || EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_GCM_SIV_MODE)
2266                         (void)EVP_CIPHER_CTX_ctrl(loopargs[k].ctx,
2267                                                   EVP_CTRL_SET_SPEED, 1, NULL);
2268                 }
2269 
2270                 Time_F(START);
2271                 count = run_benchmark(async_jobs, loopfunc, loopargs);
2272                 d = Time_F(STOP);
2273                 for (k = 0; k < loopargs_len; k++)
2274                     EVP_CIPHER_CTX_free(loopargs[k].ctx);
2275                 print_result(D_EVP, testnum, count, d);
2276             }
2277         } else if (evp_md_name != NULL) {
2278             names[D_EVP] = evp_md_name;
2279 
2280             for (testnum = 0; testnum < size_num; testnum++) {
2281                 print_message(names[D_EVP], c[D_EVP][testnum], lengths[testnum],
2282                               seconds.sym);
2283                 Time_F(START);
2284                 count = run_benchmark(async_jobs, EVP_Digest_md_loop, loopargs);
2285                 d = Time_F(STOP);
2286                 print_result(D_EVP, testnum, count, d);
2287                 if (count < 0)
2288                     break;
2289             }
2290         }
2291     }
2292 
2293     if (doit[D_EVP_CMAC]) {
2294         OSSL_PARAM params[3];
2295         EVP_CIPHER *cipher = NULL;
2296 
2297         mac = EVP_MAC_fetch(app_get0_libctx(), "CMAC", app_get0_propq());
2298         if (mac == NULL || evp_mac_ciphername == NULL)
2299             goto end;
2300         if (!opt_cipher(evp_mac_ciphername, &cipher))
2301             goto end;
2302 
2303         keylen = EVP_CIPHER_get_key_length(cipher);
2304         EVP_CIPHER_free(cipher);
2305         if (keylen <= 0 || keylen > (int)sizeof(key32)) {
2306             BIO_printf(bio_err, "\nRequested CMAC cipher with unsupported key length.\n");
2307             goto end;
2308         }
2309         evp_cmac_name = app_malloc(sizeof("cmac()")
2310                                    + strlen(evp_mac_ciphername), "CMAC name");
2311         sprintf(evp_cmac_name, "cmac(%s)", evp_mac_ciphername);
2312         names[D_EVP_CMAC] = evp_cmac_name;
2313 
2314         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER,
2315                                                      evp_mac_ciphername, 0);
2316         params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
2317                                                       (char *)key32, keylen);
2318         params[2] = OSSL_PARAM_construct_end();
2319 
2320         for (i = 0; i < loopargs_len; i++) {
2321             loopargs[i].mctx = EVP_MAC_CTX_new(mac);
2322             if (loopargs[i].mctx == NULL)
2323                 goto end;
2324 
2325             if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params))
2326                 goto end;
2327         }
2328 
2329         for (testnum = 0; testnum < size_num; testnum++) {
2330             print_message(names[D_EVP_CMAC], c[D_EVP_CMAC][testnum],
2331                           lengths[testnum], seconds.sym);
2332             Time_F(START);
2333             count = run_benchmark(async_jobs, CMAC_loop, loopargs);
2334             d = Time_F(STOP);
2335             print_result(D_EVP_CMAC, testnum, count, d);
2336             if (count < 0)
2337                 break;
2338         }
2339         for (i = 0; i < loopargs_len; i++)
2340             EVP_MAC_CTX_free(loopargs[i].mctx);
2341         EVP_MAC_free(mac);
2342         mac = NULL;
2343     }
2344 
2345     for (i = 0; i < loopargs_len; i++)
2346         if (RAND_bytes(loopargs[i].buf, 36) <= 0)
2347             goto end;
2348 
2349     for (testnum = 0; testnum < RSA_NUM; testnum++) {
2350         EVP_PKEY *rsa_key = NULL;
2351         int st = 0;
2352 
2353         if (!rsa_doit[testnum])
2354             continue;
2355 
2356         if (primes > RSA_DEFAULT_PRIME_NUM) {
2357             /* we haven't set keys yet,  generate multi-prime RSA keys */
2358             bn = BN_new();
2359             st = bn != NULL
2360                 && BN_set_word(bn, RSA_F4)
2361                 && init_gen_str(&genctx, "RSA", NULL, 0, NULL, NULL)
2362                 && EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, rsa_keys[testnum].bits) > 0
2363                 && EVP_PKEY_CTX_set1_rsa_keygen_pubexp(genctx, bn) > 0
2364                 && EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) > 0
2365                 && EVP_PKEY_keygen(genctx, &rsa_key);
2366             BN_free(bn);
2367             bn = NULL;
2368             EVP_PKEY_CTX_free(genctx);
2369             genctx = NULL;
2370         } else {
2371             const unsigned char *p = rsa_keys[testnum].data;
2372 
2373             st = (rsa_key = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p,
2374                                            rsa_keys[testnum].length)) != NULL;
2375         }
2376 
2377         for (i = 0; st && i < loopargs_len; i++) {
2378             loopargs[i].rsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL);
2379             loopargs[i].sigsize = loopargs[i].buflen;
2380             if (loopargs[i].rsa_sign_ctx[testnum] == NULL
2381                 || EVP_PKEY_sign_init(loopargs[i].rsa_sign_ctx[testnum]) <= 0
2382                 || EVP_PKEY_sign(loopargs[i].rsa_sign_ctx[testnum],
2383                                  loopargs[i].buf2,
2384                                  &loopargs[i].sigsize,
2385                                  loopargs[i].buf, 36) <= 0)
2386                 st = 0;
2387         }
2388         if (!st) {
2389             BIO_printf(bio_err,
2390                        "RSA sign setup failure.  No RSA sign will be done.\n");
2391             ERR_print_errors(bio_err);
2392             op_count = 1;
2393         } else {
2394             pkey_print_message("private", "rsa",
2395                                rsa_c[testnum][0], rsa_keys[testnum].bits,
2396                                seconds.rsa);
2397             /* RSA_blinding_on(rsa_key[testnum],NULL); */
2398             Time_F(START);
2399             count = run_benchmark(async_jobs, RSA_sign_loop, loopargs);
2400             d = Time_F(STOP);
2401             BIO_printf(bio_err,
2402                        mr ? "+R1:%ld:%d:%.2f\n"
2403                        : "%ld %u bits private RSA's in %.2fs\n",
2404                        count, rsa_keys[testnum].bits, d);
2405             rsa_results[testnum][0] = (double)count / d;
2406             op_count = count;
2407         }
2408 
2409         for (i = 0; st && i < loopargs_len; i++) {
2410             loopargs[i].rsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key,
2411                                                                    NULL);
2412             if (loopargs[i].rsa_verify_ctx[testnum] == NULL
2413                 || EVP_PKEY_verify_init(loopargs[i].rsa_verify_ctx[testnum]) <= 0
2414                 || EVP_PKEY_verify(loopargs[i].rsa_verify_ctx[testnum],
2415                                    loopargs[i].buf2,
2416                                    loopargs[i].sigsize,
2417                                    loopargs[i].buf, 36) <= 0)
2418                 st = 0;
2419         }
2420         if (!st) {
2421             BIO_printf(bio_err,
2422                        "RSA verify setup failure.  No RSA verify will be done.\n");
2423             ERR_print_errors(bio_err);
2424             rsa_doit[testnum] = 0;
2425         } else {
2426             pkey_print_message("public", "rsa",
2427                                rsa_c[testnum][1], rsa_keys[testnum].bits,
2428                                seconds.rsa);
2429             Time_F(START);
2430             count = run_benchmark(async_jobs, RSA_verify_loop, loopargs);
2431             d = Time_F(STOP);
2432             BIO_printf(bio_err,
2433                        mr ? "+R2:%ld:%d:%.2f\n"
2434                        : "%ld %u bits public RSA's in %.2fs\n",
2435                        count, rsa_keys[testnum].bits, d);
2436             rsa_results[testnum][1] = (double)count / d;
2437         }
2438 
2439         if (op_count <= 1) {
2440             /* if longer than 10s, don't do any more */
2441             stop_it(rsa_doit, testnum);
2442         }
2443         EVP_PKEY_free(rsa_key);
2444     }
2445 
2446     for (testnum = 0; testnum < DSA_NUM; testnum++) {
2447         EVP_PKEY *dsa_key = NULL;
2448         int st;
2449 
2450         if (!dsa_doit[testnum])
2451             continue;
2452 
2453         st = (dsa_key = get_dsa(dsa_bits[testnum])) != NULL;
2454 
2455         for (i = 0; st && i < loopargs_len; i++) {
2456             loopargs[i].dsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key,
2457                                                                  NULL);
2458             loopargs[i].sigsize = loopargs[i].buflen;
2459             if (loopargs[i].dsa_sign_ctx[testnum] == NULL
2460                 || EVP_PKEY_sign_init(loopargs[i].dsa_sign_ctx[testnum]) <= 0
2461 
2462                 || EVP_PKEY_sign(loopargs[i].dsa_sign_ctx[testnum],
2463                                  loopargs[i].buf2,
2464                                  &loopargs[i].sigsize,
2465                                  loopargs[i].buf, 20) <= 0)
2466                 st = 0;
2467         }
2468         if (!st) {
2469             BIO_printf(bio_err,
2470                        "DSA sign setup failure.  No DSA sign will be done.\n");
2471             ERR_print_errors(bio_err);
2472             op_count = 1;
2473         } else {
2474             pkey_print_message("sign", "dsa",
2475                                dsa_c[testnum][0], dsa_bits[testnum],
2476                                seconds.dsa);
2477             Time_F(START);
2478             count = run_benchmark(async_jobs, DSA_sign_loop, loopargs);
2479             d = Time_F(STOP);
2480             BIO_printf(bio_err,
2481                        mr ? "+R3:%ld:%u:%.2f\n"
2482                        : "%ld %u bits DSA signs in %.2fs\n",
2483                        count, dsa_bits[testnum], d);
2484             dsa_results[testnum][0] = (double)count / d;
2485             op_count = count;
2486         }
2487 
2488         for (i = 0; st && i < loopargs_len; i++) {
2489             loopargs[i].dsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key,
2490                                                                    NULL);
2491             if (loopargs[i].dsa_verify_ctx[testnum] == NULL
2492                 || EVP_PKEY_verify_init(loopargs[i].dsa_verify_ctx[testnum]) <= 0
2493                 || EVP_PKEY_verify(loopargs[i].dsa_verify_ctx[testnum],
2494                                    loopargs[i].buf2,
2495                                    loopargs[i].sigsize,
2496                                    loopargs[i].buf, 36) <= 0)
2497                 st = 0;
2498         }
2499         if (!st) {
2500             BIO_printf(bio_err,
2501                        "DSA verify setup failure.  No DSA verify will be done.\n");
2502             ERR_print_errors(bio_err);
2503             dsa_doit[testnum] = 0;
2504         } else {
2505             pkey_print_message("verify", "dsa",
2506                                dsa_c[testnum][1], dsa_bits[testnum],
2507                                seconds.dsa);
2508             Time_F(START);
2509             count = run_benchmark(async_jobs, DSA_verify_loop, loopargs);
2510             d = Time_F(STOP);
2511             BIO_printf(bio_err,
2512                        mr ? "+R4:%ld:%u:%.2f\n"
2513                        : "%ld %u bits DSA verify in %.2fs\n",
2514                        count, dsa_bits[testnum], d);
2515             dsa_results[testnum][1] = (double)count / d;
2516         }
2517 
2518         if (op_count <= 1) {
2519             /* if longer than 10s, don't do any more */
2520             stop_it(dsa_doit, testnum);
2521         }
2522         EVP_PKEY_free(dsa_key);
2523     }
2524 
2525     for (testnum = 0; testnum < ECDSA_NUM; testnum++) {
2526         EVP_PKEY *ecdsa_key = NULL;
2527         int st;
2528 
2529         if (!ecdsa_doit[testnum])
2530             continue;
2531 
2532         st = (ecdsa_key = get_ecdsa(&ec_curves[testnum])) != NULL;
2533 
2534         for (i = 0; st && i < loopargs_len; i++) {
2535             loopargs[i].ecdsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key,
2536                                                                    NULL);
2537             loopargs[i].sigsize = loopargs[i].buflen;
2538             if (loopargs[i].ecdsa_sign_ctx[testnum] == NULL
2539                 || EVP_PKEY_sign_init(loopargs[i].ecdsa_sign_ctx[testnum]) <= 0
2540 
2541                 || EVP_PKEY_sign(loopargs[i].ecdsa_sign_ctx[testnum],
2542                                  loopargs[i].buf2,
2543                                  &loopargs[i].sigsize,
2544                                  loopargs[i].buf, 20) <= 0)
2545                 st = 0;
2546         }
2547         if (!st) {
2548             BIO_printf(bio_err,
2549                        "ECDSA sign setup failure.  No ECDSA sign will be done.\n");
2550             ERR_print_errors(bio_err);
2551             op_count = 1;
2552         } else {
2553             pkey_print_message("sign", "ecdsa",
2554                                ecdsa_c[testnum][0], ec_curves[testnum].bits,
2555                                seconds.ecdsa);
2556             Time_F(START);
2557             count = run_benchmark(async_jobs, ECDSA_sign_loop, loopargs);
2558             d = Time_F(STOP);
2559             BIO_printf(bio_err,
2560                        mr ? "+R5:%ld:%u:%.2f\n"
2561                        : "%ld %u bits ECDSA signs in %.2fs\n",
2562                        count, ec_curves[testnum].bits, d);
2563             ecdsa_results[testnum][0] = (double)count / d;
2564             op_count = count;
2565         }
2566 
2567         for (i = 0; st && i < loopargs_len; i++) {
2568             loopargs[i].ecdsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key,
2569                                                                      NULL);
2570             if (loopargs[i].ecdsa_verify_ctx[testnum] == NULL
2571                 || EVP_PKEY_verify_init(loopargs[i].ecdsa_verify_ctx[testnum]) <= 0
2572                 || EVP_PKEY_verify(loopargs[i].ecdsa_verify_ctx[testnum],
2573                                    loopargs[i].buf2,
2574                                    loopargs[i].sigsize,
2575                                    loopargs[i].buf, 20) <= 0)
2576                 st = 0;
2577         }
2578         if (!st) {
2579             BIO_printf(bio_err,
2580                        "ECDSA verify setup failure.  No ECDSA verify will be done.\n");
2581             ERR_print_errors(bio_err);
2582             ecdsa_doit[testnum] = 0;
2583         } else {
2584             pkey_print_message("verify", "ecdsa",
2585                                ecdsa_c[testnum][1], ec_curves[testnum].bits,
2586                                seconds.ecdsa);
2587             Time_F(START);
2588             count = run_benchmark(async_jobs, ECDSA_verify_loop, loopargs);
2589             d = Time_F(STOP);
2590             BIO_printf(bio_err,
2591                        mr ? "+R6:%ld:%u:%.2f\n"
2592                        : "%ld %u bits ECDSA verify in %.2fs\n",
2593                        count, ec_curves[testnum].bits, d);
2594             ecdsa_results[testnum][1] = (double)count / d;
2595         }
2596 
2597         if (op_count <= 1) {
2598             /* if longer than 10s, don't do any more */
2599             stop_it(ecdsa_doit, testnum);
2600         }
2601     }
2602 
2603     for (testnum = 0; testnum < EC_NUM; testnum++) {
2604         int ecdh_checks = 1;
2605 
2606         if (!ecdh_doit[testnum])
2607             continue;
2608 
2609         for (i = 0; i < loopargs_len; i++) {
2610             EVP_PKEY_CTX *test_ctx = NULL;
2611             EVP_PKEY_CTX *ctx = NULL;
2612             EVP_PKEY *key_A = NULL;
2613             EVP_PKEY *key_B = NULL;
2614             size_t outlen;
2615             size_t test_outlen;
2616 
2617             if ((key_A = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key A */
2618                 || (key_B = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key B */
2619                 || (ctx = EVP_PKEY_CTX_new(key_A, NULL)) == NULL /* derivation ctx from skeyA */
2620                 || EVP_PKEY_derive_init(ctx) <= 0 /* init derivation ctx */
2621                 || EVP_PKEY_derive_set_peer(ctx, key_B) <= 0 /* set peer pubkey in ctx */
2622                 || EVP_PKEY_derive(ctx, NULL, &outlen) <= 0 /* determine max length */
2623                 || outlen == 0 /* ensure outlen is a valid size */
2624                 || outlen > MAX_ECDH_SIZE /* avoid buffer overflow */) {
2625                 ecdh_checks = 0;
2626                 BIO_printf(bio_err, "ECDH key generation failure.\n");
2627                 ERR_print_errors(bio_err);
2628                 op_count = 1;
2629                 break;
2630             }
2631 
2632             /*
2633              * Here we perform a test run, comparing the output of a*B and b*A;
2634              * we try this here and assume that further EVP_PKEY_derive calls
2635              * never fail, so we can skip checks in the actually benchmarked
2636              * code, for maximum performance.
2637              */
2638             if ((test_ctx = EVP_PKEY_CTX_new(key_B, NULL)) == NULL /* test ctx from skeyB */
2639                 || !EVP_PKEY_derive_init(test_ctx) /* init derivation test_ctx */
2640                 || !EVP_PKEY_derive_set_peer(test_ctx, key_A) /* set peer pubkey in test_ctx */
2641                 || !EVP_PKEY_derive(test_ctx, NULL, &test_outlen) /* determine max length */
2642                 || !EVP_PKEY_derive(ctx, loopargs[i].secret_a, &outlen) /* compute a*B */
2643                 || !EVP_PKEY_derive(test_ctx, loopargs[i].secret_b, &test_outlen) /* compute b*A */
2644                 || test_outlen != outlen /* compare output length */) {
2645                 ecdh_checks = 0;
2646                 BIO_printf(bio_err, "ECDH computation failure.\n");
2647                 ERR_print_errors(bio_err);
2648                 op_count = 1;
2649                 break;
2650             }
2651 
2652             /* Compare the computation results: CRYPTO_memcmp() returns 0 if equal */
2653             if (CRYPTO_memcmp(loopargs[i].secret_a,
2654                               loopargs[i].secret_b, outlen)) {
2655                 ecdh_checks = 0;
2656                 BIO_printf(bio_err, "ECDH computations don't match.\n");
2657                 ERR_print_errors(bio_err);
2658                 op_count = 1;
2659                 break;
2660             }
2661 
2662             loopargs[i].ecdh_ctx[testnum] = ctx;
2663             loopargs[i].outlen[testnum] = outlen;
2664 
2665             EVP_PKEY_free(key_A);
2666             EVP_PKEY_free(key_B);
2667             EVP_PKEY_CTX_free(test_ctx);
2668             test_ctx = NULL;
2669         }
2670         if (ecdh_checks != 0) {
2671             pkey_print_message("", "ecdh",
2672                                ecdh_c[testnum][0],
2673                                ec_curves[testnum].bits, seconds.ecdh);
2674             Time_F(START);
2675             count =
2676                 run_benchmark(async_jobs, ECDH_EVP_derive_key_loop, loopargs);
2677             d = Time_F(STOP);
2678             BIO_printf(bio_err,
2679                        mr ? "+R7:%ld:%d:%.2f\n" :
2680                        "%ld %u-bits ECDH ops in %.2fs\n", count,
2681                        ec_curves[testnum].bits, d);
2682             ecdh_results[testnum][0] = (double)count / d;
2683             op_count = count;
2684         }
2685 
2686         if (op_count <= 1) {
2687             /* if longer than 10s, don't do any more */
2688             stop_it(ecdh_doit, testnum);
2689         }
2690     }
2691 
2692     for (testnum = 0; testnum < EdDSA_NUM; testnum++) {
2693         int st = 1;
2694         EVP_PKEY *ed_pkey = NULL;
2695         EVP_PKEY_CTX *ed_pctx = NULL;
2696 
2697         if (!eddsa_doit[testnum])
2698             continue;           /* Ignore Curve */
2699         for (i = 0; i < loopargs_len; i++) {
2700             loopargs[i].eddsa_ctx[testnum] = EVP_MD_CTX_new();
2701             if (loopargs[i].eddsa_ctx[testnum] == NULL) {
2702                 st = 0;
2703                 break;
2704             }
2705             loopargs[i].eddsa_ctx2[testnum] = EVP_MD_CTX_new();
2706             if (loopargs[i].eddsa_ctx2[testnum] == NULL) {
2707                 st = 0;
2708                 break;
2709             }
2710 
2711             if ((ed_pctx = EVP_PKEY_CTX_new_id(ed_curves[testnum].nid,
2712                                                NULL)) == NULL
2713                 || EVP_PKEY_keygen_init(ed_pctx) <= 0
2714                 || EVP_PKEY_keygen(ed_pctx, &ed_pkey) <= 0) {
2715                 st = 0;
2716                 EVP_PKEY_CTX_free(ed_pctx);
2717                 break;
2718             }
2719             EVP_PKEY_CTX_free(ed_pctx);
2720 
2721             if (!EVP_DigestSignInit(loopargs[i].eddsa_ctx[testnum], NULL, NULL,
2722                                     NULL, ed_pkey)) {
2723                 st = 0;
2724                 EVP_PKEY_free(ed_pkey);
2725                 break;
2726             }
2727             if (!EVP_DigestVerifyInit(loopargs[i].eddsa_ctx2[testnum], NULL,
2728                                       NULL, NULL, ed_pkey)) {
2729                 st = 0;
2730                 EVP_PKEY_free(ed_pkey);
2731                 break;
2732             }
2733 
2734             EVP_PKEY_free(ed_pkey);
2735             ed_pkey = NULL;
2736         }
2737         if (st == 0) {
2738             BIO_printf(bio_err, "EdDSA failure.\n");
2739             ERR_print_errors(bio_err);
2740             op_count = 1;
2741         } else {
2742             for (i = 0; i < loopargs_len; i++) {
2743                 /* Perform EdDSA signature test */
2744                 loopargs[i].sigsize = ed_curves[testnum].sigsize;
2745                 st = EVP_DigestSign(loopargs[i].eddsa_ctx[testnum],
2746                                     loopargs[i].buf2, &loopargs[i].sigsize,
2747                                     loopargs[i].buf, 20);
2748                 if (st == 0)
2749                     break;
2750             }
2751             if (st == 0) {
2752                 BIO_printf(bio_err,
2753                            "EdDSA sign failure.  No EdDSA sign will be done.\n");
2754                 ERR_print_errors(bio_err);
2755                 op_count = 1;
2756             } else {
2757                 pkey_print_message("sign", ed_curves[testnum].name,
2758                                    eddsa_c[testnum][0],
2759                                    ed_curves[testnum].bits, seconds.eddsa);
2760                 Time_F(START);
2761                 count = run_benchmark(async_jobs, EdDSA_sign_loop, loopargs);
2762                 d = Time_F(STOP);
2763 
2764                 BIO_printf(bio_err,
2765                            mr ? "+R8:%ld:%u:%s:%.2f\n" :
2766                            "%ld %u bits %s signs in %.2fs \n",
2767                            count, ed_curves[testnum].bits,
2768                            ed_curves[testnum].name, d);
2769                 eddsa_results[testnum][0] = (double)count / d;
2770                 op_count = count;
2771             }
2772             /* Perform EdDSA verification test */
2773             for (i = 0; i < loopargs_len; i++) {
2774                 st = EVP_DigestVerify(loopargs[i].eddsa_ctx2[testnum],
2775                                       loopargs[i].buf2, loopargs[i].sigsize,
2776                                       loopargs[i].buf, 20);
2777                 if (st != 1)
2778                     break;
2779             }
2780             if (st != 1) {
2781                 BIO_printf(bio_err,
2782                            "EdDSA verify failure.  No EdDSA verify will be done.\n");
2783                 ERR_print_errors(bio_err);
2784                 eddsa_doit[testnum] = 0;
2785             } else {
2786                 pkey_print_message("verify", ed_curves[testnum].name,
2787                                    eddsa_c[testnum][1],
2788                                    ed_curves[testnum].bits, seconds.eddsa);
2789                 Time_F(START);
2790                 count = run_benchmark(async_jobs, EdDSA_verify_loop, loopargs);
2791                 d = Time_F(STOP);
2792                 BIO_printf(bio_err,
2793                            mr ? "+R9:%ld:%u:%s:%.2f\n"
2794                            : "%ld %u bits %s verify in %.2fs\n",
2795                            count, ed_curves[testnum].bits,
2796                            ed_curves[testnum].name, d);
2797                 eddsa_results[testnum][1] = (double)count / d;
2798             }
2799 
2800             if (op_count <= 1) {
2801                 /* if longer than 10s, don't do any more */
2802                 stop_it(eddsa_doit, testnum);
2803             }
2804         }
2805     }
2806 
2807 #ifndef OPENSSL_NO_SM2
2808     for (testnum = 0; testnum < SM2_NUM; testnum++) {
2809         int st = 1;
2810         EVP_PKEY *sm2_pkey = NULL;
2811 
2812         if (!sm2_doit[testnum])
2813             continue;           /* Ignore Curve */
2814         /* Init signing and verification */
2815         for (i = 0; i < loopargs_len; i++) {
2816             EVP_PKEY_CTX *sm2_pctx = NULL;
2817             EVP_PKEY_CTX *sm2_vfy_pctx = NULL;
2818             EVP_PKEY_CTX *pctx = NULL;
2819             st = 0;
2820 
2821             loopargs[i].sm2_ctx[testnum] = EVP_MD_CTX_new();
2822             loopargs[i].sm2_vfy_ctx[testnum] = EVP_MD_CTX_new();
2823             if (loopargs[i].sm2_ctx[testnum] == NULL
2824                     || loopargs[i].sm2_vfy_ctx[testnum] == NULL)
2825                 break;
2826 
2827             sm2_pkey = NULL;
2828 
2829             st = !((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SM2, NULL)) == NULL
2830                 || EVP_PKEY_keygen_init(pctx) <= 0
2831                 || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
2832                     sm2_curves[testnum].nid) <= 0
2833                 || EVP_PKEY_keygen(pctx, &sm2_pkey) <= 0);
2834             EVP_PKEY_CTX_free(pctx);
2835             if (st == 0)
2836                 break;
2837 
2838             st = 0; /* set back to zero */
2839             /* attach it sooner to rely on main final cleanup */
2840             loopargs[i].sm2_pkey[testnum] = sm2_pkey;
2841             loopargs[i].sigsize = EVP_PKEY_get_size(sm2_pkey);
2842 
2843             sm2_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL);
2844             sm2_vfy_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL);
2845             if (sm2_pctx == NULL || sm2_vfy_pctx == NULL) {
2846                 EVP_PKEY_CTX_free(sm2_vfy_pctx);
2847                 break;
2848             }
2849 
2850             /* attach them directly to respective ctx */
2851             EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_ctx[testnum], sm2_pctx);
2852             EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_vfy_ctx[testnum], sm2_vfy_pctx);
2853 
2854             /*
2855              * No need to allow user to set an explicit ID here, just use
2856              * the one defined in the 'draft-yang-tls-tl13-sm-suites' I-D.
2857              */
2858             if (EVP_PKEY_CTX_set1_id(sm2_pctx, SM2_ID, SM2_ID_LEN) != 1
2859                 || EVP_PKEY_CTX_set1_id(sm2_vfy_pctx, SM2_ID, SM2_ID_LEN) != 1)
2860                 break;
2861 
2862             if (!EVP_DigestSignInit(loopargs[i].sm2_ctx[testnum], NULL,
2863                                     EVP_sm3(), NULL, sm2_pkey))
2864                 break;
2865             if (!EVP_DigestVerifyInit(loopargs[i].sm2_vfy_ctx[testnum], NULL,
2866                                       EVP_sm3(), NULL, sm2_pkey))
2867                 break;
2868             st = 1;         /* mark loop as succeeded */
2869         }
2870         if (st == 0) {
2871             BIO_printf(bio_err, "SM2 init failure.\n");
2872             ERR_print_errors(bio_err);
2873             op_count = 1;
2874         } else {
2875             for (i = 0; i < loopargs_len; i++) {
2876                 /* Perform SM2 signature test */
2877                 st = EVP_DigestSign(loopargs[i].sm2_ctx[testnum],
2878                                     loopargs[i].buf2, &loopargs[i].sigsize,
2879                                     loopargs[i].buf, 20);
2880                 if (st == 0)
2881                     break;
2882             }
2883             if (st == 0) {
2884                 BIO_printf(bio_err,
2885                            "SM2 sign failure.  No SM2 sign will be done.\n");
2886                 ERR_print_errors(bio_err);
2887                 op_count = 1;
2888             } else {
2889                 pkey_print_message("sign", sm2_curves[testnum].name,
2890                                    sm2_c[testnum][0],
2891                                    sm2_curves[testnum].bits, seconds.sm2);
2892                 Time_F(START);
2893                 count = run_benchmark(async_jobs, SM2_sign_loop, loopargs);
2894                 d = Time_F(STOP);
2895 
2896                 BIO_printf(bio_err,
2897                            mr ? "+R10:%ld:%u:%s:%.2f\n" :
2898                            "%ld %u bits %s signs in %.2fs \n",
2899                            count, sm2_curves[testnum].bits,
2900                            sm2_curves[testnum].name, d);
2901                 sm2_results[testnum][0] = (double)count / d;
2902                 op_count = count;
2903             }
2904 
2905             /* Perform SM2 verification test */
2906             for (i = 0; i < loopargs_len; i++) {
2907                 st = EVP_DigestVerify(loopargs[i].sm2_vfy_ctx[testnum],
2908                                       loopargs[i].buf2, loopargs[i].sigsize,
2909                                       loopargs[i].buf, 20);
2910                 if (st != 1)
2911                     break;
2912             }
2913             if (st != 1) {
2914                 BIO_printf(bio_err,
2915                            "SM2 verify failure.  No SM2 verify will be done.\n");
2916                 ERR_print_errors(bio_err);
2917                 sm2_doit[testnum] = 0;
2918             } else {
2919                 pkey_print_message("verify", sm2_curves[testnum].name,
2920                                    sm2_c[testnum][1],
2921                                    sm2_curves[testnum].bits, seconds.sm2);
2922                 Time_F(START);
2923                 count = run_benchmark(async_jobs, SM2_verify_loop, loopargs);
2924                 d = Time_F(STOP);
2925                 BIO_printf(bio_err,
2926                            mr ? "+R11:%ld:%u:%s:%.2f\n"
2927                            : "%ld %u bits %s verify in %.2fs\n",
2928                            count, sm2_curves[testnum].bits,
2929                            sm2_curves[testnum].name, d);
2930                 sm2_results[testnum][1] = (double)count / d;
2931             }
2932 
2933             if (op_count <= 1) {
2934                 /* if longer than 10s, don't do any more */
2935                 for (testnum++; testnum < SM2_NUM; testnum++)
2936                     sm2_doit[testnum] = 0;
2937             }
2938         }
2939     }
2940 #endif                         /* OPENSSL_NO_SM2 */
2941 
2942 #ifndef OPENSSL_NO_DH
2943     for (testnum = 0; testnum < FFDH_NUM; testnum++) {
2944         int ffdh_checks = 1;
2945 
2946         if (!ffdh_doit[testnum])
2947             continue;
2948 
2949         for (i = 0; i < loopargs_len; i++) {
2950             EVP_PKEY *pkey_A = NULL;
2951             EVP_PKEY *pkey_B = NULL;
2952             EVP_PKEY_CTX *ffdh_ctx = NULL;
2953             EVP_PKEY_CTX *test_ctx = NULL;
2954             size_t secret_size;
2955             size_t test_out;
2956 
2957             /* Ensure that the error queue is empty */
2958             if (ERR_peek_error()) {
2959                 BIO_printf(bio_err,
2960                            "WARNING: the error queue contains previous unhandled errors.\n");
2961                 ERR_print_errors(bio_err);
2962             }
2963 
2964             pkey_A = EVP_PKEY_new();
2965             if (!pkey_A) {
2966                 BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n");
2967                 ERR_print_errors(bio_err);
2968                 op_count = 1;
2969                 ffdh_checks = 0;
2970                 break;
2971             }
2972             pkey_B = EVP_PKEY_new();
2973             if (!pkey_B) {
2974                 BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n");
2975                 ERR_print_errors(bio_err);
2976                 op_count = 1;
2977                 ffdh_checks = 0;
2978                 break;
2979             }
2980 
2981             ffdh_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, NULL);
2982             if (!ffdh_ctx) {
2983                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
2984                 ERR_print_errors(bio_err);
2985                 op_count = 1;
2986                 ffdh_checks = 0;
2987                 break;
2988             }
2989 
2990             if (EVP_PKEY_keygen_init(ffdh_ctx) <= 0) {
2991                 BIO_printf(bio_err, "Error while initialising EVP_PKEY_CTX.\n");
2992                 ERR_print_errors(bio_err);
2993                 op_count = 1;
2994                 ffdh_checks = 0;
2995                 break;
2996             }
2997             if (EVP_PKEY_CTX_set_dh_nid(ffdh_ctx, ffdh_params[testnum].nid) <= 0) {
2998                 BIO_printf(bio_err, "Error setting DH key size for keygen.\n");
2999                 ERR_print_errors(bio_err);
3000                 op_count = 1;
3001                 ffdh_checks = 0;
3002                 break;
3003             }
3004 
3005             if (EVP_PKEY_keygen(ffdh_ctx, &pkey_A) <= 0 ||
3006                 EVP_PKEY_keygen(ffdh_ctx, &pkey_B) <= 0) {
3007                 BIO_printf(bio_err, "FFDH key generation failure.\n");
3008                 ERR_print_errors(bio_err);
3009                 op_count = 1;
3010                 ffdh_checks = 0;
3011                 break;
3012             }
3013 
3014             EVP_PKEY_CTX_free(ffdh_ctx);
3015 
3016             /*
3017              * check if the derivation works correctly both ways so that
3018              * we know if future derive calls will fail, and we can skip
3019              * error checking in benchmarked code
3020              */
3021             ffdh_ctx = EVP_PKEY_CTX_new(pkey_A, NULL);
3022             if (ffdh_ctx == NULL) {
3023                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
3024                 ERR_print_errors(bio_err);
3025                 op_count = 1;
3026                 ffdh_checks = 0;
3027                 break;
3028             }
3029             if (EVP_PKEY_derive_init(ffdh_ctx) <= 0) {
3030                 BIO_printf(bio_err, "FFDH derivation context init failure.\n");
3031                 ERR_print_errors(bio_err);
3032                 op_count = 1;
3033                 ffdh_checks = 0;
3034                 break;
3035             }
3036             if (EVP_PKEY_derive_set_peer(ffdh_ctx, pkey_B) <= 0) {
3037                 BIO_printf(bio_err, "Assigning peer key for derivation failed.\n");
3038                 ERR_print_errors(bio_err);
3039                 op_count = 1;
3040                 ffdh_checks = 0;
3041                 break;
3042             }
3043             if (EVP_PKEY_derive(ffdh_ctx, NULL, &secret_size) <= 0) {
3044                 BIO_printf(bio_err, "Checking size of shared secret failed.\n");
3045                 ERR_print_errors(bio_err);
3046                 op_count = 1;
3047                 ffdh_checks = 0;
3048                 break;
3049             }
3050             if (secret_size > MAX_FFDH_SIZE) {
3051                 BIO_printf(bio_err, "Assertion failure: shared secret too large.\n");
3052                 op_count = 1;
3053                 ffdh_checks = 0;
3054                 break;
3055             }
3056             if (EVP_PKEY_derive(ffdh_ctx,
3057                                 loopargs[i].secret_ff_a,
3058                                 &secret_size) <= 0) {
3059                 BIO_printf(bio_err, "Shared secret derive failure.\n");
3060                 ERR_print_errors(bio_err);
3061                 op_count = 1;
3062                 ffdh_checks = 0;
3063                 break;
3064             }
3065             /* Now check from side B */
3066             test_ctx = EVP_PKEY_CTX_new(pkey_B, NULL);
3067             if (!test_ctx) {
3068                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
3069                 ERR_print_errors(bio_err);
3070                 op_count = 1;
3071                 ffdh_checks = 0;
3072                 break;
3073             }
3074             if (!EVP_PKEY_derive_init(test_ctx) ||
3075                 !EVP_PKEY_derive_set_peer(test_ctx, pkey_A) ||
3076                 !EVP_PKEY_derive(test_ctx, NULL, &test_out) ||
3077                 !EVP_PKEY_derive(test_ctx, loopargs[i].secret_ff_b, &test_out) ||
3078                 test_out != secret_size) {
3079                 BIO_printf(bio_err, "FFDH computation failure.\n");
3080                 op_count = 1;
3081                 ffdh_checks = 0;
3082                 break;
3083             }
3084 
3085             /* compare the computed secrets */
3086             if (CRYPTO_memcmp(loopargs[i].secret_ff_a,
3087                               loopargs[i].secret_ff_b, secret_size)) {
3088                 BIO_printf(bio_err, "FFDH computations don't match.\n");
3089                 ERR_print_errors(bio_err);
3090                 op_count = 1;
3091                 ffdh_checks = 0;
3092                 break;
3093             }
3094 
3095             loopargs[i].ffdh_ctx[testnum] = ffdh_ctx;
3096 
3097             EVP_PKEY_free(pkey_A);
3098             pkey_A = NULL;
3099             EVP_PKEY_free(pkey_B);
3100             pkey_B = NULL;
3101             EVP_PKEY_CTX_free(test_ctx);
3102             test_ctx = NULL;
3103         }
3104         if (ffdh_checks != 0) {
3105             pkey_print_message("", "ffdh", ffdh_c[testnum][0],
3106                                ffdh_params[testnum].bits, seconds.ffdh);
3107             Time_F(START);
3108             count =
3109                 run_benchmark(async_jobs, FFDH_derive_key_loop, loopargs);
3110             d = Time_F(STOP);
3111             BIO_printf(bio_err,
3112                        mr ? "+R12:%ld:%d:%.2f\n" :
3113                        "%ld %u-bits FFDH ops in %.2fs\n", count,
3114                        ffdh_params[testnum].bits, d);
3115             ffdh_results[testnum][0] = (double)count / d;
3116             op_count = count;
3117         }
3118         if (op_count <= 1) {
3119             /* if longer than 10s, don't do any more */
3120             stop_it(ffdh_doit, testnum);
3121         }
3122     }
3123 #endif  /* OPENSSL_NO_DH */
3124 #ifndef NO_FORK
3125  show_res:
3126 #endif
3127     if (!mr) {
3128         printf("version: %s\n", OpenSSL_version(OPENSSL_FULL_VERSION_STRING));
3129         printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON));
3130         printf("options: %s\n", BN_options());
3131         printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS));
3132         printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO));
3133     }
3134 
3135     if (pr_header) {
3136         if (mr) {
3137             printf("+H");
3138         } else {
3139             printf("The 'numbers' are in 1000s of bytes per second processed.\n");
3140             printf("type        ");
3141         }
3142         for (testnum = 0; testnum < size_num; testnum++)
3143             printf(mr ? ":%d" : "%7d bytes", lengths[testnum]);
3144         printf("\n");
3145     }
3146 
3147     for (k = 0; k < ALGOR_NUM; k++) {
3148         if (!doit[k])
3149             continue;
3150         if (mr)
3151             printf("+F:%u:%s", k, names[k]);
3152         else
3153             printf("%-13s", names[k]);
3154         for (testnum = 0; testnum < size_num; testnum++) {
3155             if (results[k][testnum] > 10000 && !mr)
3156                 printf(" %11.2fk", results[k][testnum] / 1e3);
3157             else
3158                 printf(mr ? ":%.2f" : " %11.2f ", results[k][testnum]);
3159         }
3160         printf("\n");
3161     }
3162     testnum = 1;
3163     for (k = 0; k < RSA_NUM; k++) {
3164         if (!rsa_doit[k])
3165             continue;
3166         if (testnum && !mr) {
3167             printf("%18ssign    verify    sign/s verify/s\n", " ");
3168             testnum = 0;
3169         }
3170         if (mr)
3171             printf("+F2:%u:%u:%f:%f\n",
3172                    k, rsa_keys[k].bits, rsa_results[k][0], rsa_results[k][1]);
3173         else
3174             printf("rsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
3175                    rsa_keys[k].bits, 1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1],
3176                    rsa_results[k][0], rsa_results[k][1]);
3177     }
3178     testnum = 1;
3179     for (k = 0; k < DSA_NUM; k++) {
3180         if (!dsa_doit[k])
3181             continue;
3182         if (testnum && !mr) {
3183             printf("%18ssign    verify    sign/s verify/s\n", " ");
3184             testnum = 0;
3185         }
3186         if (mr)
3187             printf("+F3:%u:%u:%f:%f\n",
3188                    k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]);
3189         else
3190             printf("dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
3191                    dsa_bits[k], 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1],
3192                    dsa_results[k][0], dsa_results[k][1]);
3193     }
3194     testnum = 1;
3195     for (k = 0; k < OSSL_NELEM(ecdsa_doit); k++) {
3196         if (!ecdsa_doit[k])
3197             continue;
3198         if (testnum && !mr) {
3199             printf("%30ssign    verify    sign/s verify/s\n", " ");
3200             testnum = 0;
3201         }
3202 
3203         if (mr)
3204             printf("+F4:%u:%u:%f:%f\n",
3205                    k, ec_curves[k].bits,
3206                    ecdsa_results[k][0], ecdsa_results[k][1]);
3207         else
3208             printf("%4u bits ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
3209                    ec_curves[k].bits, ec_curves[k].name,
3210                    1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1],
3211                    ecdsa_results[k][0], ecdsa_results[k][1]);
3212     }
3213 
3214     testnum = 1;
3215     for (k = 0; k < EC_NUM; k++) {
3216         if (!ecdh_doit[k])
3217             continue;
3218         if (testnum && !mr) {
3219             printf("%30sop      op/s\n", " ");
3220             testnum = 0;
3221         }
3222         if (mr)
3223             printf("+F5:%u:%u:%f:%f\n",
3224                    k, ec_curves[k].bits,
3225                    ecdh_results[k][0], 1.0 / ecdh_results[k][0]);
3226 
3227         else
3228             printf("%4u bits ecdh (%s) %8.4fs %8.1f\n",
3229                    ec_curves[k].bits, ec_curves[k].name,
3230                    1.0 / ecdh_results[k][0], ecdh_results[k][0]);
3231     }
3232 
3233     testnum = 1;
3234     for (k = 0; k < OSSL_NELEM(eddsa_doit); k++) {
3235         if (!eddsa_doit[k])
3236             continue;
3237         if (testnum && !mr) {
3238             printf("%30ssign    verify    sign/s verify/s\n", " ");
3239             testnum = 0;
3240         }
3241 
3242         if (mr)
3243             printf("+F6:%u:%u:%s:%f:%f\n",
3244                    k, ed_curves[k].bits, ed_curves[k].name,
3245                    eddsa_results[k][0], eddsa_results[k][1]);
3246         else
3247             printf("%4u bits EdDSA (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
3248                    ed_curves[k].bits, ed_curves[k].name,
3249                    1.0 / eddsa_results[k][0], 1.0 / eddsa_results[k][1],
3250                    eddsa_results[k][0], eddsa_results[k][1]);
3251     }
3252 
3253 #ifndef OPENSSL_NO_SM2
3254     testnum = 1;
3255     for (k = 0; k < OSSL_NELEM(sm2_doit); k++) {
3256         if (!sm2_doit[k])
3257             continue;
3258         if (testnum && !mr) {
3259             printf("%30ssign    verify    sign/s verify/s\n", " ");
3260             testnum = 0;
3261         }
3262 
3263         if (mr)
3264             printf("+F7:%u:%u:%s:%f:%f\n",
3265                    k, sm2_curves[k].bits, sm2_curves[k].name,
3266                    sm2_results[k][0], sm2_results[k][1]);
3267         else
3268             printf("%4u bits SM2 (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
3269                    sm2_curves[k].bits, sm2_curves[k].name,
3270                    1.0 / sm2_results[k][0], 1.0 / sm2_results[k][1],
3271                    sm2_results[k][0], sm2_results[k][1]);
3272     }
3273 #endif
3274 #ifndef OPENSSL_NO_DH
3275     testnum = 1;
3276     for (k = 0; k < FFDH_NUM; k++) {
3277         if (!ffdh_doit[k])
3278             continue;
3279         if (testnum && !mr) {
3280             printf("%23sop     op/s\n", " ");
3281             testnum = 0;
3282         }
3283         if (mr)
3284             printf("+F8:%u:%u:%f:%f\n",
3285                    k, ffdh_params[k].bits,
3286                    ffdh_results[k][0], 1.0 / ffdh_results[k][0]);
3287 
3288         else
3289             printf("%4u bits ffdh %8.4fs %8.1f\n",
3290                    ffdh_params[k].bits,
3291                    1.0 / ffdh_results[k][0], ffdh_results[k][0]);
3292     }
3293 #endif /* OPENSSL_NO_DH */
3294 
3295     ret = 0;
3296 
3297  end:
3298     ERR_print_errors(bio_err);
3299     for (i = 0; i < loopargs_len; i++) {
3300         OPENSSL_free(loopargs[i].buf_malloc);
3301         OPENSSL_free(loopargs[i].buf2_malloc);
3302 
3303         BN_free(bn);
3304         EVP_PKEY_CTX_free(genctx);
3305         for (k = 0; k < RSA_NUM; k++) {
3306             EVP_PKEY_CTX_free(loopargs[i].rsa_sign_ctx[k]);
3307             EVP_PKEY_CTX_free(loopargs[i].rsa_verify_ctx[k]);
3308         }
3309 #ifndef OPENSSL_NO_DH
3310         OPENSSL_free(loopargs[i].secret_ff_a);
3311         OPENSSL_free(loopargs[i].secret_ff_b);
3312         for (k = 0; k < FFDH_NUM; k++)
3313             EVP_PKEY_CTX_free(loopargs[i].ffdh_ctx[k]);
3314 #endif
3315         for (k = 0; k < DSA_NUM; k++) {
3316             EVP_PKEY_CTX_free(loopargs[i].dsa_sign_ctx[k]);
3317             EVP_PKEY_CTX_free(loopargs[i].dsa_verify_ctx[k]);
3318         }
3319         for (k = 0; k < ECDSA_NUM; k++) {
3320             EVP_PKEY_CTX_free(loopargs[i].ecdsa_sign_ctx[k]);
3321             EVP_PKEY_CTX_free(loopargs[i].ecdsa_verify_ctx[k]);
3322         }
3323         for (k = 0; k < EC_NUM; k++)
3324             EVP_PKEY_CTX_free(loopargs[i].ecdh_ctx[k]);
3325         for (k = 0; k < EdDSA_NUM; k++) {
3326             EVP_MD_CTX_free(loopargs[i].eddsa_ctx[k]);
3327             EVP_MD_CTX_free(loopargs[i].eddsa_ctx2[k]);
3328         }
3329 #ifndef OPENSSL_NO_SM2
3330         for (k = 0; k < SM2_NUM; k++) {
3331             EVP_PKEY_CTX *pctx = NULL;
3332 
3333             /* free signing ctx */
3334             if (loopargs[i].sm2_ctx[k] != NULL
3335                 && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_ctx[k])) != NULL)
3336                 EVP_PKEY_CTX_free(pctx);
3337             EVP_MD_CTX_free(loopargs[i].sm2_ctx[k]);
3338             /* free verification ctx */
3339             if (loopargs[i].sm2_vfy_ctx[k] != NULL
3340                 && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_vfy_ctx[k])) != NULL)
3341                 EVP_PKEY_CTX_free(pctx);
3342             EVP_MD_CTX_free(loopargs[i].sm2_vfy_ctx[k]);
3343             /* free pkey */
3344             EVP_PKEY_free(loopargs[i].sm2_pkey[k]);
3345         }
3346 #endif
3347         OPENSSL_free(loopargs[i].secret_a);
3348         OPENSSL_free(loopargs[i].secret_b);
3349     }
3350     OPENSSL_free(evp_hmac_name);
3351     OPENSSL_free(evp_cmac_name);
3352 
3353     if (async_jobs > 0) {
3354         for (i = 0; i < loopargs_len; i++)
3355             ASYNC_WAIT_CTX_free(loopargs[i].wait_ctx);
3356     }
3357 
3358     if (async_init) {
3359         ASYNC_cleanup_thread();
3360     }
3361     OPENSSL_free(loopargs);
3362     release_engine(e);
3363     EVP_CIPHER_free(evp_cipher);
3364     EVP_MAC_free(mac);
3365     NCONF_free(conf);
3366     return ret;
3367 }
3368 
print_message(const char * s,long num,int length,int tm)3369 static void print_message(const char *s, long num, int length, int tm)
3370 {
3371     BIO_printf(bio_err,
3372                mr ? "+DT:%s:%d:%d\n"
3373                : "Doing %s for %ds on %d size blocks: ", s, tm, length);
3374     (void)BIO_flush(bio_err);
3375     run = 1;
3376     alarm(tm);
3377 }
3378 
pkey_print_message(const char * str,const char * str2,long num,unsigned int bits,int tm)3379 static void pkey_print_message(const char *str, const char *str2, long num,
3380                                unsigned int bits, int tm)
3381 {
3382     BIO_printf(bio_err,
3383                mr ? "+DTP:%d:%s:%s:%d\n"
3384                : "Doing %u bits %s %s's for %ds: ", bits, str, str2, tm);
3385     (void)BIO_flush(bio_err);
3386     run = 1;
3387     alarm(tm);
3388 }
3389 
print_result(int alg,int run_no,int count,double time_used)3390 static void print_result(int alg, int run_no, int count, double time_used)
3391 {
3392     if (count == -1) {
3393         BIO_printf(bio_err, "%s error!\n", names[alg]);
3394         ERR_print_errors(bio_err);
3395         return;
3396     }
3397     BIO_printf(bio_err,
3398                mr ? "+R:%d:%s:%f\n"
3399                : "%d %s's in %.2fs\n", count, names[alg], time_used);
3400     results[alg][run_no] = ((double)count) / time_used * lengths[run_no];
3401 }
3402 
3403 #ifndef NO_FORK
sstrsep(char ** string,const char * delim)3404 static char *sstrsep(char **string, const char *delim)
3405 {
3406     char isdelim[256];
3407     char *token = *string;
3408 
3409     if (**string == 0)
3410         return NULL;
3411 
3412     memset(isdelim, 0, sizeof(isdelim));
3413     isdelim[0] = 1;
3414 
3415     while (*delim) {
3416         isdelim[(unsigned char)(*delim)] = 1;
3417         delim++;
3418     }
3419 
3420     while (!isdelim[(unsigned char)(**string)])
3421         (*string)++;
3422 
3423     if (**string) {
3424         **string = 0;
3425         (*string)++;
3426     }
3427 
3428     return token;
3429 }
3430 
do_multi(int multi,int size_num)3431 static int do_multi(int multi, int size_num)
3432 {
3433     int n;
3434     int fd[2];
3435     int *fds;
3436     int status;
3437     static char sep[] = ":";
3438 
3439     fds = app_malloc(sizeof(*fds) * multi, "fd buffer for do_multi");
3440     for (n = 0; n < multi; ++n) {
3441         if (pipe(fd) == -1) {
3442             BIO_printf(bio_err, "pipe failure\n");
3443             exit(1);
3444         }
3445         fflush(stdout);
3446         (void)BIO_flush(bio_err);
3447         if (fork()) {
3448             close(fd[1]);
3449             fds[n] = fd[0];
3450         } else {
3451             close(fd[0]);
3452             close(1);
3453             if (dup(fd[1]) == -1) {
3454                 BIO_printf(bio_err, "dup failed\n");
3455                 exit(1);
3456             }
3457             close(fd[1]);
3458             mr = 1;
3459             usertime = 0;
3460             OPENSSL_free(fds);
3461             return 0;
3462         }
3463         printf("Forked child %d\n", n);
3464     }
3465 
3466     /* for now, assume the pipe is long enough to take all the output */
3467     for (n = 0; n < multi; ++n) {
3468         FILE *f;
3469         char buf[1024];
3470         char *p;
3471 
3472         f = fdopen(fds[n], "r");
3473         while (fgets(buf, sizeof(buf), f)) {
3474             p = strchr(buf, '\n');
3475             if (p)
3476                 *p = '\0';
3477             if (buf[0] != '+') {
3478                 BIO_printf(bio_err,
3479                            "Don't understand line '%s' from child %d\n", buf,
3480                            n);
3481                 continue;
3482             }
3483             printf("Got: %s from %d\n", buf, n);
3484             p = buf;
3485             if (CHECK_AND_SKIP_PREFIX(p, "+F:")) {
3486                 int alg;
3487                 int j;
3488 
3489                 alg = atoi(sstrsep(&p, sep));
3490                 sstrsep(&p, sep);
3491                 for (j = 0; j < size_num; ++j)
3492                     results[alg][j] += atof(sstrsep(&p, sep));
3493             } else if (CHECK_AND_SKIP_PREFIX(p, "+F2:")) {
3494                 int k;
3495                 double d;
3496 
3497                 k = atoi(sstrsep(&p, sep));
3498                 sstrsep(&p, sep);
3499 
3500                 d = atof(sstrsep(&p, sep));
3501                 rsa_results[k][0] += d;
3502 
3503                 d = atof(sstrsep(&p, sep));
3504                 rsa_results[k][1] += d;
3505             } else if (CHECK_AND_SKIP_PREFIX(p, "+F3:")) {
3506                 int k;
3507                 double d;
3508 
3509                 k = atoi(sstrsep(&p, sep));
3510                 sstrsep(&p, sep);
3511 
3512                 d = atof(sstrsep(&p, sep));
3513                 dsa_results[k][0] += d;
3514 
3515                 d = atof(sstrsep(&p, sep));
3516                 dsa_results[k][1] += d;
3517             } else if (CHECK_AND_SKIP_PREFIX(p, "+F4:")) {
3518                 int k;
3519                 double d;
3520 
3521                 k = atoi(sstrsep(&p, sep));
3522                 sstrsep(&p, sep);
3523 
3524                 d = atof(sstrsep(&p, sep));
3525                 ecdsa_results[k][0] += d;
3526 
3527                 d = atof(sstrsep(&p, sep));
3528                 ecdsa_results[k][1] += d;
3529             } else if (CHECK_AND_SKIP_PREFIX(p, "+F5:")) {
3530                 int k;
3531                 double d;
3532 
3533                 k = atoi(sstrsep(&p, sep));
3534                 sstrsep(&p, sep);
3535 
3536                 d = atof(sstrsep(&p, sep));
3537                 ecdh_results[k][0] += d;
3538             } else if (CHECK_AND_SKIP_PREFIX(p, "+F6:")) {
3539                 int k;
3540                 double d;
3541 
3542                 k = atoi(sstrsep(&p, sep));
3543                 sstrsep(&p, sep);
3544                 sstrsep(&p, sep);
3545 
3546                 d = atof(sstrsep(&p, sep));
3547                 eddsa_results[k][0] += d;
3548 
3549                 d = atof(sstrsep(&p, sep));
3550                 eddsa_results[k][1] += d;
3551 # ifndef OPENSSL_NO_SM2
3552             } else if (CHECK_AND_SKIP_PREFIX(p, "+F7:")) {
3553                 int k;
3554                 double d;
3555 
3556                 k = atoi(sstrsep(&p, sep));
3557                 sstrsep(&p, sep);
3558                 sstrsep(&p, sep);
3559 
3560                 d = atof(sstrsep(&p, sep));
3561                 sm2_results[k][0] += d;
3562 
3563                 d = atof(sstrsep(&p, sep));
3564                 sm2_results[k][1] += d;
3565 # endif /* OPENSSL_NO_SM2 */
3566 # ifndef OPENSSL_NO_DH
3567             } else if (CHECK_AND_SKIP_PREFIX(p, "+F8:")) {
3568                 int k;
3569                 double d;
3570 
3571                 k = atoi(sstrsep(&p, sep));
3572                 sstrsep(&p, sep);
3573 
3574                 d = atof(sstrsep(&p, sep));
3575                 ffdh_results[k][0] += d;
3576 # endif /* OPENSSL_NO_DH */
3577             } else if (!HAS_PREFIX(buf, "+H:")) {
3578                 BIO_printf(bio_err, "Unknown type '%s' from child %d\n", buf,
3579                            n);
3580             }
3581         }
3582 
3583         fclose(f);
3584     }
3585     OPENSSL_free(fds);
3586     for (n = 0; n < multi; ++n) {
3587         while (wait(&status) == -1)
3588             if (errno != EINTR) {
3589                 BIO_printf(bio_err, "Waitng for child failed with 0x%x\n",
3590                            errno);
3591                 return 1;
3592             }
3593         if (WIFEXITED(status) && WEXITSTATUS(status)) {
3594             BIO_printf(bio_err, "Child exited with %d\n", WEXITSTATUS(status));
3595         } else if (WIFSIGNALED(status)) {
3596             BIO_printf(bio_err, "Child terminated by signal %d\n",
3597                        WTERMSIG(status));
3598         }
3599     }
3600     return 1;
3601 }
3602 #endif
3603 
multiblock_speed(const EVP_CIPHER * evp_cipher,int lengths_single,const openssl_speed_sec_t * seconds)3604 static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single,
3605                              const openssl_speed_sec_t *seconds)
3606 {
3607     static const int mblengths_list[] =
3608         { 8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024 };
3609     const int *mblengths = mblengths_list;
3610     int j, count, keylen, num = OSSL_NELEM(mblengths_list);
3611     const char *alg_name;
3612     unsigned char *inp = NULL, *out = NULL, *key, no_key[32], no_iv[16];
3613     EVP_CIPHER_CTX *ctx = NULL;
3614     double d = 0.0;
3615 
3616     if (lengths_single) {
3617         mblengths = &lengths_single;
3618         num = 1;
3619     }
3620 
3621     inp = app_malloc(mblengths[num - 1], "multiblock input buffer");
3622     out = app_malloc(mblengths[num - 1] + 1024, "multiblock output buffer");
3623     if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
3624         app_bail_out("failed to allocate cipher context\n");
3625     if (!EVP_EncryptInit_ex(ctx, evp_cipher, NULL, NULL, no_iv))
3626         app_bail_out("failed to initialise cipher context\n");
3627 
3628     if ((keylen = EVP_CIPHER_CTX_get_key_length(ctx)) < 0) {
3629         BIO_printf(bio_err, "Impossible negative key length: %d\n", keylen);
3630         goto err;
3631     }
3632     key = app_malloc(keylen, "evp_cipher key");
3633     if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
3634         app_bail_out("failed to generate random cipher key\n");
3635     if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL))
3636         app_bail_out("failed to set cipher key\n");
3637     OPENSSL_clear_free(key, keylen);
3638 
3639     if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
3640                              sizeof(no_key), no_key) <= 0)
3641         app_bail_out("failed to set AEAD key\n");
3642     if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL)
3643         app_bail_out("failed to get cipher name\n");
3644 
3645     for (j = 0; j < num; j++) {
3646         print_message(alg_name, 0, mblengths[j], seconds->sym);
3647         Time_F(START);
3648         for (count = 0; run && count < INT_MAX; count++) {
3649             unsigned char aad[EVP_AEAD_TLS1_AAD_LEN];
3650             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
3651             size_t len = mblengths[j];
3652             int packlen;
3653 
3654             memset(aad, 0, 8);  /* avoid uninitialized values */
3655             aad[8] = 23;        /* SSL3_RT_APPLICATION_DATA */
3656             aad[9] = 3;         /* version */
3657             aad[10] = 2;
3658             aad[11] = 0;        /* length */
3659             aad[12] = 0;
3660             mb_param.out = NULL;
3661             mb_param.inp = aad;
3662             mb_param.len = len;
3663             mb_param.interleave = 8;
3664 
3665             packlen = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
3666                                           sizeof(mb_param), &mb_param);
3667 
3668             if (packlen > 0) {
3669                 mb_param.out = out;
3670                 mb_param.inp = inp;
3671                 mb_param.len = len;
3672                 (void)EVP_CIPHER_CTX_ctrl(ctx,
3673                                           EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
3674                                           sizeof(mb_param), &mb_param);
3675             } else {
3676                 int pad;
3677 
3678                 RAND_bytes(out, 16);
3679                 len += 16;
3680                 aad[11] = (unsigned char)(len >> 8);
3681                 aad[12] = (unsigned char)(len);
3682                 pad = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD,
3683                                           EVP_AEAD_TLS1_AAD_LEN, aad);
3684                 EVP_Cipher(ctx, out, inp, len + pad);
3685             }
3686         }
3687         d = Time_F(STOP);
3688         BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n"
3689                    : "%d %s's in %.2fs\n", count, "evp", d);
3690         results[D_EVP][j] = ((double)count) / d * mblengths[j];
3691     }
3692 
3693     if (mr) {
3694         fprintf(stdout, "+H");
3695         for (j = 0; j < num; j++)
3696             fprintf(stdout, ":%d", mblengths[j]);
3697         fprintf(stdout, "\n");
3698         fprintf(stdout, "+F:%d:%s", D_EVP, alg_name);
3699         for (j = 0; j < num; j++)
3700             fprintf(stdout, ":%.2f", results[D_EVP][j]);
3701         fprintf(stdout, "\n");
3702     } else {
3703         fprintf(stdout,
3704                 "The 'numbers' are in 1000s of bytes per second processed.\n");
3705         fprintf(stdout, "type                    ");
3706         for (j = 0; j < num; j++)
3707             fprintf(stdout, "%7d bytes", mblengths[j]);
3708         fprintf(stdout, "\n");
3709         fprintf(stdout, "%-24s", alg_name);
3710 
3711         for (j = 0; j < num; j++) {
3712             if (results[D_EVP][j] > 10000)
3713                 fprintf(stdout, " %11.2fk", results[D_EVP][j] / 1e3);
3714             else
3715                 fprintf(stdout, " %11.2f ", results[D_EVP][j]);
3716         }
3717         fprintf(stdout, "\n");
3718     }
3719 
3720  err:
3721     OPENSSL_free(inp);
3722     OPENSSL_free(out);
3723     EVP_CIPHER_CTX_free(ctx);
3724 }
3725