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