xref: /aosp_15_r20/external/cronet/third_party/boringssl/src/tool/speed.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 /* Copyright (c) 2014, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <algorithm>
16 #include <functional>
17 #include <memory>
18 #include <string>
19 #include <vector>
20 
21 #include <assert.h>
22 #include <errno.h>
23 #include <inttypes.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <string.h>
27 
28 #define OPENSSL_I_UNDERSTAND_EXPERIMENTAL_FUNCTION_RISK
29 
30 #include <openssl/aead.h>
31 #include <openssl/aes.h>
32 #include <openssl/base64.h>
33 #include <openssl/bn.h>
34 #include <openssl/bytestring.h>
35 #include <openssl/crypto.h>
36 #include <openssl/curve25519.h>
37 #include <openssl/digest.h>
38 #include <openssl/ec.h>
39 #include <openssl/ec_key.h>
40 #include <openssl/ecdsa.h>
41 #include <openssl/err.h>
42 #include <openssl/evp.h>
43 #define OPENSSL_UNSTABLE_EXPERIMENTAL_SPX
44 #include <openssl/experimental/kyber.h>
45 #include <openssl/experimental/spx.h>
46 #include <openssl/hrss.h>
47 #include <openssl/mem.h>
48 #include <openssl/nid.h>
49 #include <openssl/rand.h>
50 #include <openssl/rsa.h>
51 #include <openssl/siphash.h>
52 #include <openssl/trust_token.h>
53 
54 #if defined(OPENSSL_WINDOWS)
55 OPENSSL_MSVC_PRAGMA(warning(push, 3))
56 #include <windows.h>
57 OPENSSL_MSVC_PRAGMA(warning(pop))
58 #elif defined(OPENSSL_APPLE)
59 #include <sys/time.h>
60 #else
61 #include <time.h>
62 #endif
63 
64 #if defined(OPENSSL_THREADS)
65 #include <condition_variable>
66 #include <mutex>
67 #include <thread>
68 #endif
69 
70 #include "../crypto/ec_extra/internal.h"
71 #include "../crypto/fipsmodule/ec/internal.h"
72 #include "../crypto/internal.h"
73 #include "../crypto/trust_token/internal.h"
74 #include "internal.h"
75 
76 // g_print_json is true if printed output is JSON formatted.
77 static bool g_print_json = false;
78 
79 // TimeResults represents the results of benchmarking a function.
80 struct TimeResults {
81   // num_calls is the number of function calls done in the time period.
82   uint64_t num_calls;
83   // us is the number of microseconds that elapsed in the time period.
84   uint64_t us;
85 
PrintTimeResults86   void Print(const std::string &description) const {
87     if (g_print_json) {
88       PrintJSON(description);
89     } else {
90       printf(
91           "Did %" PRIu64 " %s operations in %" PRIu64 "us (%.1f ops/sec)\n",
92           num_calls, description.c_str(), us,
93           (static_cast<double>(num_calls) / static_cast<double>(us)) * 1000000);
94     }
95   }
96 
PrintWithBytesTimeResults97   void PrintWithBytes(const std::string &description,
98                       size_t bytes_per_call) const {
99     if (g_print_json) {
100       PrintJSON(description, bytes_per_call);
101     } else {
102       printf(
103           "Did %" PRIu64 " %s operations in %" PRIu64
104           "us (%.1f ops/sec): %.1f MB/s\n",
105           num_calls, description.c_str(), us,
106           (static_cast<double>(num_calls) / static_cast<double>(us)) * 1000000,
107           static_cast<double>(bytes_per_call * num_calls) /
108               static_cast<double>(us));
109     }
110   }
111 
112  private:
PrintJSONTimeResults113   void PrintJSON(const std::string &description,
114                  size_t bytes_per_call = 0) const {
115     if (first_json_printed) {
116       puts(",");
117     }
118 
119     printf("{\"description\": \"%s\", \"numCalls\": %" PRIu64
120            ", \"microseconds\": %" PRIu64,
121            description.c_str(), num_calls, us);
122 
123     if (bytes_per_call > 0) {
124       printf(", \"bytesPerCall\": %zu", bytes_per_call);
125     }
126 
127     printf("}");
128     first_json_printed = true;
129   }
130 
131   // first_json_printed is true if |g_print_json| is true and the first item in
132   // the JSON results has been printed already. This is used to handle the
133   // commas between each item in the result list.
134   static bool first_json_printed;
135 };
136 
137 bool TimeResults::first_json_printed = false;
138 
139 #if defined(OPENSSL_WINDOWS)
time_now()140 static uint64_t time_now() { return GetTickCount64() * 1000; }
141 #elif defined(OPENSSL_APPLE)
time_now()142 static uint64_t time_now() {
143   struct timeval tv;
144   uint64_t ret;
145 
146   gettimeofday(&tv, NULL);
147   ret = tv.tv_sec;
148   ret *= 1000000;
149   ret += tv.tv_usec;
150   return ret;
151 }
152 #else
time_now()153 static uint64_t time_now() {
154   struct timespec ts;
155   clock_gettime(CLOCK_MONOTONIC, &ts);
156 
157   uint64_t ret = ts.tv_sec;
158   ret *= 1000000;
159   ret += ts.tv_nsec / 1000;
160   return ret;
161 }
162 #endif
163 
164 static uint64_t g_timeout_seconds = 1;
165 static std::vector<size_t> g_chunk_lengths = {16, 256, 1350, 8192, 16384};
166 
167 // IterationsBetweenTimeChecks returns the number of iterations of |func| to run
168 // in between checking the time, or zero on error.
IterationsBetweenTimeChecks(std::function<bool ()> func)169 static uint32_t IterationsBetweenTimeChecks(std::function<bool()> func) {
170   uint64_t start = time_now();
171   if (!func()) {
172     return 0;
173   }
174   uint64_t delta = time_now() - start;
175   if (delta == 0) {
176     return 250;
177   }
178 
179   // Aim for about 100ms between time checks.
180   uint32_t ret = static_cast<double>(100000) / static_cast<double>(delta);
181   if (ret > 1000) {
182     ret = 1000;
183   } else if (ret < 1) {
184     ret = 1;
185   }
186   return ret;
187 }
188 
TimeFunctionImpl(TimeResults * results,std::function<bool ()> func,uint32_t iterations_between_time_checks)189 static bool TimeFunctionImpl(TimeResults *results, std::function<bool()> func,
190                              uint32_t iterations_between_time_checks) {
191   // total_us is the total amount of time that we'll aim to measure a function
192   // for.
193   const uint64_t total_us = g_timeout_seconds * 1000000;
194   uint64_t start = time_now(), now;
195   uint64_t done = 0;
196   for (;;) {
197     for (uint32_t i = 0; i < iterations_between_time_checks; i++) {
198       if (!func()) {
199         return false;
200       }
201       done++;
202     }
203 
204     now = time_now();
205     if (now - start > total_us) {
206       break;
207     }
208   }
209 
210   results->us = now - start;
211   results->num_calls = done;
212   return true;
213 }
214 
TimeFunction(TimeResults * results,std::function<bool ()> func)215 static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
216   uint32_t iterations_between_time_checks = IterationsBetweenTimeChecks(func);
217   if (iterations_between_time_checks == 0) {
218     return false;
219   }
220 
221   return TimeFunctionImpl(results, std::move(func),
222                           iterations_between_time_checks);
223 }
224 
225 #if defined(OPENSSL_THREADS)
226 // g_threads is the number of threads to run in parallel benchmarks.
227 static int g_threads = 1;
228 
229 // Latch behaves like C++20 std::latch.
230 class Latch {
231  public:
Latch(int expected)232   explicit Latch(int expected) : expected_(expected) {}
233   Latch(const Latch &) = delete;
234   Latch &operator=(const Latch &) = delete;
235 
ArriveAndWait()236   void ArriveAndWait() {
237     std::unique_lock<std::mutex> lock(lock_);
238     expected_--;
239     if (expected_ > 0) {
240       cond_.wait(lock, [&] { return expected_ == 0; });
241     } else {
242       cond_.notify_all();
243     }
244   }
245 
246  private:
247   int expected_;
248   std::mutex lock_;
249   std::condition_variable cond_;
250 };
251 
TimeFunctionParallel(TimeResults * results,std::function<bool ()> func)252 static bool TimeFunctionParallel(TimeResults *results,
253                                  std::function<bool()> func) {
254   if (g_threads <= 1) {
255     return TimeFunction(results, std::move(func));
256   }
257 
258   uint32_t iterations_between_time_checks = IterationsBetweenTimeChecks(func);
259   if (iterations_between_time_checks == 0) {
260     return false;
261   }
262 
263   struct ThreadResult {
264     TimeResults time_result;
265     bool ok = false;
266   };
267   std::vector<ThreadResult> thread_results(g_threads);
268   Latch latch(g_threads);
269   std::vector<std::thread> threads;
270   for (int i = 0; i < g_threads; i++) {
271     threads.emplace_back([&, i] {
272       // Wait for all the threads to be ready before running the benchmark.
273       latch.ArriveAndWait();
274       thread_results[i].ok = TimeFunctionImpl(
275           &thread_results[i].time_result, func, iterations_between_time_checks);
276     });
277   }
278 
279   for (auto &thread : threads) {
280     thread.join();
281   }
282 
283   results->num_calls = 0;
284   results->us = 0;
285   for (const auto &pair : thread_results) {
286     if (!pair.ok) {
287       return false;
288     }
289     results->num_calls += pair.time_result.num_calls;
290     results->us += pair.time_result.us;
291   }
292   return true;
293 }
294 
295 #else
TimeFunctionParallel(TimeResults * results,std::function<bool ()> func)296 static bool TimeFunctionParallel(TimeResults *results,
297                                  std::function<bool()> func) {
298   return TimeFunction(results, std::move(func));
299 }
300 #endif
301 
SpeedRSA(const std::string & selected)302 static bool SpeedRSA(const std::string &selected) {
303   if (!selected.empty() && selected.find("RSA") == std::string::npos) {
304     return true;
305   }
306 
307   static const struct {
308     const char *name;
309     const uint8_t *key;
310     const size_t key_len;
311   } kRSAKeys[] = {
312       {"RSA 2048", kDERRSAPrivate2048, kDERRSAPrivate2048Len},
313       {"RSA 4096", kDERRSAPrivate4096, kDERRSAPrivate4096Len},
314   };
315 
316   for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRSAKeys); i++) {
317     const std::string name = kRSAKeys[i].name;
318 
319     bssl::UniquePtr<RSA> key(
320         RSA_private_key_from_bytes(kRSAKeys[i].key, kRSAKeys[i].key_len));
321     if (key == nullptr) {
322       fprintf(stderr, "Failed to parse %s key.\n", name.c_str());
323       ERR_print_errors_fp(stderr);
324       return false;
325     }
326 
327     static constexpr size_t kMaxSignature = 512;
328     if (RSA_size(key.get()) > kMaxSignature) {
329       abort();
330     }
331     const uint8_t fake_sha256_hash[32] = {0};
332 
333     TimeResults results;
334     if (!TimeFunctionParallel(&results, [&key, &fake_sha256_hash]() -> bool {
335           // Usually during RSA signing we're using a long-lived |RSA| that
336           // has already had all of its |BN_MONT_CTX|s constructed, so it
337           // makes sense to use |key| directly here.
338           uint8_t out[kMaxSignature];
339           unsigned out_len;
340           return RSA_sign(NID_sha256, fake_sha256_hash,
341                           sizeof(fake_sha256_hash), out, &out_len, key.get());
342         })) {
343       fprintf(stderr, "RSA_sign failed.\n");
344       ERR_print_errors_fp(stderr);
345       return false;
346     }
347     results.Print(name + " signing");
348 
349     uint8_t sig[kMaxSignature];
350     unsigned sig_len;
351     if (!RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash), sig,
352                   &sig_len, key.get())) {
353       return false;
354     }
355     if (!TimeFunctionParallel(
356             &results, [&key, &fake_sha256_hash, &sig, sig_len]() -> bool {
357               return RSA_verify(NID_sha256, fake_sha256_hash,
358                                 sizeof(fake_sha256_hash), sig, sig_len,
359                                 key.get());
360             })) {
361       fprintf(stderr, "RSA_verify failed.\n");
362       ERR_print_errors_fp(stderr);
363       return false;
364     }
365     results.Print(name + " verify (same key)");
366 
367     if (!TimeFunctionParallel(
368             &results, [&key, &fake_sha256_hash, &sig, sig_len]() -> bool {
369               // Usually during RSA verification we have to parse an RSA key
370               // from a certificate or similar, in which case we'd need to
371               // construct a new RSA key, with a new |BN_MONT_CTX| for the
372               // public modulus. If we were to use |key| directly instead, then
373               // these costs wouldn't be accounted for.
374               bssl::UniquePtr<RSA> verify_key(RSA_new_public_key(
375                   RSA_get0_n(key.get()), RSA_get0_e(key.get())));
376               if (!verify_key) {
377                 return false;
378               }
379               return RSA_verify(NID_sha256, fake_sha256_hash,
380                                 sizeof(fake_sha256_hash), sig, sig_len,
381                                 verify_key.get());
382             })) {
383       fprintf(stderr, "RSA_verify failed.\n");
384       ERR_print_errors_fp(stderr);
385       return false;
386     }
387     results.Print(name + " verify (fresh key)");
388 
389     if (!TimeFunctionParallel(&results, [&]() -> bool {
390           return bssl::UniquePtr<RSA>(RSA_private_key_from_bytes(
391                      kRSAKeys[i].key, kRSAKeys[i].key_len)) != nullptr;
392         })) {
393       fprintf(stderr, "Failed to parse %s key.\n", name.c_str());
394       ERR_print_errors_fp(stderr);
395       return false;
396     }
397     results.Print(name + " private key parse");
398   }
399 
400   return true;
401 }
402 
SpeedRSAKeyGen(const std::string & selected)403 static bool SpeedRSAKeyGen(const std::string &selected) {
404   // Don't run this by default because it's so slow.
405   if (selected != "RSAKeyGen") {
406     return true;
407   }
408 
409   bssl::UniquePtr<BIGNUM> e(BN_new());
410   if (!BN_set_word(e.get(), 65537)) {
411     return false;
412   }
413 
414   const std::vector<int> kSizes = {2048, 3072, 4096};
415   for (int size : kSizes) {
416     const uint64_t start = time_now();
417     uint64_t num_calls = 0;
418     uint64_t us;
419     std::vector<uint64_t> durations;
420 
421     for (;;) {
422       bssl::UniquePtr<RSA> rsa(RSA_new());
423 
424       const uint64_t iteration_start = time_now();
425       if (!RSA_generate_key_ex(rsa.get(), size, e.get(), nullptr)) {
426         fprintf(stderr, "RSA_generate_key_ex failed.\n");
427         ERR_print_errors_fp(stderr);
428         return false;
429       }
430       const uint64_t iteration_end = time_now();
431 
432       num_calls++;
433       durations.push_back(iteration_end - iteration_start);
434 
435       us = iteration_end - start;
436       if (us > 30 * 1000000 /* 30 secs */) {
437         break;
438       }
439     }
440 
441     std::sort(durations.begin(), durations.end());
442     const std::string description =
443         std::string("RSA ") + std::to_string(size) + std::string(" key-gen");
444     const TimeResults results = {num_calls, us};
445     results.Print(description);
446     const size_t n = durations.size();
447     assert(n > 0);
448 
449     // Distribution information is useful, but doesn't fit into the standard
450     // format used by |g_print_json|.
451     if (!g_print_json) {
452       uint64_t min = durations[0];
453       uint64_t median = n & 1 ? durations[n / 2]
454                               : (durations[n / 2 - 1] + durations[n / 2]) / 2;
455       uint64_t max = durations[n - 1];
456       printf("  min: %" PRIu64 "us, median: %" PRIu64 "us, max: %" PRIu64
457              "us\n",
458              min, median, max);
459     }
460   }
461 
462   return true;
463 }
464 
ChunkLenSuffix(size_t chunk_len)465 static std::string ChunkLenSuffix(size_t chunk_len) {
466   char buf[32];
467   snprintf(buf, sizeof(buf), " (%zu byte%s)", chunk_len,
468            chunk_len != 1 ? "s" : "");
469   return buf;
470 }
471 
SpeedAEADChunk(const EVP_AEAD * aead,std::string name,size_t chunk_len,size_t ad_len,evp_aead_direction_t direction)472 static bool SpeedAEADChunk(const EVP_AEAD *aead, std::string name,
473                            size_t chunk_len, size_t ad_len,
474                            evp_aead_direction_t direction) {
475   static const unsigned kAlignment = 16;
476 
477   name += ChunkLenSuffix(chunk_len);
478   bssl::ScopedEVP_AEAD_CTX ctx;
479   const size_t key_len = EVP_AEAD_key_length(aead);
480   const size_t nonce_len = EVP_AEAD_nonce_length(aead);
481   const size_t overhead_len = EVP_AEAD_max_overhead(aead);
482 
483   auto key = std::make_unique<uint8_t[]>(key_len);
484   OPENSSL_memset(key.get(), 0, key_len);
485   auto nonce = std::make_unique<uint8_t[]>(nonce_len);
486   OPENSSL_memset(nonce.get(), 0, nonce_len);
487   auto in_storage = std::make_unique<uint8_t[]>(chunk_len + kAlignment);
488   // N.B. for EVP_AEAD_CTX_seal_scatter the input and output buffers may be the
489   // same size. However, in the direction == evp_aead_open case we still use
490   // non-scattering seal, hence we add overhead_len to the size of this buffer.
491   auto out_storage =
492       std::make_unique<uint8_t[]>(chunk_len + overhead_len + kAlignment);
493   auto in2_storage =
494       std::make_unique<uint8_t[]>(chunk_len + overhead_len + kAlignment);
495   auto ad = std::make_unique<uint8_t[]>(ad_len);
496   OPENSSL_memset(ad.get(), 0, ad_len);
497   auto tag_storage = std::make_unique<uint8_t[]>(overhead_len + kAlignment);
498 
499   uint8_t *const in =
500       static_cast<uint8_t *>(align_pointer(in_storage.get(), kAlignment));
501   OPENSSL_memset(in, 0, chunk_len);
502   uint8_t *const out =
503       static_cast<uint8_t *>(align_pointer(out_storage.get(), kAlignment));
504   OPENSSL_memset(out, 0, chunk_len + overhead_len);
505   uint8_t *const tag =
506       static_cast<uint8_t *>(align_pointer(tag_storage.get(), kAlignment));
507   OPENSSL_memset(tag, 0, overhead_len);
508   uint8_t *const in2 =
509       static_cast<uint8_t *>(align_pointer(in2_storage.get(), kAlignment));
510 
511   if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
512                                         EVP_AEAD_DEFAULT_TAG_LENGTH,
513                                         evp_aead_seal)) {
514     fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
515     ERR_print_errors_fp(stderr);
516     return false;
517   }
518 
519   // TODO(davidben): In most cases, this can be |TimeFunctionParallel|, but a
520   // few stateful AEADs must be run serially.
521   TimeResults results;
522   if (direction == evp_aead_seal) {
523     if (!TimeFunction(&results,
524                       [chunk_len, nonce_len, ad_len, overhead_len, in, out, tag,
525                        &ctx, &nonce, &ad]() -> bool {
526                         size_t tag_len;
527                         return EVP_AEAD_CTX_seal_scatter(
528                             ctx.get(), out, tag, &tag_len, overhead_len,
529                             nonce.get(), nonce_len, in, chunk_len, nullptr, 0,
530                             ad.get(), ad_len);
531                       })) {
532       fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
533       ERR_print_errors_fp(stderr);
534       return false;
535     }
536   } else {
537     size_t out_len;
538     EVP_AEAD_CTX_seal(ctx.get(), out, &out_len, chunk_len + overhead_len,
539                       nonce.get(), nonce_len, in, chunk_len, ad.get(), ad_len);
540 
541     ctx.Reset();
542     if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
543                                           EVP_AEAD_DEFAULT_TAG_LENGTH,
544                                           evp_aead_open)) {
545       fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
546       ERR_print_errors_fp(stderr);
547       return false;
548     }
549 
550     if (!TimeFunction(&results,
551                       [chunk_len, overhead_len, nonce_len, ad_len, in2, out,
552                        out_len, &ctx, &nonce, &ad]() -> bool {
553                         size_t in2_len;
554                         // N.B. EVP_AEAD_CTX_open_gather is not implemented for
555                         // all AEADs.
556                         return EVP_AEAD_CTX_open(ctx.get(), in2, &in2_len,
557                                                  chunk_len + overhead_len,
558                                                  nonce.get(), nonce_len, out,
559                                                  out_len, ad.get(), ad_len);
560                       })) {
561       fprintf(stderr, "EVP_AEAD_CTX_open failed.\n");
562       ERR_print_errors_fp(stderr);
563       return false;
564     }
565   }
566 
567   results.PrintWithBytes(
568       name + (direction == evp_aead_seal ? " seal" : " open"), chunk_len);
569   return true;
570 }
571 
SpeedAEAD(const EVP_AEAD * aead,const std::string & name,size_t ad_len,const std::string & selected)572 static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
573                       size_t ad_len, const std::string &selected) {
574   if (!selected.empty() && name.find(selected) == std::string::npos) {
575     return true;
576   }
577 
578   for (size_t chunk_len : g_chunk_lengths) {
579     if (!SpeedAEADChunk(aead, name, chunk_len, ad_len, evp_aead_seal)) {
580       return false;
581     }
582   }
583   return true;
584 }
585 
SpeedAEADOpen(const EVP_AEAD * aead,const std::string & name,size_t ad_len,const std::string & selected)586 static bool SpeedAEADOpen(const EVP_AEAD *aead, const std::string &name,
587                           size_t ad_len, const std::string &selected) {
588   if (!selected.empty() && name.find(selected) == std::string::npos) {
589     return true;
590   }
591 
592   for (size_t chunk_len : g_chunk_lengths) {
593     if (!SpeedAEADChunk(aead, name, chunk_len, ad_len, evp_aead_open)) {
594       return false;
595     }
596   }
597 
598   return true;
599 }
600 
SpeedAESBlock(const std::string & name,unsigned bits,const std::string & selected)601 static bool SpeedAESBlock(const std::string &name, unsigned bits,
602                           const std::string &selected) {
603   if (!selected.empty() && name.find(selected) == std::string::npos) {
604     return true;
605   }
606 
607   static const uint8_t kZero[32] = {0};
608 
609   {
610     TimeResults results;
611     if (!TimeFunctionParallel(&results, [&]() -> bool {
612           AES_KEY key;
613           return AES_set_encrypt_key(kZero, bits, &key) == 0;
614         })) {
615       fprintf(stderr, "AES_set_encrypt_key failed.\n");
616       return false;
617     }
618     results.Print(name + " encrypt setup");
619   }
620 
621   {
622     AES_KEY key;
623     if (AES_set_encrypt_key(kZero, bits, &key) != 0) {
624       return false;
625     }
626     uint8_t block[16] = {0};
627     TimeResults results;
628     if (!TimeFunctionParallel(&results, [&]() -> bool {
629           AES_encrypt(block, block, &key);
630           return true;
631         })) {
632       fprintf(stderr, "AES_encrypt failed.\n");
633       return false;
634     }
635     results.Print(name + " encrypt");
636   }
637 
638   {
639     TimeResults results;
640     if (!TimeFunctionParallel(&results, [&]() -> bool {
641           AES_KEY key;
642           return AES_set_decrypt_key(kZero, bits, &key) == 0;
643         })) {
644       fprintf(stderr, "AES_set_decrypt_key failed.\n");
645       return false;
646     }
647     results.Print(name + " decrypt setup");
648   }
649 
650   {
651     AES_KEY key;
652     if (AES_set_decrypt_key(kZero, bits, &key) != 0) {
653       return false;
654     }
655     uint8_t block[16] = {0};
656     TimeResults results;
657     if (!TimeFunctionParallel(&results, [&]() -> bool {
658           AES_decrypt(block, block, &key);
659           return true;
660         })) {
661       fprintf(stderr, "AES_decrypt failed.\n");
662       return false;
663     }
664     results.Print(name + " decrypt");
665   }
666 
667   return true;
668 }
669 
SpeedHashChunk(const EVP_MD * md,std::string name,size_t chunk_len)670 static bool SpeedHashChunk(const EVP_MD *md, std::string name,
671                            size_t chunk_len) {
672   uint8_t input[16384] = {0};
673 
674   if (chunk_len > sizeof(input)) {
675     return false;
676   }
677 
678   name += ChunkLenSuffix(chunk_len);
679   TimeResults results;
680   if (!TimeFunctionParallel(&results, [md, chunk_len, &input]() -> bool {
681         uint8_t digest[EVP_MAX_MD_SIZE];
682         unsigned int md_len;
683 
684         bssl::ScopedEVP_MD_CTX ctx;
685         return EVP_DigestInit_ex(ctx.get(), md, NULL /* ENGINE */) &&
686                EVP_DigestUpdate(ctx.get(), input, chunk_len) &&
687                EVP_DigestFinal_ex(ctx.get(), digest, &md_len);
688       })) {
689     fprintf(stderr, "EVP_DigestInit_ex failed.\n");
690     ERR_print_errors_fp(stderr);
691     return false;
692   }
693 
694   results.PrintWithBytes(name, chunk_len);
695   return true;
696 }
697 
SpeedHash(const EVP_MD * md,const std::string & name,const std::string & selected)698 static bool SpeedHash(const EVP_MD *md, const std::string &name,
699                       const std::string &selected) {
700   if (!selected.empty() && name.find(selected) == std::string::npos) {
701     return true;
702   }
703 
704   for (size_t chunk_len : g_chunk_lengths) {
705     if (!SpeedHashChunk(md, name, chunk_len)) {
706       return false;
707     }
708   }
709 
710   return true;
711 }
712 
SpeedRandomChunk(std::string name,size_t chunk_len)713 static bool SpeedRandomChunk(std::string name, size_t chunk_len) {
714   static constexpr size_t kMaxChunk = 16384;
715   if (chunk_len > kMaxChunk) {
716     return false;
717   }
718 
719   name += ChunkLenSuffix(chunk_len);
720   TimeResults results;
721   if (!TimeFunctionParallel(&results, [chunk_len]() -> bool {
722         uint8_t scratch[kMaxChunk];
723         RAND_bytes(scratch, chunk_len);
724         return true;
725       })) {
726     return false;
727   }
728 
729   results.PrintWithBytes(name, chunk_len);
730   return true;
731 }
732 
SpeedRandom(const std::string & selected)733 static bool SpeedRandom(const std::string &selected) {
734   if (!selected.empty() && selected != "RNG") {
735     return true;
736   }
737 
738   for (size_t chunk_len : g_chunk_lengths) {
739     if (!SpeedRandomChunk("RNG", chunk_len)) {
740       return false;
741     }
742   }
743 
744   return true;
745 }
746 
SpeedECDHCurve(const std::string & name,const EC_GROUP * group,const std::string & selected)747 static bool SpeedECDHCurve(const std::string &name, const EC_GROUP *group,
748                            const std::string &selected) {
749   if (!selected.empty() && name.find(selected) == std::string::npos) {
750     return true;
751   }
752 
753   bssl::UniquePtr<EC_KEY> peer_key(EC_KEY_new());
754   if (!peer_key ||
755       !EC_KEY_set_group(peer_key.get(), group) ||
756       !EC_KEY_generate_key(peer_key.get())) {
757     return false;
758   }
759 
760   size_t peer_value_len = EC_POINT_point2oct(
761       EC_KEY_get0_group(peer_key.get()), EC_KEY_get0_public_key(peer_key.get()),
762       POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, nullptr);
763   if (peer_value_len == 0) {
764     return false;
765   }
766   auto peer_value = std::make_unique<uint8_t[]>(peer_value_len);
767   peer_value_len = EC_POINT_point2oct(
768       EC_KEY_get0_group(peer_key.get()), EC_KEY_get0_public_key(peer_key.get()),
769       POINT_CONVERSION_UNCOMPRESSED, peer_value.get(), peer_value_len, nullptr);
770   if (peer_value_len == 0) {
771     return false;
772   }
773 
774   TimeResults results;
775   if (!TimeFunctionParallel(
776           &results, [group, peer_value_len, &peer_value]() -> bool {
777             bssl::UniquePtr<EC_KEY> key(EC_KEY_new());
778             if (!key || !EC_KEY_set_group(key.get(), group) ||
779                 !EC_KEY_generate_key(key.get())) {
780               return false;
781             }
782             bssl::UniquePtr<EC_POINT> point(EC_POINT_new(group));
783             bssl::UniquePtr<EC_POINT> peer_point(EC_POINT_new(group));
784             bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new());
785             bssl::UniquePtr<BIGNUM> x(BN_new());
786             if (!point || !peer_point || !ctx || !x ||
787                 !EC_POINT_oct2point(group, peer_point.get(), peer_value.get(),
788                                     peer_value_len, ctx.get()) ||
789                 !EC_POINT_mul(group, point.get(), nullptr, peer_point.get(),
790                               EC_KEY_get0_private_key(key.get()), ctx.get()) ||
791                 !EC_POINT_get_affine_coordinates_GFp(
792                     group, point.get(), x.get(), nullptr, ctx.get())) {
793               return false;
794             }
795 
796             return true;
797           })) {
798     return false;
799   }
800 
801   results.Print(name);
802   return true;
803 }
804 
SpeedECDSACurve(const std::string & name,const EC_GROUP * group,const std::string & selected)805 static bool SpeedECDSACurve(const std::string &name, const EC_GROUP *group,
806                             const std::string &selected) {
807   if (!selected.empty() && name.find(selected) == std::string::npos) {
808     return true;
809   }
810 
811   bssl::UniquePtr<EC_KEY> key(EC_KEY_new());
812   if (!key ||
813       !EC_KEY_set_group(key.get(), group) ||
814       !EC_KEY_generate_key(key.get())) {
815     return false;
816   }
817 
818   static constexpr size_t kMaxSignature = 256;
819   if (ECDSA_size(key.get()) > kMaxSignature) {
820     abort();
821   }
822   uint8_t digest[20];
823   OPENSSL_memset(digest, 42, sizeof(digest));
824 
825   TimeResults results;
826   if (!TimeFunctionParallel(&results, [&key, &digest]() -> bool {
827         uint8_t out[kMaxSignature];
828         unsigned out_len;
829         return ECDSA_sign(0, digest, sizeof(digest), out, &out_len,
830                           key.get()) == 1;
831       })) {
832     return false;
833   }
834 
835   results.Print(name + " signing");
836 
837   uint8_t signature[kMaxSignature];
838   unsigned sig_len;
839   if (!ECDSA_sign(0, digest, sizeof(digest), signature, &sig_len, key.get())) {
840     return false;
841   }
842 
843   if (!TimeFunctionParallel(
844           &results, [&key, &signature, &digest, sig_len]() -> bool {
845             return ECDSA_verify(0, digest, sizeof(digest), signature, sig_len,
846                                 key.get()) == 1;
847           })) {
848     return false;
849   }
850 
851   results.Print(name + " verify");
852 
853   return true;
854 }
855 
SpeedECDH(const std::string & selected)856 static bool SpeedECDH(const std::string &selected) {
857   return SpeedECDHCurve("ECDH P-224", EC_group_p224(), selected) &&
858          SpeedECDHCurve("ECDH P-256", EC_group_p256(), selected) &&
859          SpeedECDHCurve("ECDH P-384", EC_group_p384(), selected) &&
860          SpeedECDHCurve("ECDH P-521", EC_group_p521(), selected);
861 }
862 
SpeedECDSA(const std::string & selected)863 static bool SpeedECDSA(const std::string &selected) {
864   return SpeedECDSACurve("ECDSA P-224", EC_group_p224(), selected) &&
865          SpeedECDSACurve("ECDSA P-256", EC_group_p256(), selected) &&
866          SpeedECDSACurve("ECDSA P-384", EC_group_p384(), selected) &&
867          SpeedECDSACurve("ECDSA P-521", EC_group_p521(), selected);
868 }
869 
Speed25519(const std::string & selected)870 static bool Speed25519(const std::string &selected) {
871   if (!selected.empty() && selected.find("25519") == std::string::npos) {
872     return true;
873   }
874 
875   TimeResults results;
876   if (!TimeFunctionParallel(&results, []() -> bool {
877         uint8_t public_key[32], private_key[64];
878         ED25519_keypair(public_key, private_key);
879         return true;
880       })) {
881     return false;
882   }
883 
884   results.Print("Ed25519 key generation");
885 
886   uint8_t public_key[32], private_key[64];
887   ED25519_keypair(public_key, private_key);
888   static const uint8_t kMessage[] = {0, 1, 2, 3, 4, 5};
889 
890   if (!TimeFunctionParallel(&results, [&private_key]() -> bool {
891         uint8_t out[64];
892         return ED25519_sign(out, kMessage, sizeof(kMessage), private_key) == 1;
893       })) {
894     return false;
895   }
896 
897   results.Print("Ed25519 signing");
898 
899   uint8_t signature[64];
900   if (!ED25519_sign(signature, kMessage, sizeof(kMessage), private_key)) {
901     return false;
902   }
903 
904   if (!TimeFunctionParallel(&results, [&public_key, &signature]() -> bool {
905         return ED25519_verify(kMessage, sizeof(kMessage), signature,
906                               public_key) == 1;
907       })) {
908     fprintf(stderr, "Ed25519 verify failed.\n");
909     return false;
910   }
911 
912   results.Print("Ed25519 verify");
913 
914   if (!TimeFunctionParallel(&results, []() -> bool {
915         uint8_t out[32], in[32];
916         OPENSSL_memset(in, 0, sizeof(in));
917         X25519_public_from_private(out, in);
918         return true;
919       })) {
920     fprintf(stderr, "Curve25519 base-point multiplication failed.\n");
921     return false;
922   }
923 
924   results.Print("Curve25519 base-point multiplication");
925 
926   if (!TimeFunctionParallel(&results, []() -> bool {
927         uint8_t out[32], in1[32], in2[32];
928         OPENSSL_memset(in1, 0, sizeof(in1));
929         OPENSSL_memset(in2, 0, sizeof(in2));
930         in1[0] = 1;
931         in2[0] = 9;
932         return X25519(out, in1, in2) == 1;
933       })) {
934     fprintf(stderr, "Curve25519 arbitrary point multiplication failed.\n");
935     return false;
936   }
937 
938   results.Print("Curve25519 arbitrary point multiplication");
939 
940   return true;
941 }
942 
SpeedSPAKE2(const std::string & selected)943 static bool SpeedSPAKE2(const std::string &selected) {
944   if (!selected.empty() && selected.find("SPAKE2") == std::string::npos) {
945     return true;
946   }
947 
948   TimeResults results;
949 
950   static const uint8_t kAliceName[] = {'A'};
951   static const uint8_t kBobName[] = {'B'};
952   static const uint8_t kPassword[] = "password";
953   bssl::UniquePtr<SPAKE2_CTX> alice(
954       SPAKE2_CTX_new(spake2_role_alice, kAliceName, sizeof(kAliceName),
955                      kBobName, sizeof(kBobName)));
956   uint8_t alice_msg[SPAKE2_MAX_MSG_SIZE];
957   size_t alice_msg_len;
958 
959   if (!SPAKE2_generate_msg(alice.get(), alice_msg, &alice_msg_len,
960                            sizeof(alice_msg), kPassword, sizeof(kPassword))) {
961     fprintf(stderr, "SPAKE2_generate_msg failed.\n");
962     return false;
963   }
964 
965   if (!TimeFunctionParallel(&results, [&alice_msg, alice_msg_len]() -> bool {
966         bssl::UniquePtr<SPAKE2_CTX> bob(
967             SPAKE2_CTX_new(spake2_role_bob, kBobName, sizeof(kBobName),
968                            kAliceName, sizeof(kAliceName)));
969         uint8_t bob_msg[SPAKE2_MAX_MSG_SIZE], bob_key[64];
970         size_t bob_msg_len, bob_key_len;
971         if (!SPAKE2_generate_msg(bob.get(), bob_msg, &bob_msg_len,
972                                  sizeof(bob_msg), kPassword,
973                                  sizeof(kPassword)) ||
974             !SPAKE2_process_msg(bob.get(), bob_key, &bob_key_len,
975                                 sizeof(bob_key), alice_msg, alice_msg_len)) {
976           return false;
977         }
978 
979         return true;
980       })) {
981     fprintf(stderr, "SPAKE2 failed.\n");
982   }
983 
984   results.Print("SPAKE2 over Ed25519");
985 
986   return true;
987 }
988 
SpeedScrypt(const std::string & selected)989 static bool SpeedScrypt(const std::string &selected) {
990   if (!selected.empty() && selected.find("scrypt") == std::string::npos) {
991     return true;
992   }
993 
994   TimeResults results;
995 
996   static const char kPassword[] = "password";
997   static const uint8_t kSalt[] = "NaCl";
998 
999   if (!TimeFunctionParallel(&results, [&]() -> bool {
1000         uint8_t out[64];
1001         return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
1002                                 sizeof(kSalt) - 1, 1024, 8, 16, 0 /* max_mem */,
1003                                 out, sizeof(out));
1004       })) {
1005     fprintf(stderr, "scrypt failed.\n");
1006     return false;
1007   }
1008   results.Print("scrypt (N = 1024, r = 8, p = 16)");
1009 
1010   if (!TimeFunctionParallel(&results, [&]() -> bool {
1011         uint8_t out[64];
1012         return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
1013                                 sizeof(kSalt) - 1, 16384, 8, 1, 0 /* max_mem */,
1014                                 out, sizeof(out));
1015       })) {
1016     fprintf(stderr, "scrypt failed.\n");
1017     return false;
1018   }
1019   results.Print("scrypt (N = 16384, r = 8, p = 1)");
1020 
1021   return true;
1022 }
1023 
SpeedHRSS(const std::string & selected)1024 static bool SpeedHRSS(const std::string &selected) {
1025   if (!selected.empty() && selected != "HRSS") {
1026     return true;
1027   }
1028 
1029   TimeResults results;
1030 
1031   if (!TimeFunctionParallel(&results, []() -> bool {
1032         struct HRSS_public_key pub;
1033         struct HRSS_private_key priv;
1034         uint8_t entropy[HRSS_GENERATE_KEY_BYTES];
1035         RAND_bytes(entropy, sizeof(entropy));
1036         return HRSS_generate_key(&pub, &priv, entropy);
1037       })) {
1038     fprintf(stderr, "Failed to time HRSS_generate_key.\n");
1039     return false;
1040   }
1041 
1042   results.Print("HRSS generate");
1043 
1044   struct HRSS_public_key pub;
1045   struct HRSS_private_key priv;
1046   uint8_t key_entropy[HRSS_GENERATE_KEY_BYTES];
1047   RAND_bytes(key_entropy, sizeof(key_entropy));
1048   if (!HRSS_generate_key(&pub, &priv, key_entropy)) {
1049     return false;
1050   }
1051 
1052   if (!TimeFunctionParallel(&results, [&pub]() -> bool {
1053         uint8_t entropy[HRSS_ENCAP_BYTES];
1054         uint8_t shared_key[HRSS_KEY_BYTES];
1055         uint8_t ciphertext[HRSS_CIPHERTEXT_BYTES];
1056         RAND_bytes(entropy, sizeof(entropy));
1057         return HRSS_encap(ciphertext, shared_key, &pub, entropy);
1058       })) {
1059     fprintf(stderr, "Failed to time HRSS_encap.\n");
1060     return false;
1061   }
1062   results.Print("HRSS encap");
1063 
1064   uint8_t entropy[HRSS_ENCAP_BYTES];
1065   uint8_t shared_key[HRSS_KEY_BYTES];
1066   uint8_t ciphertext[HRSS_CIPHERTEXT_BYTES];
1067   RAND_bytes(entropy, sizeof(entropy));
1068   if (!HRSS_encap(ciphertext, shared_key, &pub, entropy)) {
1069     return false;
1070   }
1071 
1072   if (!TimeFunctionParallel(&results, [&priv, &ciphertext]() -> bool {
1073         uint8_t shared_key2[HRSS_KEY_BYTES];
1074         return HRSS_decap(shared_key2, &priv, ciphertext, sizeof(ciphertext));
1075       })) {
1076     fprintf(stderr, "Failed to time HRSS_encap.\n");
1077     return false;
1078   }
1079 
1080   results.Print("HRSS decap");
1081 
1082   return true;
1083 }
1084 
SpeedKyber(const std::string & selected)1085 static bool SpeedKyber(const std::string &selected) {
1086   if (!selected.empty() && selected != "Kyber") {
1087     return true;
1088   }
1089 
1090   TimeResults results;
1091 
1092   uint8_t ciphertext[KYBER_CIPHERTEXT_BYTES];
1093   // This ciphertext is nonsense, but Kyber decap is constant-time so, for the
1094   // purposes of timing, it's fine.
1095   memset(ciphertext, 42, sizeof(ciphertext));
1096   if (!TimeFunctionParallel(&results, [&]() -> bool {
1097         KYBER_private_key priv;
1098         uint8_t encoded_public_key[KYBER_PUBLIC_KEY_BYTES];
1099         KYBER_generate_key(encoded_public_key, &priv);
1100         uint8_t shared_secret[KYBER_SHARED_SECRET_BYTES];
1101         KYBER_decap(shared_secret, ciphertext, &priv);
1102         return true;
1103       })) {
1104     fprintf(stderr, "Failed to time KYBER_generate_key + KYBER_decap.\n");
1105     return false;
1106   }
1107 
1108   results.Print("Kyber generate + decap");
1109 
1110   KYBER_private_key priv;
1111   uint8_t encoded_public_key[KYBER_PUBLIC_KEY_BYTES];
1112   KYBER_generate_key(encoded_public_key, &priv);
1113   KYBER_public_key pub;
1114   if (!TimeFunctionParallel(&results, [&]() -> bool {
1115         CBS encoded_public_key_cbs;
1116         CBS_init(&encoded_public_key_cbs, encoded_public_key,
1117                  sizeof(encoded_public_key));
1118         if (!KYBER_parse_public_key(&pub, &encoded_public_key_cbs)) {
1119           return false;
1120         }
1121         uint8_t shared_secret[KYBER_SHARED_SECRET_BYTES];
1122         KYBER_encap(ciphertext, shared_secret, &pub);
1123         return true;
1124       })) {
1125     fprintf(stderr, "Failed to time KYBER_encap.\n");
1126     return false;
1127   }
1128 
1129   results.Print("Kyber parse + encap");
1130 
1131   return true;
1132 }
1133 
SpeedSpx(const std::string & selected)1134 static bool SpeedSpx(const std::string &selected) {
1135   if (!selected.empty() && selected.find("spx") == std::string::npos) {
1136     return true;
1137   }
1138 
1139   TimeResults results;
1140   if (!TimeFunctionParallel(&results, []() -> bool {
1141         uint8_t public_key[32], private_key[64];
1142         SPX_generate_key(public_key, private_key);
1143         return true;
1144       })) {
1145     return false;
1146   }
1147 
1148   results.Print("SPHINCS+-SHA2-128s key generation");
1149 
1150   uint8_t public_key[32], private_key[64];
1151   SPX_generate_key(public_key, private_key);
1152   static const uint8_t kMessage[] = {0, 1, 2, 3, 4, 5};
1153 
1154   if (!TimeFunctionParallel(&results, [&private_key]() -> bool {
1155         uint8_t out[SPX_SIGNATURE_BYTES];
1156         SPX_sign(out, private_key, kMessage, sizeof(kMessage), true);
1157         return true;
1158       })) {
1159     return false;
1160   }
1161 
1162   results.Print("SPHINCS+-SHA2-128s signing");
1163 
1164   uint8_t signature[SPX_SIGNATURE_BYTES];
1165   SPX_sign(signature, private_key, kMessage, sizeof(kMessage), true);
1166 
1167   if (!TimeFunctionParallel(&results, [&public_key, &signature]() -> bool {
1168         return SPX_verify(signature, public_key, kMessage, sizeof(kMessage)) ==
1169                1;
1170       })) {
1171     fprintf(stderr, "SPHINCS+-SHA2-128s verify failed.\n");
1172     return false;
1173   }
1174 
1175   results.Print("SPHINCS+-SHA2-128s verify");
1176 
1177   return true;
1178 }
1179 
SpeedHashToCurve(const std::string & selected)1180 static bool SpeedHashToCurve(const std::string &selected) {
1181   if (!selected.empty() && selected.find("hashtocurve") == std::string::npos) {
1182     return true;
1183   }
1184 
1185   uint8_t input[64];
1186   RAND_bytes(input, sizeof(input));
1187 
1188   static const uint8_t kLabel[] = "label";
1189 
1190   TimeResults results;
1191   {
1192     if (!TimeFunctionParallel(&results, [&]() -> bool {
1193           EC_JACOBIAN out;
1194           return ec_hash_to_curve_p256_xmd_sha256_sswu(EC_group_p256(), &out,
1195                                                        kLabel, sizeof(kLabel),
1196                                                        input, sizeof(input));
1197         })) {
1198       fprintf(stderr, "hash-to-curve failed.\n");
1199       return false;
1200     }
1201     results.Print("hash-to-curve P256_XMD:SHA-256_SSWU_RO_");
1202 
1203     if (!TimeFunctionParallel(&results, [&]() -> bool {
1204           EC_JACOBIAN out;
1205           return ec_hash_to_curve_p384_xmd_sha384_sswu(EC_group_p384(), &out,
1206                                                        kLabel, sizeof(kLabel),
1207                                                        input, sizeof(input));
1208         })) {
1209       fprintf(stderr, "hash-to-curve failed.\n");
1210       return false;
1211     }
1212     results.Print("hash-to-curve P384_XMD:SHA-384_SSWU_RO_");
1213 
1214     if (!TimeFunctionParallel(&results, [&]() -> bool {
1215           EC_SCALAR out;
1216           return ec_hash_to_scalar_p384_xmd_sha512_draft07(
1217               EC_group_p384(), &out, kLabel, sizeof(kLabel), input,
1218               sizeof(input));
1219         })) {
1220       fprintf(stderr, "hash-to-scalar failed.\n");
1221       return false;
1222     }
1223     results.Print("hash-to-scalar P384_XMD:SHA-512");
1224   }
1225 
1226   return true;
1227 }
1228 
SpeedBase64(const std::string & selected)1229 static bool SpeedBase64(const std::string &selected) {
1230   if (!selected.empty() && selected.find("base64") == std::string::npos) {
1231     return true;
1232   }
1233 
1234   static const char kInput[] =
1235       "MIIDtTCCAp2gAwIBAgIJALW2IrlaBKUhMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV"
1236       "BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX"
1237       "aWRnaXRzIFB0eSBMdGQwHhcNMTYwNzA5MDQzODA5WhcNMTYwODA4MDQzODA5WjBF"
1238       "MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50"
1239       "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB"
1240       "CgKCAQEAugvahBkSAUF1fC49vb1bvlPrcl80kop1iLpiuYoz4Qptwy57+EWssZBc"
1241       "HprZ5BkWf6PeGZ7F5AX1PyJbGHZLqvMCvViP6pd4MFox/igESISEHEixoiXCzepB"
1242       "rhtp5UQSjHD4D4hKtgdMgVxX+LRtwgW3mnu/vBu7rzpr/DS8io99p3lqZ1Aky+aN"
1243       "lcMj6MYy8U+YFEevb/V0lRY9oqwmW7BHnXikm/vi6sjIS350U8zb/mRzYeIs2R65"
1244       "LUduTL50+UMgat9ocewI2dv8aO9Dph+8NdGtg8LFYyTTHcUxJoMr1PTOgnmET19W"
1245       "JH4PrFwk7ZE1QJQQ1L4iKmPeQistuQIDAQABo4GnMIGkMB0GA1UdDgQWBBT5m6Vv"
1246       "zYjVYHG30iBE+j2XDhUE8jB1BgNVHSMEbjBsgBT5m6VvzYjVYHG30iBE+j2XDhUE"
1247       "8qFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV"
1248       "BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJALW2IrlaBKUhMAwGA1UdEwQF"
1249       "MAMBAf8wDQYJKoZIhvcNAQELBQADggEBAD7Jg68SArYWlcoHfZAB90Pmyrt5H6D8"
1250       "LRi+W2Ri1fBNxREELnezWJ2scjl4UMcsKYp4Pi950gVN+62IgrImcCNvtb5I1Cfy"
1251       "/MNNur9ffas6X334D0hYVIQTePyFk3umI+2mJQrtZZyMPIKSY/sYGQHhGGX6wGK+"
1252       "GO/og0PQk/Vu6D+GU2XRnDV0YZg1lsAsHd21XryK6fDmNkEMwbIWrts4xc7scRrG"
1253       "HWy+iMf6/7p/Ak/SIicM4XSwmlQ8pPxAZPr+E2LoVd9pMpWUwpW2UbtO5wsGTrY5"
1254       "sO45tFNN/y+jtUheB1C2ijObG/tXELaiyCdM+S/waeuv0MXtI4xnn1A=";
1255 
1256   TimeResults results;
1257   if (!TimeFunctionParallel(&results, [&]() -> bool {
1258         uint8_t out[sizeof(kInput)];
1259         size_t len;
1260         return EVP_DecodeBase64(out, &len, sizeof(out),
1261                                 reinterpret_cast<const uint8_t *>(kInput),
1262                                 strlen(kInput));
1263       })) {
1264     fprintf(stderr, "base64 decode failed.\n");
1265     return false;
1266   }
1267   results.PrintWithBytes("base64 decode", strlen(kInput));
1268   return true;
1269 }
1270 
SpeedSipHash(const std::string & selected)1271 static bool SpeedSipHash(const std::string &selected) {
1272   if (!selected.empty() && selected.find("siphash") == std::string::npos) {
1273     return true;
1274   }
1275 
1276   uint64_t key[2] = {0};
1277   for (size_t len : g_chunk_lengths) {
1278     std::vector<uint8_t> input(len);
1279     TimeResults results;
1280     if (!TimeFunctionParallel(&results, [&]() -> bool {
1281           SIPHASH_24(key, input.data(), input.size());
1282           return true;
1283         })) {
1284       fprintf(stderr, "SIPHASH_24 failed.\n");
1285       ERR_print_errors_fp(stderr);
1286       return false;
1287     }
1288     results.PrintWithBytes("SipHash-2-4" + ChunkLenSuffix(len), len);
1289   }
1290 
1291   return true;
1292 }
1293 
trust_token_pretoken_dup(const TRUST_TOKEN_PRETOKEN * in)1294 static TRUST_TOKEN_PRETOKEN *trust_token_pretoken_dup(
1295     const TRUST_TOKEN_PRETOKEN *in) {
1296   return static_cast<TRUST_TOKEN_PRETOKEN *>(
1297       OPENSSL_memdup(in, sizeof(TRUST_TOKEN_PRETOKEN)));
1298 }
1299 
SpeedTrustToken(std::string name,const TRUST_TOKEN_METHOD * method,size_t batchsize,const std::string & selected)1300 static bool SpeedTrustToken(std::string name, const TRUST_TOKEN_METHOD *method,
1301                             size_t batchsize, const std::string &selected) {
1302   if (!selected.empty() && selected.find("trusttoken") == std::string::npos) {
1303     return true;
1304   }
1305 
1306   TimeResults results;
1307   if (!TimeFunction(&results, [&]() -> bool {
1308         uint8_t priv_key[TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE];
1309         uint8_t pub_key[TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE];
1310         size_t priv_key_len, pub_key_len;
1311         return TRUST_TOKEN_generate_key(
1312             method, priv_key, &priv_key_len, TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE,
1313             pub_key, &pub_key_len, TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE, 0);
1314       })) {
1315     fprintf(stderr, "TRUST_TOKEN_generate_key failed.\n");
1316     return false;
1317   }
1318   results.Print(name + " generate_key");
1319 
1320   bssl::UniquePtr<TRUST_TOKEN_CLIENT> client(
1321       TRUST_TOKEN_CLIENT_new(method, batchsize));
1322   bssl::UniquePtr<TRUST_TOKEN_ISSUER> issuer(
1323       TRUST_TOKEN_ISSUER_new(method, batchsize));
1324   uint8_t priv_key[TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE];
1325   uint8_t pub_key[TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE];
1326   size_t priv_key_len, pub_key_len, key_index;
1327   if (!client || !issuer ||
1328       !TRUST_TOKEN_generate_key(
1329           method, priv_key, &priv_key_len, TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE,
1330           pub_key, &pub_key_len, TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE, 0) ||
1331       !TRUST_TOKEN_CLIENT_add_key(client.get(), &key_index, pub_key,
1332                                   pub_key_len) ||
1333       !TRUST_TOKEN_ISSUER_add_key(issuer.get(), priv_key, priv_key_len)) {
1334     fprintf(stderr, "failed to generate trust token key.\n");
1335     return false;
1336   }
1337 
1338   uint8_t public_key[32], private_key[64];
1339   ED25519_keypair(public_key, private_key);
1340   bssl::UniquePtr<EVP_PKEY> priv(
1341       EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, private_key, 32));
1342   bssl::UniquePtr<EVP_PKEY> pub(
1343       EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key, 32));
1344   if (!priv || !pub) {
1345     fprintf(stderr, "failed to generate trust token SRR key.\n");
1346     return false;
1347   }
1348 
1349   TRUST_TOKEN_CLIENT_set_srr_key(client.get(), pub.get());
1350   TRUST_TOKEN_ISSUER_set_srr_key(issuer.get(), priv.get());
1351   uint8_t metadata_key[32];
1352   RAND_bytes(metadata_key, sizeof(metadata_key));
1353   if (!TRUST_TOKEN_ISSUER_set_metadata_key(issuer.get(), metadata_key,
1354                                            sizeof(metadata_key))) {
1355     fprintf(stderr, "failed to generate trust token metadata key.\n");
1356     return false;
1357   }
1358 
1359   if (!TimeFunction(&results, [&]() -> bool {
1360         uint8_t *issue_msg = NULL;
1361         size_t msg_len;
1362         int ok = TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
1363                                                    &msg_len, batchsize);
1364         OPENSSL_free(issue_msg);
1365         // Clear pretokens.
1366         sk_TRUST_TOKEN_PRETOKEN_pop_free(client->pretokens,
1367                                          TRUST_TOKEN_PRETOKEN_free);
1368         client->pretokens = sk_TRUST_TOKEN_PRETOKEN_new_null();
1369         return ok;
1370       })) {
1371     fprintf(stderr, "TRUST_TOKEN_CLIENT_begin_issuance failed.\n");
1372     return false;
1373   }
1374   results.Print(name + " begin_issuance");
1375 
1376   uint8_t *issue_msg = NULL;
1377   size_t msg_len;
1378   if (!TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg, &msg_len,
1379                                          batchsize)) {
1380     fprintf(stderr, "TRUST_TOKEN_CLIENT_begin_issuance failed.\n");
1381     return false;
1382   }
1383   bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
1384 
1385   bssl::UniquePtr<STACK_OF(TRUST_TOKEN_PRETOKEN)> pretokens(
1386       sk_TRUST_TOKEN_PRETOKEN_deep_copy(client->pretokens,
1387                                         trust_token_pretoken_dup,
1388                                         TRUST_TOKEN_PRETOKEN_free));
1389 
1390   if (!TimeFunction(&results, [&]() -> bool {
1391         uint8_t *issue_resp = NULL;
1392         size_t resp_len, tokens_issued;
1393         int ok = TRUST_TOKEN_ISSUER_issue(issuer.get(), &issue_resp, &resp_len,
1394                                           &tokens_issued, issue_msg, msg_len,
1395                                           /*public_metadata=*/0,
1396                                           /*private_metadata=*/0,
1397                                           /*max_issuance=*/batchsize);
1398         OPENSSL_free(issue_resp);
1399         return ok;
1400       })) {
1401     fprintf(stderr, "TRUST_TOKEN_ISSUER_issue failed.\n");
1402     return false;
1403   }
1404   results.Print(name + " issue");
1405 
1406   uint8_t *issue_resp = NULL;
1407   size_t resp_len, tokens_issued;
1408   if (!TRUST_TOKEN_ISSUER_issue(issuer.get(), &issue_resp, &resp_len,
1409                                 &tokens_issued, issue_msg, msg_len,
1410                                 /*public_metadata=*/0, /*private_metadata=*/0,
1411                                 /*max_issuance=*/batchsize)) {
1412     fprintf(stderr, "TRUST_TOKEN_ISSUER_issue failed.\n");
1413     return false;
1414   }
1415   bssl::UniquePtr<uint8_t> free_issue_resp(issue_resp);
1416 
1417   if (!TimeFunction(&results, [&]() -> bool {
1418         size_t key_index2;
1419         bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
1420             TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index2,
1421                                                issue_resp, resp_len));
1422 
1423         // Reset pretokens.
1424         client->pretokens = sk_TRUST_TOKEN_PRETOKEN_deep_copy(
1425             pretokens.get(), trust_token_pretoken_dup,
1426             TRUST_TOKEN_PRETOKEN_free);
1427         return !!tokens;
1428       })) {
1429     fprintf(stderr, "TRUST_TOKEN_CLIENT_finish_issuance failed.\n");
1430     return false;
1431   }
1432   results.Print(name + " finish_issuance");
1433 
1434   bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
1435       TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
1436                                          resp_len));
1437   if (!tokens || sk_TRUST_TOKEN_num(tokens.get()) < 1) {
1438     fprintf(stderr, "TRUST_TOKEN_CLIENT_finish_issuance failed.\n");
1439     return false;
1440   }
1441 
1442   const TRUST_TOKEN *token = sk_TRUST_TOKEN_value(tokens.get(), 0);
1443 
1444   const uint8_t kClientData[] = "\x70TEST CLIENT DATA";
1445   uint64_t kRedemptionTime = 13374242;
1446 
1447   if (!TimeFunction(&results, [&]() -> bool {
1448         uint8_t *redeem_msg = NULL;
1449         size_t redeem_msg_len;
1450         int ok = TRUST_TOKEN_CLIENT_begin_redemption(
1451             client.get(), &redeem_msg, &redeem_msg_len, token, kClientData,
1452             sizeof(kClientData) - 1, kRedemptionTime);
1453         OPENSSL_free(redeem_msg);
1454         return ok;
1455       })) {
1456     fprintf(stderr, "TRUST_TOKEN_CLIENT_begin_redemption failed.\n");
1457     return false;
1458   }
1459   results.Print(name + " begin_redemption");
1460 
1461   uint8_t *redeem_msg = NULL;
1462   size_t redeem_msg_len;
1463   if (!TRUST_TOKEN_CLIENT_begin_redemption(
1464           client.get(), &redeem_msg, &redeem_msg_len, token, kClientData,
1465           sizeof(kClientData) - 1, kRedemptionTime)) {
1466     fprintf(stderr, "TRUST_TOKEN_CLIENT_begin_redemption failed.\n");
1467     return false;
1468   }
1469   bssl::UniquePtr<uint8_t> free_redeem_msg(redeem_msg);
1470 
1471   if (!TimeFunction(&results, [&]() -> bool {
1472         uint32_t public_value;
1473         uint8_t private_value;
1474         TRUST_TOKEN *rtoken;
1475         uint8_t *client_data = NULL;
1476         size_t client_data_len;
1477         int ok = TRUST_TOKEN_ISSUER_redeem(
1478             issuer.get(), &public_value, &private_value, &rtoken, &client_data,
1479             &client_data_len, redeem_msg, redeem_msg_len);
1480         OPENSSL_free(client_data);
1481         TRUST_TOKEN_free(rtoken);
1482         return ok;
1483       })) {
1484     fprintf(stderr, "TRUST_TOKEN_ISSUER_redeem failed.\n");
1485     return false;
1486   }
1487   results.Print(name + " redeem");
1488 
1489   uint32_t public_value;
1490   uint8_t private_value;
1491   TRUST_TOKEN *rtoken;
1492   uint8_t *client_data = NULL;
1493   size_t client_data_len;
1494   if (!TRUST_TOKEN_ISSUER_redeem(issuer.get(), &public_value, &private_value,
1495                                  &rtoken, &client_data, &client_data_len,
1496                                  redeem_msg, redeem_msg_len)) {
1497     fprintf(stderr, "TRUST_TOKEN_ISSUER_redeem failed.\n");
1498     return false;
1499   }
1500   bssl::UniquePtr<uint8_t> free_client_data(client_data);
1501   bssl::UniquePtr<TRUST_TOKEN> free_rtoken(rtoken);
1502 
1503   return true;
1504 }
1505 
1506 #if defined(BORINGSSL_FIPS)
SpeedSelfTest(const std::string & selected)1507 static bool SpeedSelfTest(const std::string &selected) {
1508   if (!selected.empty() && selected.find("self-test") == std::string::npos) {
1509     return true;
1510   }
1511 
1512   TimeResults results;
1513   if (!TimeFunction(&results, []() -> bool { return BORINGSSL_self_test(); })) {
1514     fprintf(stderr, "BORINGSSL_self_test faileid.\n");
1515     ERR_print_errors_fp(stderr);
1516     return false;
1517   }
1518 
1519   results.Print("self-test");
1520   return true;
1521 }
1522 #endif
1523 
1524 static const struct argument kArguments[] = {
1525     {
1526         "-filter",
1527         kOptionalArgument,
1528         "A filter on the speed tests to run",
1529     },
1530     {
1531         "-timeout",
1532         kOptionalArgument,
1533         "The number of seconds to run each test for (default is 1)",
1534     },
1535     {
1536         "-chunks",
1537         kOptionalArgument,
1538         "A comma-separated list of input sizes to run tests at (default is "
1539         "16,256,1350,8192,16384)",
1540     },
1541     {
1542         "-json",
1543         kBooleanArgument,
1544         "If this flag is set, speed will print the output of each benchmark in "
1545         "JSON format as follows: \"{\"description\": "
1546         "\"descriptionOfOperation\", \"numCalls\": 1234, "
1547         "\"timeInMicroseconds\": 1234567, \"bytesPerCall\": 1234}\". When "
1548         "there is no information about the bytes per call for an  operation, "
1549         "the JSON field for bytesPerCall will be omitted.",
1550     },
1551 #if defined(OPENSSL_THREADS)
1552     {
1553         "-threads",
1554         kOptionalArgument,
1555         "The number of threads to benchmark in parallel (default is 1)",
1556     },
1557 #endif
1558     {
1559         "",
1560         kOptionalArgument,
1561         "",
1562     },
1563 };
1564 
Speed(const std::vector<std::string> & args)1565 bool Speed(const std::vector<std::string> &args) {
1566   std::map<std::string, std::string> args_map;
1567   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
1568     PrintUsage(kArguments);
1569     return false;
1570   }
1571 
1572   std::string selected;
1573   if (args_map.count("-filter") != 0) {
1574     selected = args_map["-filter"];
1575   }
1576 
1577   if (args_map.count("-json") != 0) {
1578     g_print_json = true;
1579   }
1580 
1581   if (args_map.count("-timeout") != 0) {
1582     g_timeout_seconds = atoi(args_map["-timeout"].c_str());
1583   }
1584 
1585 #if defined(OPENSSL_THREADS)
1586   if (args_map.count("-threads") != 0) {
1587     g_threads = atoi(args_map["-threads"].c_str());
1588   }
1589 #endif
1590 
1591   if (args_map.count("-chunks") != 0) {
1592     g_chunk_lengths.clear();
1593     const char *start = args_map["-chunks"].data();
1594     const char *end = start + args_map["-chunks"].size();
1595     while (start != end) {
1596       errno = 0;
1597       char *ptr;
1598       unsigned long long val = strtoull(start, &ptr, 10);
1599       if (ptr == start /* no numeric characters found */ ||
1600           errno == ERANGE /* overflow */ || static_cast<size_t>(val) != val) {
1601         fprintf(stderr, "Error parsing -chunks argument\n");
1602         return false;
1603       }
1604       g_chunk_lengths.push_back(static_cast<size_t>(val));
1605       start = ptr;
1606       if (start != end) {
1607         if (*start != ',') {
1608           fprintf(stderr, "Error parsing -chunks argument\n");
1609           return false;
1610         }
1611         start++;
1612       }
1613     }
1614   }
1615 
1616   // kTLSADLen is the number of bytes of additional data that TLS passes to
1617   // AEADs.
1618   static const size_t kTLSADLen = 13;
1619   // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
1620   // These are AEADs that weren't originally defined as AEADs, but which we use
1621   // via the AEAD interface. In order for that to work, they have some TLS
1622   // knowledge in them and construct a couple of the AD bytes internally.
1623   static const size_t kLegacyADLen = kTLSADLen - 2;
1624 
1625   if (g_print_json) {
1626     puts("[");
1627   }
1628   if (!SpeedRSA(selected) ||
1629       !SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen, selected) ||
1630       !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen, selected) ||
1631       !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen,
1632                  selected) ||
1633       !SpeedAEAD(EVP_aead_des_ede3_cbc_sha1_tls(), "DES-EDE3-CBC-SHA1",
1634                  kLegacyADLen, selected) ||
1635       !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
1636                  kLegacyADLen, selected) ||
1637       !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
1638                  kLegacyADLen, selected) ||
1639       !SpeedAEADOpen(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
1640                      kLegacyADLen, selected) ||
1641       !SpeedAEADOpen(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
1642                      kLegacyADLen, selected) ||
1643       !SpeedAEAD(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
1644                  selected) ||
1645       !SpeedAEAD(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
1646                  selected) ||
1647       !SpeedAEADOpen(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
1648                      selected) ||
1649       !SpeedAEADOpen(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
1650                      selected) ||
1651       !SpeedAEAD(EVP_aead_aes_128_ccm_bluetooth(), "AES-128-CCM-Bluetooth",
1652                  kTLSADLen, selected) ||
1653       !SpeedAESBlock("AES-128", 128, selected) ||
1654       !SpeedAESBlock("AES-256", 256, selected) ||
1655       !SpeedHash(EVP_sha1(), "SHA-1", selected) ||
1656       !SpeedHash(EVP_sha256(), "SHA-256", selected) ||
1657       !SpeedHash(EVP_sha512(), "SHA-512", selected) ||
1658       !SpeedHash(EVP_blake2b256(), "BLAKE2b-256", selected) ||
1659       !SpeedRandom(selected) ||      //
1660       !SpeedECDH(selected) ||        //
1661       !SpeedECDSA(selected) ||       //
1662       !Speed25519(selected) ||       //
1663       !SpeedSPAKE2(selected) ||      //
1664       !SpeedScrypt(selected) ||      //
1665       !SpeedRSAKeyGen(selected) ||   //
1666       !SpeedHRSS(selected) ||        //
1667       !SpeedKyber(selected) ||       //
1668       !SpeedSpx(selected) ||         //
1669       !SpeedHashToCurve(selected) || //
1670       !SpeedTrustToken("TrustToken-Exp1-Batch1", TRUST_TOKEN_experiment_v1(), 1,
1671                        selected) ||
1672       !SpeedTrustToken("TrustToken-Exp1-Batch10", TRUST_TOKEN_experiment_v1(),
1673                        10, selected) ||
1674       !SpeedTrustToken("TrustToken-Exp2VOPRF-Batch1",
1675                        TRUST_TOKEN_experiment_v2_voprf(), 1, selected) ||
1676       !SpeedTrustToken("TrustToken-Exp2VOPRF-Batch10",
1677                        TRUST_TOKEN_experiment_v2_voprf(), 10, selected) ||
1678       !SpeedTrustToken("TrustToken-Exp2PMB-Batch1",
1679                        TRUST_TOKEN_experiment_v2_pmb(), 1, selected) ||
1680       !SpeedTrustToken("TrustToken-Exp2PMB-Batch10",
1681                        TRUST_TOKEN_experiment_v2_pmb(), 10, selected) ||
1682       !SpeedBase64(selected) || //
1683       !SpeedSipHash(selected)) {
1684     return false;
1685   }
1686 #if defined(BORINGSSL_FIPS)
1687   if (!SpeedSelfTest(selected)) {
1688     return false;
1689   }
1690 #endif
1691   if (g_print_json) {
1692     puts("\n]");
1693   }
1694 
1695   return true;
1696 }
1697