blob: 8b4b13c6b9e181107d9b6fb9f993334a01143b5a [file] [log] [blame]
Adam Langleyc5c0c7e2014-06-20 12:00:00 -07001/* 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
Adam Langleya0f1c8e2018-03-30 13:43:59 -070015#include <algorithm>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070016#include <functional>
17#include <memory>
Zola Bridgesf10ea552019-10-01 11:35:44 -070018#include <string>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070019#include <vector>
20
Adam Langleya0f1c8e2018-03-30 13:43:59 -070021#include <assert.h>
David Benjamin64431732019-02-10 22:07:23 +000022#include <errno.h>
David Benjamin1a46f8f2022-11-23 13:10:15 -050023#include <inttypes.h>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070024#include <stdint.h>
David Benjaminbcb65b92016-08-14 22:06:49 -040025#include <stdlib.h>
Adam Langley2b2d66d2015-01-30 17:08:37 -080026#include <string.h>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070027
Adam Langley92b6b022015-04-16 14:01:33 -070028#include <openssl/aead.h>
David Benjamin25e36da2019-08-31 13:25:15 -040029#include <openssl/aes.h>
David Benjaminf9587272021-09-21 16:33:15 -040030#include <openssl/base64.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070031#include <openssl/bn.h>
Sophie Schmieg58472cc2023-03-07 00:39:31 +000032#include <openssl/bytestring.h>
David Benjaminab5edbe2021-01-27 16:49:50 -050033#include <openssl/crypto.h>
Sophie Schmieg58472cc2023-03-07 00:39:31 +000034#include <openssl/curve25519.h>
Adam Langley92b6b022015-04-16 14:01:33 -070035#include <openssl/digest.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070036#include <openssl/ec.h>
Matt Braithwaited17d74d2016-08-17 20:10:28 -070037#include <openssl/ec_key.h>
Sophie Schmieg58472cc2023-03-07 00:39:31 +000038#include <openssl/ecdsa.h>
39#include <openssl/err.h>
David Benjaminb5292532017-06-09 19:27:37 -040040#include <openssl/evp.h>
Adam Langley7b935932018-11-12 13:53:42 -080041#include <openssl/hrss.h>
Sophie Schmieg58472cc2023-03-07 00:39:31 +000042#include <openssl/kyber.h>
Steven Valdez188b65a2020-04-21 14:31:05 -040043#include <openssl/mem.h>
David Benjamin98193672016-03-25 18:07:11 -040044#include <openssl/nid.h>
Adam Langley92b6b022015-04-16 14:01:33 -070045#include <openssl/rand.h>
46#include <openssl/rsa.h>
David Benjamin345c86b2022-01-23 11:11:17 -050047#include <openssl/siphash.h>
Steven Valdez188b65a2020-04-21 14:31:05 -040048#include <openssl/trust_token.h>
Adam Langley92b6b022015-04-16 14:01:33 -070049
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070050#if defined(OPENSSL_WINDOWS)
David Benjamina353cdb2016-06-09 16:48:33 -040051OPENSSL_MSVC_PRAGMA(warning(push, 3))
Adam Langley3e719312015-03-20 16:32:23 -070052#include <windows.h>
David Benjamina353cdb2016-06-09 16:48:33 -040053OPENSSL_MSVC_PRAGMA(warning(pop))
Adam Langley30eda1d2014-06-24 11:15:12 -070054#elif defined(OPENSSL_APPLE)
55#include <sys/time.h>
David Benjamin2f401ec2016-09-09 19:49:35 -040056#else
57#include <time.h>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070058#endif
59
David Benjaminc1f5d792023-03-03 23:49:38 -050060#if defined(OPENSSL_THREADS)
61#include <condition_variable>
62#include <mutex>
63#include <thread>
64#endif
65
Steven Valdez188b65a2020-04-21 14:31:05 -040066#include "../crypto/ec_extra/internal.h"
67#include "../crypto/fipsmodule/ec/internal.h"
David Benjamin17cf2cb2016-12-13 01:07:13 -050068#include "../crypto/internal.h"
Steven Valdez188b65a2020-04-21 14:31:05 -040069#include "../crypto/trust_token/internal.h"
David Benjamin58084af2015-06-07 00:25:15 -040070#include "internal.h"
Adam Langleyad6b28e2015-04-14 12:07:44 -070071
Zola Bridgesf10ea552019-10-01 11:35:44 -070072// g_print_json is true if printed output is JSON formatted.
73static bool g_print_json = false;
Adam Langley2b2d66d2015-01-30 17:08:37 -080074
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070075// TimeResults represents the results of benchmarking a function.
76struct TimeResults {
77 // num_calls is the number of function calls done in the time period.
David Benjamin1a46f8f2022-11-23 13:10:15 -050078 uint64_t num_calls;
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070079 // us is the number of microseconds that elapsed in the time period.
David Benjamin1a46f8f2022-11-23 13:10:15 -050080 uint64_t us;
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070081
Zola Bridgesf10ea552019-10-01 11:35:44 -070082 void Print(const std::string &description) const {
83 if (g_print_json) {
84 PrintJSON(description);
85 } else {
David Benjamin1a46f8f2022-11-23 13:10:15 -050086 printf(
87 "Did %" PRIu64 " %s operations in %" PRIu64 "us (%.1f ops/sec)\n",
88 num_calls, description.c_str(), us,
89 (static_cast<double>(num_calls) / static_cast<double>(us)) * 1000000);
Zola Bridgesf10ea552019-10-01 11:35:44 -070090 }
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070091 }
92
Zola Bridgesf10ea552019-10-01 11:35:44 -070093 void PrintWithBytes(const std::string &description,
94 size_t bytes_per_call) const {
95 if (g_print_json) {
96 PrintJSON(description, bytes_per_call);
97 } else {
David Benjamin1a46f8f2022-11-23 13:10:15 -050098 printf(
99 "Did %" PRIu64 " %s operations in %" PRIu64
100 "us (%.1f ops/sec): %.1f MB/s\n",
101 num_calls, description.c_str(), us,
102 (static_cast<double>(num_calls) / static_cast<double>(us)) * 1000000,
103 static_cast<double>(bytes_per_call * num_calls) /
104 static_cast<double>(us));
Zola Bridgesf10ea552019-10-01 11:35:44 -0700105 }
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700106 }
Zola Bridgesf10ea552019-10-01 11:35:44 -0700107
108 private:
109 void PrintJSON(const std::string &description,
110 size_t bytes_per_call = 0) const {
111 if (first_json_printed) {
112 puts(",");
113 }
114
David Benjamin1a46f8f2022-11-23 13:10:15 -0500115 printf("{\"description\": \"%s\", \"numCalls\": %" PRIu64
116 ", \"microseconds\": %" PRIu64,
Zola Bridgesf10ea552019-10-01 11:35:44 -0700117 description.c_str(), num_calls, us);
118
119 if (bytes_per_call > 0) {
120 printf(", \"bytesPerCall\": %zu", bytes_per_call);
121 }
122
123 printf("}");
124 first_json_printed = true;
125 }
126
127 // first_json_printed is true if |g_print_json| is true and the first item in
128 // the JSON results has been printed already. This is used to handle the
129 // commas between each item in the result list.
130 static bool first_json_printed;
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700131};
132
Zola Bridgesf10ea552019-10-01 11:35:44 -0700133bool TimeResults::first_json_printed = false;
134
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700135#if defined(OPENSSL_WINDOWS)
136static uint64_t time_now() { return GetTickCount64() * 1000; }
Adam Langley30eda1d2014-06-24 11:15:12 -0700137#elif defined(OPENSSL_APPLE)
138static uint64_t time_now() {
139 struct timeval tv;
140 uint64_t ret;
141
142 gettimeofday(&tv, NULL);
143 ret = tv.tv_sec;
144 ret *= 1000000;
145 ret += tv.tv_usec;
146 return ret;
147}
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700148#else
149static uint64_t time_now() {
150 struct timespec ts;
151 clock_gettime(CLOCK_MONOTONIC, &ts);
152
153 uint64_t ret = ts.tv_sec;
154 ret *= 1000000;
155 ret += ts.tv_nsec / 1000;
156 return ret;
157}
158#endif
159
David Benjaminbcb65b92016-08-14 22:06:49 -0400160static uint64_t g_timeout_seconds = 1;
David Benjamin5501a262019-03-20 17:45:15 -0500161static std::vector<size_t> g_chunk_lengths = {16, 256, 1350, 8192, 16384};
David Benjaminbcb65b92016-08-14 22:06:49 -0400162
David Benjaminc1f5d792023-03-03 23:49:38 -0500163// IterationsBetweenTimeChecks returns the number of iterations of |func| to run
164// in between checking the time, or zero on error.
165static uint32_t IterationsBetweenTimeChecks(std::function<bool()> func) {
166 uint64_t start = time_now();
167 if (!func()) {
168 return 0;
169 }
170 uint64_t delta = time_now() - start;
171 if (delta == 0) {
172 return 250;
173 }
174
175 // Aim for about 100ms between time checks.
176 uint32_t ret = static_cast<double>(100000) / static_cast<double>(delta);
177 if (ret > 1000) {
178 ret = 1000;
179 } else if (ret < 1) {
180 ret = 1;
181 }
182 return ret;
183}
184
185static bool TimeFunctionImpl(TimeResults *results, std::function<bool()> func,
186 uint32_t iterations_between_time_checks) {
David Benjaminbcb65b92016-08-14 22:06:49 -0400187 // total_us is the total amount of time that we'll aim to measure a function
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700188 // for.
David Benjaminbcb65b92016-08-14 22:06:49 -0400189 const uint64_t total_us = g_timeout_seconds * 1000000;
David Benjaminc1f5d792023-03-03 23:49:38 -0500190 uint64_t start = time_now(), now;
David Benjamin1a46f8f2022-11-23 13:10:15 -0500191 uint64_t done = 0;
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700192 for (;;) {
David Benjaminc1f5d792023-03-03 23:49:38 -0500193 for (uint32_t i = 0; i < iterations_between_time_checks; i++) {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700194 if (!func()) {
195 return false;
196 }
197 done++;
198 }
199
200 now = time_now();
David Benjaminbcb65b92016-08-14 22:06:49 -0400201 if (now - start > total_us) {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700202 break;
203 }
204 }
205
206 results->us = now - start;
207 results->num_calls = done;
208 return true;
209}
210
David Benjaminc1f5d792023-03-03 23:49:38 -0500211static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
212 uint32_t iterations_between_time_checks = IterationsBetweenTimeChecks(func);
213 if (iterations_between_time_checks == 0) {
214 return false;
215 }
216
217 return TimeFunctionImpl(results, std::move(func),
218 iterations_between_time_checks);
219}
220
221#if defined(OPENSSL_THREADS)
222// g_threads is the number of threads to run in parallel benchmarks.
223static int g_threads = 1;
224
225// Latch behaves like C++20 std::latch.
226class Latch {
227 public:
228 explicit Latch(int expected) : expected_(expected) {}
229 Latch(const Latch &) = delete;
230 Latch &operator=(const Latch &) = delete;
231
232 void ArriveAndWait() {
233 std::unique_lock<std::mutex> lock(lock_);
234 expected_--;
235 if (expected_ > 0) {
236 cond_.wait(lock, [&] { return expected_ == 0; });
237 } else {
238 cond_.notify_all();
239 }
240 }
241
242 private:
243 int expected_;
244 std::mutex lock_;
245 std::condition_variable cond_;
246};
247
248static bool TimeFunctionParallel(TimeResults *results,
249 std::function<bool()> func) {
250 if (g_threads <= 1) {
251 return TimeFunction(results, std::move(func));
252 }
253
254 uint32_t iterations_between_time_checks = IterationsBetweenTimeChecks(func);
255 if (iterations_between_time_checks == 0) {
256 return false;
257 }
258
259 struct ThreadResult {
260 TimeResults time_result;
261 bool ok = false;
262 };
263 std::vector<ThreadResult> thread_results(g_threads);
264 Latch latch(g_threads);
265 std::vector<std::thread> threads;
266 for (int i = 0; i < g_threads; i++) {
267 threads.emplace_back([&, i] {
268 // Wait for all the threads to be ready before running the benchmark.
269 latch.ArriveAndWait();
270 thread_results[i].ok = TimeFunctionImpl(
271 &thread_results[i].time_result, func, iterations_between_time_checks);
272 });
273 }
274
275 for (auto &thread : threads) {
276 thread.join();
277 }
278
279 results->num_calls = 0;
280 results->us = 0;
281 for (const auto& pair : thread_results) {
282 if (!pair.ok) {
283 return false;
284 }
285 results->num_calls += pair.time_result.num_calls;
286 results->us += pair.time_result.us;
287 }
288 return true;
289}
290
291#else
292static bool TimeFunctionParallel(TimeResults *results,
293 std::function<bool()> func) {
294 return TimeFunction(results, std::move(func));
295}
296#endif
297
Daniel Hirche1414d862018-04-13 19:09:25 +0200298static bool SpeedRSA(const std::string &selected) {
299 if (!selected.empty() && selected.find("RSA") == std::string::npos) {
Adam Langley90b58402015-04-13 11:04:18 -0700300 return true;
301 }
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700302
Daniel Hirche1414d862018-04-13 19:09:25 +0200303 static const struct {
304 const char *name;
305 const uint8_t *key;
306 const size_t key_len;
307 } kRSAKeys[] = {
308 {"RSA 2048", kDERRSAPrivate2048, kDERRSAPrivate2048Len},
309 {"RSA 4096", kDERRSAPrivate4096, kDERRSAPrivate4096Len},
310 };
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700311
David Benjamin1a46f8f2022-11-23 13:10:15 -0500312 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRSAKeys); i++) {
Daniel Hirche1414d862018-04-13 19:09:25 +0200313 const std::string name = kRSAKeys[i].name;
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700314
Daniel Hirche1414d862018-04-13 19:09:25 +0200315 bssl::UniquePtr<RSA> key(
316 RSA_private_key_from_bytes(kRSAKeys[i].key, kRSAKeys[i].key_len));
317 if (key == nullptr) {
318 fprintf(stderr, "Failed to parse %s key.\n", name.c_str());
319 ERR_print_errors_fp(stderr);
320 return false;
321 }
David Benjaminf11ea192018-04-09 20:17:20 -0400322
David Benjaminc1f5d792023-03-03 23:49:38 -0500323 static constexpr size_t kMaxSignature = 512;
324 if (RSA_size(key.get()) > kMaxSignature) {
325 abort();
326 }
Daniel Hirche1414d862018-04-13 19:09:25 +0200327 const uint8_t fake_sha256_hash[32] = {0};
Daniel Hirche1414d862018-04-13 19:09:25 +0200328
329 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500330 if (!TimeFunctionParallel(&results, [&key, &fake_sha256_hash]() -> bool {
331 // Usually during RSA signing we're using a long-lived |RSA| that
332 // has already had all of its |BN_MONT_CTX|s constructed, so it
333 // makes sense to use |key| directly here.
334 uint8_t out[kMaxSignature];
335 unsigned out_len;
336 return RSA_sign(NID_sha256, fake_sha256_hash,
337 sizeof(fake_sha256_hash), out, &out_len, key.get());
Daniel Hirche1414d862018-04-13 19:09:25 +0200338 })) {
339 fprintf(stderr, "RSA_sign failed.\n");
340 ERR_print_errors_fp(stderr);
341 return false;
342 }
343 results.Print(name + " signing");
344
David Benjaminc1f5d792023-03-03 23:49:38 -0500345 uint8_t sig[kMaxSignature];
346 unsigned sig_len;
347 if (!RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash), sig,
348 &sig_len, key.get())) {
349 return false;
350 }
351 if (!TimeFunctionParallel(
352 &results, [&key, &fake_sha256_hash, &sig, sig_len]() -> bool {
353 return RSA_verify(NID_sha256, fake_sha256_hash,
354 sizeof(fake_sha256_hash), sig, sig_len,
355 key.get());
356 })) {
Daniel Hirche1414d862018-04-13 19:09:25 +0200357 fprintf(stderr, "RSA_verify failed.\n");
358 ERR_print_errors_fp(stderr);
359 return false;
360 }
361 results.Print(name + " verify (same key)");
362
David Benjaminc1f5d792023-03-03 23:49:38 -0500363 if (!TimeFunctionParallel(
364 &results, [&key, &fake_sha256_hash, &sig, sig_len]() -> bool {
365 // Usually during RSA verification we have to parse an RSA key
366 // from a certificate or similar, in which case we'd need to
367 // construct a new RSA key, with a new |BN_MONT_CTX| for the
368 // public modulus. If we were to use |key| directly instead, then
369 // these costs wouldn't be accounted for.
David Benjamind4553e02023-06-03 01:11:16 -0400370 bssl::UniquePtr<RSA> verify_key(RSA_new_public_key(
371 RSA_get0_n(key.get()), RSA_get0_e(key.get())));
David Benjaminc1f5d792023-03-03 23:49:38 -0500372 if (!verify_key) {
373 return false;
374 }
David Benjaminc1f5d792023-03-03 23:49:38 -0500375 return RSA_verify(NID_sha256, fake_sha256_hash,
376 sizeof(fake_sha256_hash), sig, sig_len,
377 verify_key.get());
378 })) {
Daniel Hirche1414d862018-04-13 19:09:25 +0200379 fprintf(stderr, "RSA_verify failed.\n");
380 ERR_print_errors_fp(stderr);
381 return false;
382 }
383 results.Print(name + " verify (fresh key)");
David Benjamin417010f2021-06-30 17:41:42 -0400384
David Benjaminc1f5d792023-03-03 23:49:38 -0500385 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjamin417010f2021-06-30 17:41:42 -0400386 return bssl::UniquePtr<RSA>(RSA_private_key_from_bytes(
387 kRSAKeys[i].key, kRSAKeys[i].key_len)) != nullptr;
388 })) {
389 fprintf(stderr, "Failed to parse %s key.\n", name.c_str());
390 ERR_print_errors_fp(stderr);
391 return false;
392 }
393 results.Print(name + " private key parse");
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700394 }
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700395
396 return true;
397}
398
Adam Langleya0f1c8e2018-03-30 13:43:59 -0700399static bool SpeedRSAKeyGen(const std::string &selected) {
400 // Don't run this by default because it's so slow.
401 if (selected != "RSAKeyGen") {
402 return true;
403 }
404
405 bssl::UniquePtr<BIGNUM> e(BN_new());
406 if (!BN_set_word(e.get(), 65537)) {
407 return false;
408 }
409
410 const std::vector<int> kSizes = {2048, 3072, 4096};
411 for (int size : kSizes) {
412 const uint64_t start = time_now();
David Benjamin1a46f8f2022-11-23 13:10:15 -0500413 uint64_t num_calls = 0;
414 uint64_t us;
415 std::vector<uint64_t> durations;
Adam Langleya0f1c8e2018-03-30 13:43:59 -0700416
417 for (;;) {
418 bssl::UniquePtr<RSA> rsa(RSA_new());
419
420 const uint64_t iteration_start = time_now();
421 if (!RSA_generate_key_ex(rsa.get(), size, e.get(), nullptr)) {
422 fprintf(stderr, "RSA_generate_key_ex failed.\n");
423 ERR_print_errors_fp(stderr);
424 return false;
425 }
426 const uint64_t iteration_end = time_now();
427
428 num_calls++;
429 durations.push_back(iteration_end - iteration_start);
430
431 us = iteration_end - start;
432 if (us > 30 * 1000000 /* 30 secs */) {
433 break;
434 }
435 }
436
437 std::sort(durations.begin(), durations.end());
Zola Bridgesf10ea552019-10-01 11:35:44 -0700438 const std::string description =
439 std::string("RSA ") + std::to_string(size) + std::string(" key-gen");
440 const TimeResults results = {num_calls, us};
441 results.Print(description);
Adam Langleya0f1c8e2018-03-30 13:43:59 -0700442 const size_t n = durations.size();
443 assert(n > 0);
David Benjamin64431732019-02-10 22:07:23 +0000444
Zola Bridgesf10ea552019-10-01 11:35:44 -0700445 // Distribution information is useful, but doesn't fit into the standard
446 // format used by |g_print_json|.
447 if (!g_print_json) {
David Benjamin1a46f8f2022-11-23 13:10:15 -0500448 uint64_t min = durations[0];
449 uint64_t median = n & 1 ? durations[n / 2]
Zola Bridgesf10ea552019-10-01 11:35:44 -0700450 : (durations[n / 2 - 1] + durations[n / 2]) / 2;
David Benjamin1a46f8f2022-11-23 13:10:15 -0500451 uint64_t max = durations[n - 1];
452 printf(" min: %" PRIu64 "us, median: %" PRIu64 "us, max: %" PRIu64
453 "us\n",
454 min, median, max);
Zola Bridgesf10ea552019-10-01 11:35:44 -0700455 }
Adam Langleya0f1c8e2018-03-30 13:43:59 -0700456 }
457
458 return true;
459}
460
David Benjamin64431732019-02-10 22:07:23 +0000461static std::string ChunkLenSuffix(size_t chunk_len) {
462 char buf[32];
463 snprintf(buf, sizeof(buf), " (%zu byte%s)", chunk_len,
464 chunk_len != 1 ? "s" : "");
465 return buf;
466}
467
468static bool SpeedAEADChunk(const EVP_AEAD *aead, std::string name,
Adam Langleyba9557d2017-02-27 13:53:23 -0800469 size_t chunk_len, size_t ad_len,
470 evp_aead_direction_t direction) {
Adam Langley26725342015-01-28 15:52:57 -0800471 static const unsigned kAlignment = 16;
472
David Benjamin64431732019-02-10 22:07:23 +0000473 name += ChunkLenSuffix(chunk_len);
David Benjamin0cce8632016-10-20 15:13:26 -0400474 bssl::ScopedEVP_AEAD_CTX ctx;
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700475 const size_t key_len = EVP_AEAD_key_length(aead);
476 const size_t nonce_len = EVP_AEAD_nonce_length(aead);
477 const size_t overhead_len = EVP_AEAD_max_overhead(aead);
478
479 std::unique_ptr<uint8_t[]> key(new uint8_t[key_len]);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500480 OPENSSL_memset(key.get(), 0, key_len);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700481 std::unique_ptr<uint8_t[]> nonce(new uint8_t[nonce_len]);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500482 OPENSSL_memset(nonce.get(), 0, nonce_len);
Brian Smith1d1562d2015-03-17 00:32:20 -1000483 std::unique_ptr<uint8_t[]> in_storage(new uint8_t[chunk_len + kAlignment]);
Martin Kreichgauerdc110f52017-08-02 15:40:09 -0700484 // N.B. for EVP_AEAD_CTX_seal_scatter the input and output buffers may be the
485 // same size. However, in the direction == evp_aead_open case we still use
486 // non-scattering seal, hence we add overhead_len to the size of this buffer.
487 std::unique_ptr<uint8_t[]> out_storage(
488 new uint8_t[chunk_len + overhead_len + kAlignment]);
David Benjaminc93724b2018-05-21 17:14:05 -0400489 std::unique_ptr<uint8_t[]> in2_storage(
490 new uint8_t[chunk_len + overhead_len + kAlignment]);
Adam Langleye7624342015-01-15 17:33:48 -0800491 std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
David Benjamin17cf2cb2016-12-13 01:07:13 -0500492 OPENSSL_memset(ad.get(), 0, ad_len);
Martin Kreichgauerdc110f52017-08-02 15:40:09 -0700493 std::unique_ptr<uint8_t[]> tag_storage(
494 new uint8_t[overhead_len + kAlignment]);
495
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700496
David Benjaminecc301c2021-07-02 12:30:40 -0400497 uint8_t *const in =
498 static_cast<uint8_t *>(align_pointer(in_storage.get(), kAlignment));
David Benjamin17cf2cb2016-12-13 01:07:13 -0500499 OPENSSL_memset(in, 0, chunk_len);
David Benjaminecc301c2021-07-02 12:30:40 -0400500 uint8_t *const out =
501 static_cast<uint8_t *>(align_pointer(out_storage.get(), kAlignment));
David Benjamin17cf2cb2016-12-13 01:07:13 -0500502 OPENSSL_memset(out, 0, chunk_len + overhead_len);
David Benjaminecc301c2021-07-02 12:30:40 -0400503 uint8_t *const tag =
504 static_cast<uint8_t *>(align_pointer(tag_storage.get(), kAlignment));
Martin Kreichgauerdc110f52017-08-02 15:40:09 -0700505 OPENSSL_memset(tag, 0, overhead_len);
David Benjaminecc301c2021-07-02 12:30:40 -0400506 uint8_t *const in2 =
507 static_cast<uint8_t *>(align_pointer(in2_storage.get(), kAlignment));
Adam Langley26725342015-01-28 15:52:57 -0800508
David Benjamin0cce8632016-10-20 15:13:26 -0400509 if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
David Benjamind434f282015-03-17 18:28:37 -0400510 EVP_AEAD_DEFAULT_TAG_LENGTH,
511 evp_aead_seal)) {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700512 fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
Brian Smith83a82982015-04-09 16:21:10 -1000513 ERR_print_errors_fp(stderr);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700514 return false;
515 }
516
David Benjaminc1f5d792023-03-03 23:49:38 -0500517 // TODO(davidben): In most cases, this can be |TimeFunctionParallel|, but a
518 // few stateful AEADs must be run serially.
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700519 TimeResults results;
Adam Langleyba9557d2017-02-27 13:53:23 -0800520 if (direction == evp_aead_seal) {
Martin Kreichgauerdc110f52017-08-02 15:40:09 -0700521 if (!TimeFunction(&results,
522 [chunk_len, nonce_len, ad_len, overhead_len, in, out, tag,
523 &ctx, &nonce, &ad]() -> bool {
524 size_t tag_len;
525 return EVP_AEAD_CTX_seal_scatter(
526 ctx.get(), out, tag, &tag_len, overhead_len,
527 nonce.get(), nonce_len, in, chunk_len, nullptr, 0,
528 ad.get(), ad_len);
529 })) {
Adam Langleyba9557d2017-02-27 13:53:23 -0800530 fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
531 ERR_print_errors_fp(stderr);
532 return false;
533 }
534 } else {
535 size_t out_len;
536 EVP_AEAD_CTX_seal(ctx.get(), out, &out_len, chunk_len + overhead_len,
537 nonce.get(), nonce_len, in, chunk_len, ad.get(), ad_len);
538
David Benjaminc93724b2018-05-21 17:14:05 -0400539 ctx.Reset();
540 if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
541 EVP_AEAD_DEFAULT_TAG_LENGTH,
542 evp_aead_open)) {
543 fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
544 ERR_print_errors_fp(stderr);
545 return false;
546 }
547
Martin Kreichgauerdc110f52017-08-02 15:40:09 -0700548 if (!TimeFunction(&results,
David Benjaminc93724b2018-05-21 17:14:05 -0400549 [chunk_len, overhead_len, nonce_len, ad_len, in2, out,
550 out_len, &ctx, &nonce, &ad]() -> bool {
Martin Kreichgauerdc110f52017-08-02 15:40:09 -0700551 size_t in2_len;
552 // N.B. EVP_AEAD_CTX_open_gather is not implemented for
553 // all AEADs.
David Benjaminc93724b2018-05-21 17:14:05 -0400554 return EVP_AEAD_CTX_open(ctx.get(), in2, &in2_len,
555 chunk_len + overhead_len,
556 nonce.get(), nonce_len, out,
557 out_len, ad.get(), ad_len);
Martin Kreichgauerdc110f52017-08-02 15:40:09 -0700558 })) {
Adam Langleyba9557d2017-02-27 13:53:23 -0800559 fprintf(stderr, "EVP_AEAD_CTX_open failed.\n");
560 ERR_print_errors_fp(stderr);
561 return false;
562 }
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700563 }
564
Adam Langleyba9557d2017-02-27 13:53:23 -0800565 results.PrintWithBytes(
566 name + (direction == evp_aead_seal ? " seal" : " open"), chunk_len);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700567 return true;
568}
569
Adam Langleye7624342015-01-15 17:33:48 -0800570static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
Adam Langley90b58402015-04-13 11:04:18 -0700571 size_t ad_len, const std::string &selected) {
572 if (!selected.empty() && name.find(selected) == std::string::npos) {
573 return true;
574 }
575
David Benjamin64431732019-02-10 22:07:23 +0000576 for (size_t chunk_len : g_chunk_lengths) {
577 if (!SpeedAEADChunk(aead, name, chunk_len, ad_len, evp_aead_seal)) {
578 return false;
579 }
580 }
581 return true;
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700582}
583
Adam Langleyba9557d2017-02-27 13:53:23 -0800584static bool SpeedAEADOpen(const EVP_AEAD *aead, const std::string &name,
585 size_t ad_len, const std::string &selected) {
586 if (!selected.empty() && name.find(selected) == std::string::npos) {
587 return true;
588 }
589
David Benjamin64431732019-02-10 22:07:23 +0000590 for (size_t chunk_len : g_chunk_lengths) {
591 if (!SpeedAEADChunk(aead, name, chunk_len, ad_len, evp_aead_open)) {
592 return false;
593 }
594 }
595
596 return true;
Adam Langleyba9557d2017-02-27 13:53:23 -0800597}
Adam Langleyba9557d2017-02-27 13:53:23 -0800598
David Benjamin25e36da2019-08-31 13:25:15 -0400599static bool SpeedAESBlock(const std::string &name, unsigned bits,
600 const std::string &selected) {
601 if (!selected.empty() && name.find(selected) == std::string::npos) {
602 return true;
603 }
604
605 static const uint8_t kZero[32] = {0};
606
607 {
608 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500609 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjamin25e36da2019-08-31 13:25:15 -0400610 AES_KEY key;
611 return AES_set_encrypt_key(kZero, bits, &key) == 0;
612 })) {
613 fprintf(stderr, "AES_set_encrypt_key failed.\n");
614 return false;
615 }
616 results.Print(name + " encrypt setup");
617 }
618
619 {
620 AES_KEY key;
621 if (AES_set_encrypt_key(kZero, bits, &key) != 0) {
622 return false;
623 }
624 uint8_t block[16] = {0};
625 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500626 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjamin25e36da2019-08-31 13:25:15 -0400627 AES_encrypt(block, block, &key);
628 return true;
629 })) {
630 fprintf(stderr, "AES_encrypt failed.\n");
631 return false;
632 }
633 results.Print(name + " encrypt");
634 }
635
636 {
637 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500638 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjamin25e36da2019-08-31 13:25:15 -0400639 AES_KEY key;
640 return AES_set_decrypt_key(kZero, bits, &key) == 0;
641 })) {
642 fprintf(stderr, "AES_set_decrypt_key failed.\n");
643 return false;
644 }
645 results.Print(name + " decrypt setup");
646 }
647
648 {
649 AES_KEY key;
650 if (AES_set_decrypt_key(kZero, bits, &key) != 0) {
651 return false;
652 }
653 uint8_t block[16] = {0};
654 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500655 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjamin25e36da2019-08-31 13:25:15 -0400656 AES_decrypt(block, block, &key);
657 return true;
658 })) {
659 fprintf(stderr, "AES_decrypt failed.\n");
660 return false;
661 }
662 results.Print(name + " decrypt");
663 }
664
665 return true;
666}
667
David Benjamin64431732019-02-10 22:07:23 +0000668static bool SpeedHashChunk(const EVP_MD *md, std::string name,
Adam Langley006779a2014-06-20 12:00:00 -0700669 size_t chunk_len) {
David Benjamin345c86b2022-01-23 11:11:17 -0500670 uint8_t input[16384] = {0};
Adam Langley006779a2014-06-20 12:00:00 -0700671
David Benjamin345c86b2022-01-23 11:11:17 -0500672 if (chunk_len > sizeof(input)) {
Adam Langley006779a2014-06-20 12:00:00 -0700673 return false;
674 }
675
David Benjamin64431732019-02-10 22:07:23 +0000676 name += ChunkLenSuffix(chunk_len);
Adam Langley006779a2014-06-20 12:00:00 -0700677 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500678 if (!TimeFunctionParallel(&results, [md, chunk_len, &input]() -> bool {
Adam Langley006779a2014-06-20 12:00:00 -0700679 uint8_t digest[EVP_MAX_MD_SIZE];
680 unsigned int md_len;
681
David Benjaminc1f5d792023-03-03 23:49:38 -0500682 bssl::ScopedEVP_MD_CTX ctx;
Daniel Hirche1414d862018-04-13 19:09:25 +0200683 return EVP_DigestInit_ex(ctx.get(), md, NULL /* ENGINE */) &&
David Benjamin345c86b2022-01-23 11:11:17 -0500684 EVP_DigestUpdate(ctx.get(), input, chunk_len) &&
Daniel Hirche1414d862018-04-13 19:09:25 +0200685 EVP_DigestFinal_ex(ctx.get(), digest, &md_len);
Adam Langley006779a2014-06-20 12:00:00 -0700686 })) {
687 fprintf(stderr, "EVP_DigestInit_ex failed.\n");
Brian Smith83a82982015-04-09 16:21:10 -1000688 ERR_print_errors_fp(stderr);
Adam Langley006779a2014-06-20 12:00:00 -0700689 return false;
690 }
691
692 results.PrintWithBytes(name, chunk_len);
Adam Langley006779a2014-06-20 12:00:00 -0700693 return true;
694}
David Benjamin64431732019-02-10 22:07:23 +0000695
Adam Langley90b58402015-04-13 11:04:18 -0700696static bool SpeedHash(const EVP_MD *md, const std::string &name,
697 const std::string &selected) {
698 if (!selected.empty() && name.find(selected) == std::string::npos) {
699 return true;
700 }
701
David Benjamin64431732019-02-10 22:07:23 +0000702 for (size_t chunk_len : g_chunk_lengths) {
703 if (!SpeedHashChunk(md, name, chunk_len)) {
704 return false;
705 }
706 }
707
708 return true;
Adam Langley006779a2014-06-20 12:00:00 -0700709}
710
David Benjamin64431732019-02-10 22:07:23 +0000711static bool SpeedRandomChunk(std::string name, size_t chunk_len) {
David Benjaminc1f5d792023-03-03 23:49:38 -0500712 static constexpr size_t kMaxChunk = 16384;
713 if (chunk_len > kMaxChunk) {
Adam Langley90b58402015-04-13 11:04:18 -0700714 return false;
715 }
716
David Benjamin64431732019-02-10 22:07:23 +0000717 name += ChunkLenSuffix(chunk_len);
Adam Langley90b58402015-04-13 11:04:18 -0700718 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500719 if (!TimeFunctionParallel(&results, [chunk_len]() -> bool {
720 uint8_t scratch[kMaxChunk];
Adam Langley90b58402015-04-13 11:04:18 -0700721 RAND_bytes(scratch, chunk_len);
722 return true;
723 })) {
724 return false;
725 }
726
727 results.PrintWithBytes(name, chunk_len);
728 return true;
729}
730
731static bool SpeedRandom(const std::string &selected) {
732 if (!selected.empty() && selected != "RNG") {
733 return true;
734 }
735
David Benjamin64431732019-02-10 22:07:23 +0000736 for (size_t chunk_len : g_chunk_lengths) {
737 if (!SpeedRandomChunk("RNG", chunk_len)) {
738 return false;
739 }
740 }
741
742 return true;
Adam Langley90b58402015-04-13 11:04:18 -0700743}
744
Adam Langleyad6b28e2015-04-14 12:07:44 -0700745static bool SpeedECDHCurve(const std::string &name, int nid,
746 const std::string &selected) {
747 if (!selected.empty() && name.find(selected) == std::string::npos) {
748 return true;
749 }
750
David Benjamin88b1a372018-03-31 23:56:13 -0400751 bssl::UniquePtr<EC_KEY> peer_key(EC_KEY_new_by_curve_name(nid));
752 if (!peer_key ||
753 !EC_KEY_generate_key(peer_key.get())) {
754 return false;
755 }
756
757 size_t peer_value_len = EC_POINT_point2oct(
758 EC_KEY_get0_group(peer_key.get()), EC_KEY_get0_public_key(peer_key.get()),
759 POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, nullptr);
760 if (peer_value_len == 0) {
761 return false;
762 }
763 std::unique_ptr<uint8_t[]> peer_value(new uint8_t[peer_value_len]);
764 peer_value_len = EC_POINT_point2oct(
765 EC_KEY_get0_group(peer_key.get()), EC_KEY_get0_public_key(peer_key.get()),
766 POINT_CONVERSION_UNCOMPRESSED, peer_value.get(), peer_value_len, nullptr);
767 if (peer_value_len == 0) {
768 return false;
769 }
770
Adam Langleyad6b28e2015-04-14 12:07:44 -0700771 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500772 if (!TimeFunctionParallel(
773 &results, [nid, peer_value_len, &peer_value]() -> bool {
774 bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
775 if (!key || !EC_KEY_generate_key(key.get())) {
776 return false;
777 }
778 const EC_GROUP *const group = EC_KEY_get0_group(key.get());
779 bssl::UniquePtr<EC_POINT> point(EC_POINT_new(group));
780 bssl::UniquePtr<EC_POINT> peer_point(EC_POINT_new(group));
781 bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new());
782 bssl::UniquePtr<BIGNUM> x(BN_new());
783 if (!point || !peer_point || !ctx || !x ||
784 !EC_POINT_oct2point(group, peer_point.get(), peer_value.get(),
785 peer_value_len, ctx.get()) ||
786 !EC_POINT_mul(group, point.get(), nullptr, peer_point.get(),
787 EC_KEY_get0_private_key(key.get()), ctx.get()) ||
788 !EC_POINT_get_affine_coordinates_GFp(
789 group, point.get(), x.get(), nullptr, ctx.get())) {
790 return false;
791 }
Adam Langleyad6b28e2015-04-14 12:07:44 -0700792
David Benjaminc1f5d792023-03-03 23:49:38 -0500793 return true;
794 })) {
Adam Langleyad6b28e2015-04-14 12:07:44 -0700795 return false;
796 }
797
798 results.Print(name);
799 return true;
800}
801
802static bool SpeedECDSACurve(const std::string &name, int nid,
803 const std::string &selected) {
804 if (!selected.empty() && name.find(selected) == std::string::npos) {
805 return true;
806 }
807
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700808 bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
Adam Langleyad6b28e2015-04-14 12:07:44 -0700809 if (!key ||
810 !EC_KEY_generate_key(key.get())) {
811 return false;
812 }
813
David Benjaminc1f5d792023-03-03 23:49:38 -0500814 static constexpr size_t kMaxSignature = 256;
815 if (ECDSA_size(key.get()) > kMaxSignature) {
816 abort();
Adam Langleyad6b28e2015-04-14 12:07:44 -0700817 }
818 uint8_t digest[20];
David Benjamin17cf2cb2016-12-13 01:07:13 -0500819 OPENSSL_memset(digest, 42, sizeof(digest));
Adam Langleyad6b28e2015-04-14 12:07:44 -0700820
821 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500822 if (!TimeFunctionParallel(&results, [&key, &digest]() -> bool {
823 uint8_t out[kMaxSignature];
824 unsigned out_len;
825 return ECDSA_sign(0, digest, sizeof(digest), out, &out_len,
Adam Langleyad6b28e2015-04-14 12:07:44 -0700826 key.get()) == 1;
827 })) {
828 return false;
829 }
830
831 results.Print(name + " signing");
832
David Benjaminc1f5d792023-03-03 23:49:38 -0500833 uint8_t signature[kMaxSignature];
834 unsigned sig_len;
835 if (!ECDSA_sign(0, digest, sizeof(digest), signature, &sig_len, key.get())) {
836 return false;
837 }
838
839 if (!TimeFunctionParallel(
840 &results, [&key, &signature, &digest, sig_len]() -> bool {
841 return ECDSA_verify(0, digest, sizeof(digest), signature, sig_len,
842 key.get()) == 1;
843 })) {
Adam Langleyad6b28e2015-04-14 12:07:44 -0700844 return false;
845 }
846
847 results.Print(name + " verify");
848
849 return true;
850}
851
852static bool SpeedECDH(const std::string &selected) {
853 return SpeedECDHCurve("ECDH P-224", NID_secp224r1, selected) &&
854 SpeedECDHCurve("ECDH P-256", NID_X9_62_prime256v1, selected) &&
855 SpeedECDHCurve("ECDH P-384", NID_secp384r1, selected) &&
856 SpeedECDHCurve("ECDH P-521", NID_secp521r1, selected);
857}
858
859static bool SpeedECDSA(const std::string &selected) {
860 return SpeedECDSACurve("ECDSA P-224", NID_secp224r1, selected) &&
861 SpeedECDSACurve("ECDSA P-256", NID_X9_62_prime256v1, selected) &&
862 SpeedECDSACurve("ECDSA P-384", NID_secp384r1, selected) &&
863 SpeedECDSACurve("ECDSA P-521", NID_secp521r1, selected);
864}
865
Adam Langley4fb0dc42015-11-13 13:09:47 -0800866static bool Speed25519(const std::string &selected) {
867 if (!selected.empty() && selected.find("25519") == std::string::npos) {
868 return true;
869 }
870
871 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -0500872 if (!TimeFunctionParallel(&results, []() -> bool {
873 uint8_t public_key[32], private_key[64];
Adam Langley4fb0dc42015-11-13 13:09:47 -0800874 ED25519_keypair(public_key, private_key);
875 return true;
876 })) {
877 return false;
878 }
879
880 results.Print("Ed25519 key generation");
881
David Benjaminc1f5d792023-03-03 23:49:38 -0500882 uint8_t public_key[32], private_key[64];
883 ED25519_keypair(public_key, private_key);
Adam Langley4fb0dc42015-11-13 13:09:47 -0800884 static const uint8_t kMessage[] = {0, 1, 2, 3, 4, 5};
Adam Langley4fb0dc42015-11-13 13:09:47 -0800885
David Benjaminc1f5d792023-03-03 23:49:38 -0500886 if (!TimeFunctionParallel(&results, [&private_key]() -> bool {
887 uint8_t out[64];
888 return ED25519_sign(out, kMessage, sizeof(kMessage), private_key) == 1;
Adam Langley4fb0dc42015-11-13 13:09:47 -0800889 })) {
890 return false;
891 }
892
893 results.Print("Ed25519 signing");
894
David Benjaminc1f5d792023-03-03 23:49:38 -0500895 uint8_t signature[64];
896 if (!ED25519_sign(signature, kMessage, sizeof(kMessage), private_key)) {
897 return false;
898 }
899
900 if (!TimeFunctionParallel(&results, [&public_key, &signature]() -> bool {
Adam Langley4fb0dc42015-11-13 13:09:47 -0800901 return ED25519_verify(kMessage, sizeof(kMessage), signature,
902 public_key) == 1;
903 })) {
904 fprintf(stderr, "Ed25519 verify failed.\n");
905 return false;
906 }
907
908 results.Print("Ed25519 verify");
Adam Langley4fb0dc42015-11-13 13:09:47 -0800909
David Benjaminc1f5d792023-03-03 23:49:38 -0500910 if (!TimeFunctionParallel(&results, []() -> bool {
Adam Langley4fb0dc42015-11-13 13:09:47 -0800911 uint8_t out[32], in[32];
David Benjamin17cf2cb2016-12-13 01:07:13 -0500912 OPENSSL_memset(in, 0, sizeof(in));
Adam Langley4fb0dc42015-11-13 13:09:47 -0800913 X25519_public_from_private(out, in);
914 return true;
915 })) {
916 fprintf(stderr, "Curve25519 base-point multiplication failed.\n");
917 return false;
918 }
919
920 results.Print("Curve25519 base-point multiplication");
921
David Benjaminc1f5d792023-03-03 23:49:38 -0500922 if (!TimeFunctionParallel(&results, []() -> bool {
Adam Langley4fb0dc42015-11-13 13:09:47 -0800923 uint8_t out[32], in1[32], in2[32];
David Benjamin17cf2cb2016-12-13 01:07:13 -0500924 OPENSSL_memset(in1, 0, sizeof(in1));
925 OPENSSL_memset(in2, 0, sizeof(in2));
Adam Langley3ac32b12015-11-17 15:15:05 -0800926 in1[0] = 1;
927 in2[0] = 9;
Adam Langley4fb0dc42015-11-13 13:09:47 -0800928 return X25519(out, in1, in2) == 1;
929 })) {
930 fprintf(stderr, "Curve25519 arbitrary point multiplication failed.\n");
931 return false;
932 }
933
934 results.Print("Curve25519 arbitrary point multiplication");
935
936 return true;
937}
938
Arnar Birgissonf27459e2016-02-09 18:09:00 -0800939static bool SpeedSPAKE2(const std::string &selected) {
940 if (!selected.empty() && selected.find("SPAKE2") == std::string::npos) {
941 return true;
942 }
943
944 TimeResults results;
945
946 static const uint8_t kAliceName[] = {'A'};
947 static const uint8_t kBobName[] = {'B'};
948 static const uint8_t kPassword[] = "password";
Matt Braithwaited17d74d2016-08-17 20:10:28 -0700949 bssl::UniquePtr<SPAKE2_CTX> alice(SPAKE2_CTX_new(spake2_role_alice,
950 kAliceName, sizeof(kAliceName), kBobName,
951 sizeof(kBobName)));
Arnar Birgissonf27459e2016-02-09 18:09:00 -0800952 uint8_t alice_msg[SPAKE2_MAX_MSG_SIZE];
953 size_t alice_msg_len;
954
955 if (!SPAKE2_generate_msg(alice.get(), alice_msg, &alice_msg_len,
956 sizeof(alice_msg),
957 kPassword, sizeof(kPassword))) {
958 fprintf(stderr, "SPAKE2_generate_msg failed.\n");
959 return false;
960 }
961
David Benjaminc1f5d792023-03-03 23:49:38 -0500962 if (!TimeFunctionParallel(&results, [&alice_msg, alice_msg_len]() -> bool {
963 bssl::UniquePtr<SPAKE2_CTX> bob(
964 SPAKE2_CTX_new(spake2_role_bob, kBobName, sizeof(kBobName),
965 kAliceName, sizeof(kAliceName)));
Arnar Birgissonf27459e2016-02-09 18:09:00 -0800966 uint8_t bob_msg[SPAKE2_MAX_MSG_SIZE], bob_key[64];
967 size_t bob_msg_len, bob_key_len;
968 if (!SPAKE2_generate_msg(bob.get(), bob_msg, &bob_msg_len,
969 sizeof(bob_msg), kPassword,
970 sizeof(kPassword)) ||
971 !SPAKE2_process_msg(bob.get(), bob_key, &bob_key_len,
972 sizeof(bob_key), alice_msg, alice_msg_len)) {
973 return false;
974 }
975
976 return true;
977 })) {
978 fprintf(stderr, "SPAKE2 failed.\n");
979 }
980
981 results.Print("SPAKE2 over Ed25519");
982
983 return true;
984}
985
David Benjaminb5292532017-06-09 19:27:37 -0400986static bool SpeedScrypt(const std::string &selected) {
987 if (!selected.empty() && selected.find("scrypt") == std::string::npos) {
988 return true;
989 }
990
991 TimeResults results;
992
993 static const char kPassword[] = "password";
994 static const uint8_t kSalt[] = "NaCl";
995
David Benjaminc1f5d792023-03-03 23:49:38 -0500996 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjaminb5292532017-06-09 19:27:37 -0400997 uint8_t out[64];
998 return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
999 sizeof(kSalt) - 1, 1024, 8, 16, 0 /* max_mem */,
1000 out, sizeof(out));
1001 })) {
1002 fprintf(stderr, "scrypt failed.\n");
1003 return false;
1004 }
1005 results.Print("scrypt (N = 1024, r = 8, p = 16)");
1006
David Benjaminc1f5d792023-03-03 23:49:38 -05001007 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjaminb5292532017-06-09 19:27:37 -04001008 uint8_t out[64];
1009 return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
1010 sizeof(kSalt) - 1, 16384, 8, 1, 0 /* max_mem */,
1011 out, sizeof(out));
1012 })) {
1013 fprintf(stderr, "scrypt failed.\n");
1014 return false;
1015 }
1016 results.Print("scrypt (N = 16384, r = 8, p = 1)");
1017
1018 return true;
1019}
1020
Adam Langley7b935932018-11-12 13:53:42 -08001021static bool SpeedHRSS(const std::string &selected) {
1022 if (!selected.empty() && selected != "HRSS") {
1023 return true;
1024 }
1025
1026 TimeResults results;
1027
David Benjaminc1f5d792023-03-03 23:49:38 -05001028 if (!TimeFunctionParallel(&results, []() -> bool {
Adam Langley71530132021-06-30 16:33:47 -07001029 struct HRSS_public_key pub;
1030 struct HRSS_private_key priv;
1031 uint8_t entropy[HRSS_GENERATE_KEY_BYTES];
1032 RAND_bytes(entropy, sizeof(entropy));
1033 return HRSS_generate_key(&pub, &priv, entropy);
1034 })) {
Adam Langley7b935932018-11-12 13:53:42 -08001035 fprintf(stderr, "Failed to time HRSS_generate_key.\n");
1036 return false;
1037 }
1038
1039 results.Print("HRSS generate");
1040
1041 struct HRSS_public_key pub;
1042 struct HRSS_private_key priv;
1043 uint8_t key_entropy[HRSS_GENERATE_KEY_BYTES];
1044 RAND_bytes(key_entropy, sizeof(key_entropy));
Adam Langley71530132021-06-30 16:33:47 -07001045 if (!HRSS_generate_key(&pub, &priv, key_entropy)) {
1046 return false;
1047 }
Adam Langley7b935932018-11-12 13:53:42 -08001048
David Benjaminc1f5d792023-03-03 23:49:38 -05001049 if (!TimeFunctionParallel(&results, [&pub]() -> bool {
Adam Langley71530132021-06-30 16:33:47 -07001050 uint8_t entropy[HRSS_ENCAP_BYTES];
1051 uint8_t shared_key[HRSS_KEY_BYTES];
David Benjaminc1f5d792023-03-03 23:49:38 -05001052 uint8_t ciphertext[HRSS_CIPHERTEXT_BYTES];
Adam Langley71530132021-06-30 16:33:47 -07001053 RAND_bytes(entropy, sizeof(entropy));
1054 return HRSS_encap(ciphertext, shared_key, &pub, entropy);
1055 })) {
Adam Langley7b935932018-11-12 13:53:42 -08001056 fprintf(stderr, "Failed to time HRSS_encap.\n");
1057 return false;
1058 }
Adam Langley7b935932018-11-12 13:53:42 -08001059 results.Print("HRSS encap");
1060
David Benjaminc1f5d792023-03-03 23:49:38 -05001061 uint8_t entropy[HRSS_ENCAP_BYTES];
1062 uint8_t shared_key[HRSS_KEY_BYTES];
1063 uint8_t ciphertext[HRSS_CIPHERTEXT_BYTES];
1064 RAND_bytes(entropy, sizeof(entropy));
1065 if (!HRSS_encap(ciphertext, shared_key, &pub, entropy)) {
1066 return false;
1067 }
1068
1069 if (!TimeFunctionParallel(&results, [&priv, &ciphertext]() -> bool {
1070 uint8_t shared_key2[HRSS_KEY_BYTES];
1071 return HRSS_decap(shared_key2, &priv, ciphertext, sizeof(ciphertext));
Adam Langley71530132021-06-30 16:33:47 -07001072 })) {
Adam Langley7b935932018-11-12 13:53:42 -08001073 fprintf(stderr, "Failed to time HRSS_encap.\n");
1074 return false;
1075 }
1076
1077 results.Print("HRSS decap");
1078
1079 return true;
1080}
1081
Sophie Schmieg58472cc2023-03-07 00:39:31 +00001082static bool SpeedKyber(const std::string &selected) {
1083 if (!selected.empty() && selected != "Kyber") {
1084 return true;
1085 }
1086
1087 TimeResults results;
1088
Sophie Schmieg58472cc2023-03-07 00:39:31 +00001089 uint8_t ciphertext[KYBER_CIPHERTEXT_BYTES];
1090 // This ciphertext is nonsense, but Kyber decap is constant-time so, for the
1091 // purposes of timing, it's fine.
1092 memset(ciphertext, 42, sizeof(ciphertext));
David Benjaminc1f5d792023-03-03 23:49:38 -05001093 if (!TimeFunctionParallel(&results, [&]() -> bool {
1094 KYBER_private_key priv;
1095 uint8_t encoded_public_key[KYBER_PUBLIC_KEY_BYTES];
1096 KYBER_generate_key(encoded_public_key, &priv);
1097 uint8_t shared_secret[32];
1098 KYBER_decap(shared_secret, sizeof(shared_secret), ciphertext, &priv);
1099 return true;
1100 })) {
Sophie Schmieg58472cc2023-03-07 00:39:31 +00001101 fprintf(stderr, "Failed to time KYBER_generate_key + KYBER_decap.\n");
1102 return false;
1103 }
1104
1105 results.Print("Kyber generate + decap");
1106
David Benjaminc1f5d792023-03-03 23:49:38 -05001107 KYBER_private_key priv;
1108 uint8_t encoded_public_key[KYBER_PUBLIC_KEY_BYTES];
1109 KYBER_generate_key(encoded_public_key, &priv);
Sophie Schmieg58472cc2023-03-07 00:39:31 +00001110 KYBER_public_key pub;
David Benjaminc1f5d792023-03-03 23:49:38 -05001111 if (!TimeFunctionParallel(&results, [&]() -> bool {
1112 CBS encoded_public_key_cbs;
1113 CBS_init(&encoded_public_key_cbs, encoded_public_key,
1114 sizeof(encoded_public_key));
1115 if (!KYBER_parse_public_key(&pub, &encoded_public_key_cbs)) {
1116 return false;
1117 }
1118 uint8_t shared_secret[32];
1119 KYBER_encap(ciphertext, shared_secret, sizeof(shared_secret), &pub);
1120 return true;
1121 })) {
Sophie Schmieg58472cc2023-03-07 00:39:31 +00001122 fprintf(stderr, "Failed to time KYBER_encap.\n");
1123 return false;
1124 }
1125
1126 results.Print("Kyber parse + encap");
1127
1128 return true;
1129}
1130
Steven Valdez188b65a2020-04-21 14:31:05 -04001131static bool SpeedHashToCurve(const std::string &selected) {
1132 if (!selected.empty() && selected.find("hashtocurve") == std::string::npos) {
1133 return true;
1134 }
1135
Steven Valdez188b65a2020-04-21 14:31:05 -04001136 uint8_t input[64];
1137 RAND_bytes(input, sizeof(input));
1138
1139 static const uint8_t kLabel[] = "label";
1140
1141 TimeResults results;
Steven Valdez6a718402020-04-23 11:03:26 -04001142 {
David Benjamin3950d6c2023-02-09 19:24:06 -05001143 const EC_GROUP *p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
1144 if (p256 == NULL) {
Steven Valdez6a718402020-04-23 11:03:26 -04001145 return false;
1146 }
David Benjaminc1f5d792023-03-03 23:49:38 -05001147 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjamin5e988c42023-05-03 14:05:27 -04001148 EC_JACOBIAN out;
David Benjamin3950d6c2023-02-09 19:24:06 -05001149 return ec_hash_to_curve_p256_xmd_sha256_sswu(
1150 p256, &out, kLabel, sizeof(kLabel), input, sizeof(input));
Steven Valdez6a718402020-04-23 11:03:26 -04001151 })) {
1152 fprintf(stderr, "hash-to-curve failed.\n");
1153 return false;
1154 }
David Benjamin3950d6c2023-02-09 19:24:06 -05001155 results.Print("hash-to-curve P256_XMD:SHA-256_SSWU_RO_");
1156
1157 const EC_GROUP *p384 = EC_GROUP_new_by_curve_name(NID_secp384r1);
1158 if (p384 == NULL) {
1159 return false;
1160 }
David Benjaminc1f5d792023-03-03 23:49:38 -05001161 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjamin5e988c42023-05-03 14:05:27 -04001162 EC_JACOBIAN out;
David Benjamin3950d6c2023-02-09 19:24:06 -05001163 return ec_hash_to_curve_p384_xmd_sha384_sswu(
1164 p384, &out, kLabel, sizeof(kLabel), input, sizeof(input));
1165 })) {
1166 fprintf(stderr, "hash-to-curve failed.\n");
1167 return false;
1168 }
1169 results.Print("hash-to-curve P384_XMD:SHA-384_SSWU_RO_");
Steven Valdez6a718402020-04-23 11:03:26 -04001170
David Benjaminc1f5d792023-03-03 23:49:38 -05001171 if (!TimeFunctionParallel(&results, [&]() -> bool {
Steven Valdez6a718402020-04-23 11:03:26 -04001172 EC_SCALAR out;
David Benjamineeb5bb352020-04-29 11:37:14 -04001173 return ec_hash_to_scalar_p384_xmd_sha512_draft07(
David Benjamin3950d6c2023-02-09 19:24:06 -05001174 p384, &out, kLabel, sizeof(kLabel), input, sizeof(input));
Steven Valdez6a718402020-04-23 11:03:26 -04001175 })) {
1176 fprintf(stderr, "hash-to-scalar failed.\n");
1177 return false;
1178 }
1179 results.Print("hash-to-scalar P384_XMD:SHA-512");
1180 }
Steven Valdez188b65a2020-04-21 14:31:05 -04001181
1182 return true;
1183}
1184
David Benjaminf9587272021-09-21 16:33:15 -04001185static bool SpeedBase64(const std::string &selected) {
1186 if (!selected.empty() && selected.find("base64") == std::string::npos) {
1187 return true;
1188 }
1189
1190 static const char kInput[] =
1191 "MIIDtTCCAp2gAwIBAgIJALW2IrlaBKUhMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV"
1192 "BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX"
1193 "aWRnaXRzIFB0eSBMdGQwHhcNMTYwNzA5MDQzODA5WhcNMTYwODA4MDQzODA5WjBF"
1194 "MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50"
1195 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB"
1196 "CgKCAQEAugvahBkSAUF1fC49vb1bvlPrcl80kop1iLpiuYoz4Qptwy57+EWssZBc"
1197 "HprZ5BkWf6PeGZ7F5AX1PyJbGHZLqvMCvViP6pd4MFox/igESISEHEixoiXCzepB"
1198 "rhtp5UQSjHD4D4hKtgdMgVxX+LRtwgW3mnu/vBu7rzpr/DS8io99p3lqZ1Aky+aN"
1199 "lcMj6MYy8U+YFEevb/V0lRY9oqwmW7BHnXikm/vi6sjIS350U8zb/mRzYeIs2R65"
1200 "LUduTL50+UMgat9ocewI2dv8aO9Dph+8NdGtg8LFYyTTHcUxJoMr1PTOgnmET19W"
1201 "JH4PrFwk7ZE1QJQQ1L4iKmPeQistuQIDAQABo4GnMIGkMB0GA1UdDgQWBBT5m6Vv"
1202 "zYjVYHG30iBE+j2XDhUE8jB1BgNVHSMEbjBsgBT5m6VvzYjVYHG30iBE+j2XDhUE"
1203 "8qFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV"
1204 "BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJALW2IrlaBKUhMAwGA1UdEwQF"
1205 "MAMBAf8wDQYJKoZIhvcNAQELBQADggEBAD7Jg68SArYWlcoHfZAB90Pmyrt5H6D8"
1206 "LRi+W2Ri1fBNxREELnezWJ2scjl4UMcsKYp4Pi950gVN+62IgrImcCNvtb5I1Cfy"
1207 "/MNNur9ffas6X334D0hYVIQTePyFk3umI+2mJQrtZZyMPIKSY/sYGQHhGGX6wGK+"
1208 "GO/og0PQk/Vu6D+GU2XRnDV0YZg1lsAsHd21XryK6fDmNkEMwbIWrts4xc7scRrG"
1209 "HWy+iMf6/7p/Ak/SIicM4XSwmlQ8pPxAZPr+E2LoVd9pMpWUwpW2UbtO5wsGTrY5"
1210 "sO45tFNN/y+jtUheB1C2ijObG/tXELaiyCdM+S/waeuv0MXtI4xnn1A=";
1211
David Benjaminf9587272021-09-21 16:33:15 -04001212 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -05001213 if (!TimeFunctionParallel(&results, [&]() -> bool {
1214 uint8_t out[sizeof(kInput)];
1215 size_t len;
1216 return EVP_DecodeBase64(out, &len, sizeof(out),
David Benjaminf9587272021-09-21 16:33:15 -04001217 reinterpret_cast<const uint8_t *>(kInput),
1218 strlen(kInput));
1219 })) {
1220 fprintf(stderr, "base64 decode failed.\n");
1221 return false;
1222 }
1223 results.PrintWithBytes("base64 decode", strlen(kInput));
1224 return true;
1225}
1226
David Benjamin345c86b2022-01-23 11:11:17 -05001227static bool SpeedSipHash(const std::string &selected) {
1228 if (!selected.empty() && selected.find("siphash") == std::string::npos) {
1229 return true;
1230 }
1231
1232 uint64_t key[2] = {0};
1233 for (size_t len : g_chunk_lengths) {
1234 std::vector<uint8_t> input(len);
1235 TimeResults results;
David Benjaminc1f5d792023-03-03 23:49:38 -05001236 if (!TimeFunctionParallel(&results, [&]() -> bool {
David Benjamin345c86b2022-01-23 11:11:17 -05001237 SIPHASH_24(key, input.data(), input.size());
1238 return true;
1239 })) {
1240 fprintf(stderr, "SIPHASH_24 failed.\n");
1241 ERR_print_errors_fp(stderr);
1242 return false;
1243 }
1244 results.PrintWithBytes("SipHash-2-4" + ChunkLenSuffix(len), len);
1245 }
1246
1247 return true;
1248}
1249
Steven Valdezf2b2ef82020-09-21 11:39:22 -04001250static TRUST_TOKEN_PRETOKEN *trust_token_pretoken_dup(
David Benjamindf8a55b2023-01-04 15:52:36 -08001251 const TRUST_TOKEN_PRETOKEN *in) {
1252 return static_cast<TRUST_TOKEN_PRETOKEN *>(
1253 OPENSSL_memdup(in, sizeof(TRUST_TOKEN_PRETOKEN)));
Steven Valdez188b65a2020-04-21 14:31:05 -04001254}
1255
David Benjamin239634d2020-04-29 11:17:51 -04001256static bool SpeedTrustToken(std::string name, const TRUST_TOKEN_METHOD *method,
1257 size_t batchsize, const std::string &selected) {
Steven Valdez188b65a2020-04-21 14:31:05 -04001258 if (!selected.empty() && selected.find("trusttoken") == std::string::npos) {
1259 return true;
1260 }
1261
1262 TimeResults results;
1263 if (!TimeFunction(&results, [&]() -> bool {
1264 uint8_t priv_key[TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE];
1265 uint8_t pub_key[TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE];
1266 size_t priv_key_len, pub_key_len;
1267 return TRUST_TOKEN_generate_key(
David Benjamin239634d2020-04-29 11:17:51 -04001268 method, priv_key, &priv_key_len, TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE,
1269 pub_key, &pub_key_len, TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE, 0);
Steven Valdez188b65a2020-04-21 14:31:05 -04001270 })) {
1271 fprintf(stderr, "TRUST_TOKEN_generate_key failed.\n");
1272 return false;
1273 }
1274 results.Print(name + " generate_key");
1275
David Benjamin239634d2020-04-29 11:17:51 -04001276 bssl::UniquePtr<TRUST_TOKEN_CLIENT> client(
1277 TRUST_TOKEN_CLIENT_new(method, batchsize));
1278 bssl::UniquePtr<TRUST_TOKEN_ISSUER> issuer(
1279 TRUST_TOKEN_ISSUER_new(method, batchsize));
Steven Valdez188b65a2020-04-21 14:31:05 -04001280 uint8_t priv_key[TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE];
1281 uint8_t pub_key[TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE];
1282 size_t priv_key_len, pub_key_len, key_index;
David Benjamin239634d2020-04-29 11:17:51 -04001283 if (!client || !issuer ||
Steven Valdez188b65a2020-04-21 14:31:05 -04001284 !TRUST_TOKEN_generate_key(
David Benjamin239634d2020-04-29 11:17:51 -04001285 method, priv_key, &priv_key_len, TRUST_TOKEN_MAX_PRIVATE_KEY_SIZE,
1286 pub_key, &pub_key_len, TRUST_TOKEN_MAX_PUBLIC_KEY_SIZE, 0) ||
Steven Valdez188b65a2020-04-21 14:31:05 -04001287 !TRUST_TOKEN_CLIENT_add_key(client.get(), &key_index, pub_key,
1288 pub_key_len) ||
1289 !TRUST_TOKEN_ISSUER_add_key(issuer.get(), priv_key, priv_key_len)) {
1290 fprintf(stderr, "failed to generate trust token key.\n");
1291 return false;
1292 }
1293
1294 uint8_t public_key[32], private_key[64];
1295 ED25519_keypair(public_key, private_key);
1296 bssl::UniquePtr<EVP_PKEY> priv(
1297 EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, private_key, 32));
1298 bssl::UniquePtr<EVP_PKEY> pub(
1299 EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key, 32));
1300 if (!priv || !pub) {
1301 fprintf(stderr, "failed to generate trust token SRR key.\n");
1302 return false;
1303 }
1304
1305 TRUST_TOKEN_CLIENT_set_srr_key(client.get(), pub.get());
1306 TRUST_TOKEN_ISSUER_set_srr_key(issuer.get(), priv.get());
1307 uint8_t metadata_key[32];
1308 RAND_bytes(metadata_key, sizeof(metadata_key));
1309 if (!TRUST_TOKEN_ISSUER_set_metadata_key(issuer.get(), metadata_key,
1310 sizeof(metadata_key))) {
1311 fprintf(stderr, "failed to generate trust token metadata key.\n");
1312 return false;
1313 }
1314
1315 if (!TimeFunction(&results, [&]() -> bool {
1316 uint8_t *issue_msg = NULL;
1317 size_t msg_len;
1318 int ok = TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg,
1319 &msg_len, batchsize);
1320 OPENSSL_free(issue_msg);
1321 // Clear pretokens.
Steven Valdezf2b2ef82020-09-21 11:39:22 -04001322 sk_TRUST_TOKEN_PRETOKEN_pop_free(client->pretokens,
1323 TRUST_TOKEN_PRETOKEN_free);
1324 client->pretokens = sk_TRUST_TOKEN_PRETOKEN_new_null();
Steven Valdez188b65a2020-04-21 14:31:05 -04001325 return ok;
1326 })) {
1327 fprintf(stderr, "TRUST_TOKEN_CLIENT_begin_issuance failed.\n");
1328 return false;
1329 }
1330 results.Print(name + " begin_issuance");
1331
1332 uint8_t *issue_msg = NULL;
1333 size_t msg_len;
1334 if (!TRUST_TOKEN_CLIENT_begin_issuance(client.get(), &issue_msg, &msg_len,
1335 batchsize)) {
1336 fprintf(stderr, "TRUST_TOKEN_CLIENT_begin_issuance failed.\n");
1337 return false;
1338 }
1339 bssl::UniquePtr<uint8_t> free_issue_msg(issue_msg);
1340
Steven Valdezf2b2ef82020-09-21 11:39:22 -04001341 bssl::UniquePtr<STACK_OF(TRUST_TOKEN_PRETOKEN)> pretokens(
1342 sk_TRUST_TOKEN_PRETOKEN_deep_copy(client->pretokens,
1343 trust_token_pretoken_dup,
1344 TRUST_TOKEN_PRETOKEN_free));
Steven Valdez188b65a2020-04-21 14:31:05 -04001345
1346 if (!TimeFunction(&results, [&]() -> bool {
1347 uint8_t *issue_resp = NULL;
David Benjamin17078f22020-04-28 17:50:13 -04001348 size_t resp_len, tokens_issued;
Steven Valdez188b65a2020-04-21 14:31:05 -04001349 int ok = TRUST_TOKEN_ISSUER_issue(issuer.get(), &issue_resp, &resp_len,
1350 &tokens_issued, issue_msg, msg_len,
1351 /*public_metadata=*/0,
1352 /*private_metadata=*/0,
1353 /*max_issuance=*/batchsize);
1354 OPENSSL_free(issue_resp);
1355 return ok;
1356 })) {
1357 fprintf(stderr, "TRUST_TOKEN_ISSUER_issue failed.\n");
1358 return false;
1359 }
1360 results.Print(name + " issue");
1361
1362 uint8_t *issue_resp = NULL;
David Benjamin17078f22020-04-28 17:50:13 -04001363 size_t resp_len, tokens_issued;
Steven Valdez188b65a2020-04-21 14:31:05 -04001364 if (!TRUST_TOKEN_ISSUER_issue(issuer.get(), &issue_resp, &resp_len,
1365 &tokens_issued, issue_msg, msg_len,
1366 /*public_metadata=*/0, /*private_metadata=*/0,
1367 /*max_issuance=*/batchsize)) {
1368 fprintf(stderr, "TRUST_TOKEN_ISSUER_issue failed.\n");
1369 return false;
1370 }
1371 bssl::UniquePtr<uint8_t> free_issue_resp(issue_resp);
1372
1373 if (!TimeFunction(&results, [&]() -> bool {
1374 size_t key_index2;
1375 bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
1376 TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index2,
1377 issue_resp, resp_len));
1378
1379 // Reset pretokens.
Steven Valdezf2b2ef82020-09-21 11:39:22 -04001380 client->pretokens = sk_TRUST_TOKEN_PRETOKEN_deep_copy(
1381 pretokens.get(), trust_token_pretoken_dup,
1382 TRUST_TOKEN_PRETOKEN_free);
Steven Valdez188b65a2020-04-21 14:31:05 -04001383 return !!tokens;
1384 })) {
1385 fprintf(stderr, "TRUST_TOKEN_CLIENT_finish_issuance failed.\n");
1386 return false;
1387 }
1388 results.Print(name + " finish_issuance");
1389
1390 bssl::UniquePtr<STACK_OF(TRUST_TOKEN)> tokens(
1391 TRUST_TOKEN_CLIENT_finish_issuance(client.get(), &key_index, issue_resp,
1392 resp_len));
1393 if (!tokens || sk_TRUST_TOKEN_num(tokens.get()) < 1) {
1394 fprintf(stderr, "TRUST_TOKEN_CLIENT_finish_issuance failed.\n");
1395 return false;
1396 }
1397
1398 const TRUST_TOKEN *token = sk_TRUST_TOKEN_value(tokens.get(), 0);
1399
1400 const uint8_t kClientData[] = "\x70TEST CLIENT DATA";
1401 uint64_t kRedemptionTime = 13374242;
1402
1403 if (!TimeFunction(&results, [&]() -> bool {
1404 uint8_t *redeem_msg = NULL;
1405 size_t redeem_msg_len;
1406 int ok = TRUST_TOKEN_CLIENT_begin_redemption(
1407 client.get(), &redeem_msg, &redeem_msg_len, token, kClientData,
1408 sizeof(kClientData) - 1, kRedemptionTime);
1409 OPENSSL_free(redeem_msg);
1410 return ok;
1411 })) {
1412 fprintf(stderr, "TRUST_TOKEN_CLIENT_begin_redemption failed.\n");
1413 return false;
1414 }
1415 results.Print(name + " begin_redemption");
1416
1417 uint8_t *redeem_msg = NULL;
1418 size_t redeem_msg_len;
1419 if (!TRUST_TOKEN_CLIENT_begin_redemption(
1420 client.get(), &redeem_msg, &redeem_msg_len, token, kClientData,
1421 sizeof(kClientData) - 1, kRedemptionTime)) {
1422 fprintf(stderr, "TRUST_TOKEN_CLIENT_begin_redemption failed.\n");
1423 return false;
1424 }
1425 bssl::UniquePtr<uint8_t> free_redeem_msg(redeem_msg);
1426
1427 if (!TimeFunction(&results, [&]() -> bool {
Steven Valdez80a243e2023-01-26 13:26:33 -05001428 uint32_t public_value;
1429 uint8_t private_value;
1430 TRUST_TOKEN *rtoken;
Steven Valdez188b65a2020-04-21 14:31:05 -04001431 uint8_t *client_data = NULL;
1432 size_t client_data_len;
Steven Valdez188b65a2020-04-21 14:31:05 -04001433 int ok = TRUST_TOKEN_ISSUER_redeem(
Steven Valdez80a243e2023-01-26 13:26:33 -05001434 issuer.get(), &public_value, &private_value, &rtoken, &client_data,
1435 &client_data_len, redeem_msg, redeem_msg_len);
Steven Valdez188b65a2020-04-21 14:31:05 -04001436 OPENSSL_free(client_data);
1437 TRUST_TOKEN_free(rtoken);
1438 return ok;
1439 })) {
1440 fprintf(stderr, "TRUST_TOKEN_ISSUER_redeem failed.\n");
1441 return false;
1442 }
1443 results.Print(name + " redeem");
1444
Steven Valdez80a243e2023-01-26 13:26:33 -05001445 uint32_t public_value;
1446 uint8_t private_value;
1447 TRUST_TOKEN *rtoken;
Steven Valdez188b65a2020-04-21 14:31:05 -04001448 uint8_t *client_data = NULL;
1449 size_t client_data_len;
Steven Valdez80a243e2023-01-26 13:26:33 -05001450 if (!TRUST_TOKEN_ISSUER_redeem(issuer.get(), &public_value, &private_value,
Steven Valdez188b65a2020-04-21 14:31:05 -04001451 &rtoken, &client_data, &client_data_len,
Steven Valdez80a243e2023-01-26 13:26:33 -05001452 redeem_msg, redeem_msg_len)) {
Steven Valdez188b65a2020-04-21 14:31:05 -04001453 fprintf(stderr, "TRUST_TOKEN_ISSUER_redeem failed.\n");
1454 return false;
1455 }
Steven Valdez188b65a2020-04-21 14:31:05 -04001456 bssl::UniquePtr<uint8_t> free_client_data(client_data);
1457 bssl::UniquePtr<TRUST_TOKEN> free_rtoken(rtoken);
1458
Steven Valdez188b65a2020-04-21 14:31:05 -04001459 return true;
1460}
1461
David Benjaminab5edbe2021-01-27 16:49:50 -05001462#if defined(BORINGSSL_FIPS)
1463static bool SpeedSelfTest(const std::string &selected) {
1464 if (!selected.empty() && selected.find("self-test") == std::string::npos) {
1465 return true;
1466 }
1467
1468 TimeResults results;
1469 if (!TimeFunction(&results, []() -> bool { return BORINGSSL_self_test(); })) {
1470 fprintf(stderr, "BORINGSSL_self_test faileid.\n");
1471 ERR_print_errors_fp(stderr);
1472 return false;
1473 }
1474
1475 results.Print("self-test");
1476 return true;
1477}
1478#endif
1479
David Benjaminbcb65b92016-08-14 22:06:49 -04001480static const struct argument kArguments[] = {
1481 {
David Benjamin64431732019-02-10 22:07:23 +00001482 "-filter",
1483 kOptionalArgument,
1484 "A filter on the speed tests to run",
David Benjaminbcb65b92016-08-14 22:06:49 -04001485 },
1486 {
David Benjamin64431732019-02-10 22:07:23 +00001487 "-timeout",
1488 kOptionalArgument,
1489 "The number of seconds to run each test for (default is 1)",
David Benjaminbcb65b92016-08-14 22:06:49 -04001490 },
1491 {
David Benjamin64431732019-02-10 22:07:23 +00001492 "-chunks",
1493 kOptionalArgument,
1494 "A comma-separated list of input sizes to run tests at (default is "
David Benjamin5501a262019-03-20 17:45:15 -05001495 "16,256,1350,8192,16384)",
David Benjamin64431732019-02-10 22:07:23 +00001496 },
1497 {
Zola Bridgesf10ea552019-10-01 11:35:44 -07001498 "-json",
1499 kBooleanArgument,
1500 "If this flag is set, speed will print the output of each benchmark in "
1501 "JSON format as follows: \"{\"description\": "
1502 "\"descriptionOfOperation\", \"numCalls\": 1234, "
1503 "\"timeInMicroseconds\": 1234567, \"bytesPerCall\": 1234}\". When "
1504 "there is no information about the bytes per call for an operation, "
1505 "the JSON field for bytesPerCall will be omitted.",
1506 },
David Benjaminc1f5d792023-03-03 23:49:38 -05001507#if defined(OPENSSL_THREADS)
1508 {
1509 "-threads",
1510 kOptionalArgument,
1511 "The number of threads to benchmark in parallel (default is 1)",
1512 },
1513#endif
Zola Bridgesf10ea552019-10-01 11:35:44 -07001514 {
David Benjamin64431732019-02-10 22:07:23 +00001515 "",
1516 kOptionalArgument,
1517 "",
David Benjaminbcb65b92016-08-14 22:06:49 -04001518 },
1519};
1520
Adam Langleyc5c0c7e2014-06-20 12:00:00 -07001521bool Speed(const std::vector<std::string> &args) {
David Benjaminbcb65b92016-08-14 22:06:49 -04001522 std::map<std::string, std::string> args_map;
1523 if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
1524 PrintUsage(kArguments);
Adam Langley90b58402015-04-13 11:04:18 -07001525 return false;
1526 }
David Benjaminbcb65b92016-08-14 22:06:49 -04001527
1528 std::string selected;
1529 if (args_map.count("-filter") != 0) {
1530 selected = args_map["-filter"];
1531 }
1532
Zola Bridgesf10ea552019-10-01 11:35:44 -07001533 if (args_map.count("-json") != 0) {
1534 g_print_json = true;
1535 }
1536
David Benjaminbcb65b92016-08-14 22:06:49 -04001537 if (args_map.count("-timeout") != 0) {
1538 g_timeout_seconds = atoi(args_map["-timeout"].c_str());
Adam Langley90b58402015-04-13 11:04:18 -07001539 }
Adam Langleyc5c0c7e2014-06-20 12:00:00 -07001540
David Benjaminc1f5d792023-03-03 23:49:38 -05001541#if defined(OPENSSL_THREADS)
1542 if (args_map.count("-threads") != 0) {
1543 g_threads = atoi(args_map["-threads"].c_str());
1544 }
1545#endif
1546
David Benjamin64431732019-02-10 22:07:23 +00001547 if (args_map.count("-chunks") != 0) {
1548 g_chunk_lengths.clear();
1549 const char *start = args_map["-chunks"].data();
1550 const char *end = start + args_map["-chunks"].size();
1551 while (start != end) {
1552 errno = 0;
1553 char *ptr;
1554 unsigned long long val = strtoull(start, &ptr, 10);
1555 if (ptr == start /* no numeric characters found */ ||
1556 errno == ERANGE /* overflow */ ||
1557 static_cast<size_t>(val) != val) {
1558 fprintf(stderr, "Error parsing -chunks argument\n");
1559 return false;
1560 }
1561 g_chunk_lengths.push_back(static_cast<size_t>(val));
1562 start = ptr;
1563 if (start != end) {
1564 if (*start != ',') {
1565 fprintf(stderr, "Error parsing -chunks argument\n");
1566 return false;
1567 }
1568 start++;
1569 }
1570 }
1571 }
1572
Adam Langleye7624342015-01-15 17:33:48 -08001573 // kTLSADLen is the number of bytes of additional data that TLS passes to
1574 // AEADs.
1575 static const size_t kTLSADLen = 13;
1576 // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
1577 // These are AEADs that weren't originally defined as AEADs, but which we use
1578 // via the AEAD interface. In order for that to work, they have some TLS
1579 // knowledge in them and construct a couple of the AD bytes internally.
1580 static const size_t kLegacyADLen = kTLSADLen - 2;
1581
Zola Bridgesf10ea552019-10-01 11:35:44 -07001582 if (g_print_json) {
1583 puts("[");
1584 }
Daniel Hirche1414d862018-04-13 19:09:25 +02001585 if (!SpeedRSA(selected) ||
1586 !SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen, selected) ||
Adam Langley90b58402015-04-13 11:04:18 -07001587 !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen, selected) ||
David Benjamin8ffab722015-11-30 18:48:18 -05001588 !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen,
1589 selected) ||
David Benjamindf571632015-12-07 19:48:16 -05001590 !SpeedAEAD(EVP_aead_des_ede3_cbc_sha1_tls(), "DES-EDE3-CBC-SHA1",
1591 kLegacyADLen, selected) ||
Adam Langley90b58402015-04-13 11:04:18 -07001592 !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
1593 kLegacyADLen, selected) ||
1594 !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
1595 kLegacyADLen, selected) ||
David Benjaminc93724b2018-05-21 17:14:05 -04001596 !SpeedAEADOpen(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
1597 kLegacyADLen, selected) ||
1598 !SpeedAEADOpen(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
1599 kLegacyADLen, selected) ||
Adam Langleydf447ba2016-12-01 08:24:24 -08001600 !SpeedAEAD(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
1601 selected) ||
1602 !SpeedAEAD(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
1603 selected) ||
Adam Langleyba9557d2017-02-27 13:53:23 -08001604 !SpeedAEADOpen(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
1605 selected) ||
1606 !SpeedAEADOpen(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
1607 selected) ||
Steven Valdezf16cd422018-02-13 13:39:42 -05001608 !SpeedAEAD(EVP_aead_aes_128_ccm_bluetooth(), "AES-128-CCM-Bluetooth",
1609 kTLSADLen, selected) ||
David Benjamin25e36da2019-08-31 13:25:15 -04001610 !SpeedAESBlock("AES-128", 128, selected) ||
1611 !SpeedAESBlock("AES-256", 256, selected) ||
Adam Langley90b58402015-04-13 11:04:18 -07001612 !SpeedHash(EVP_sha1(), "SHA-1", selected) ||
1613 !SpeedHash(EVP_sha256(), "SHA-256", selected) ||
1614 !SpeedHash(EVP_sha512(), "SHA-512", selected) ||
Adam Langleye1333452021-01-21 11:56:52 -08001615 !SpeedHash(EVP_blake2b256(), "BLAKE2b-256", selected) ||
Adam Langleyad6b28e2015-04-14 12:07:44 -07001616 !SpeedRandom(selected) ||
1617 !SpeedECDH(selected) ||
Adam Langley4fb0dc42015-11-13 13:09:47 -08001618 !SpeedECDSA(selected) ||
Arnar Birgissonf27459e2016-02-09 18:09:00 -08001619 !Speed25519(selected) ||
David Benjaminb5292532017-06-09 19:27:37 -04001620 !SpeedSPAKE2(selected) ||
Adam Langleya0f1c8e2018-03-30 13:43:59 -07001621 !SpeedScrypt(selected) ||
Adam Langley7b935932018-11-12 13:53:42 -08001622 !SpeedRSAKeyGen(selected) ||
Steven Valdez188b65a2020-04-21 14:31:05 -04001623 !SpeedHRSS(selected) ||
Sophie Schmieg58472cc2023-03-07 00:39:31 +00001624 !SpeedKyber(selected) ||
Steven Valdez188b65a2020-04-21 14:31:05 -04001625 !SpeedHashToCurve(selected) ||
David Benjaminaa764c42020-04-29 12:39:10 -04001626 !SpeedTrustToken("TrustToken-Exp1-Batch1", TRUST_TOKEN_experiment_v1(), 1,
1627 selected) ||
1628 !SpeedTrustToken("TrustToken-Exp1-Batch10", TRUST_TOKEN_experiment_v1(),
Steven Valdezf2b2ef82020-09-21 11:39:22 -04001629 10, selected) ||
1630 !SpeedTrustToken("TrustToken-Exp2VOPRF-Batch1",
1631 TRUST_TOKEN_experiment_v2_voprf(), 1, selected) ||
1632 !SpeedTrustToken("TrustToken-Exp2VOPRF-Batch10",
1633 TRUST_TOKEN_experiment_v2_voprf(), 10, selected) ||
1634 !SpeedTrustToken("TrustToken-Exp2PMB-Batch1",
1635 TRUST_TOKEN_experiment_v2_pmb(), 1, selected) ||
1636 !SpeedTrustToken("TrustToken-Exp2PMB-Batch10",
David Benjaminf9587272021-09-21 16:33:15 -04001637 TRUST_TOKEN_experiment_v2_pmb(), 10, selected) ||
David Benjamin345c86b2022-01-23 11:11:17 -05001638 !SpeedBase64(selected) ||
1639 !SpeedSipHash(selected)) {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -07001640 return false;
1641 }
David Benjaminab5edbe2021-01-27 16:49:50 -05001642#if defined(BORINGSSL_FIPS)
1643 if (!SpeedSelfTest(selected)) {
1644 return false;
1645 }
1646#endif
Zola Bridgesf10ea552019-10-01 11:35:44 -07001647 if (g_print_json) {
1648 puts("\n]");
1649 }
Adam Langleyc5c0c7e2014-06-20 12:00:00 -07001650
Adam Langley90b58402015-04-13 11:04:18 -07001651 return true;
Adam Langleyc5c0c7e2014-06-20 12:00:00 -07001652}