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 <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
26 
27 #include <openssl/aead.h>
28 #include <openssl/aes.h>
29 #include <openssl/bn.h>
30 #include <openssl/curve25519.h>
31 #include <openssl/digest.h>
32 #include <openssl/err.h>
33 #include <openssl/ec.h>
34 #include <openssl/ecdsa.h>
35 #include <openssl/ec_key.h>
36 #include <openssl/evp.h>
37 #include <openssl/hrss.h>
38 #include <openssl/nid.h>
39 #include <openssl/rand.h>
40 #include <openssl/rsa.h>
41 
42 #if defined(OPENSSL_WINDOWS)
43 OPENSSL_MSVC_PRAGMA(warning(push, 3))
44 #include <windows.h>
45 OPENSSL_MSVC_PRAGMA(warning(pop))
46 #elif defined(OPENSSL_APPLE)
47 #include <sys/time.h>
48 #else
49 #include <time.h>
50 #endif
51 
52 #include "../crypto/internal.h"
53 #include "internal.h"
54 
55 // g_print_json is true if printed output is JSON formatted.
56 static bool g_print_json = false;
57 
58 // TimeResults represents the results of benchmarking a function.
59 struct TimeResults {
60   // num_calls is the number of function calls done in the time period.
61   unsigned num_calls;
62   // us is the number of microseconds that elapsed in the time period.
63   unsigned us;
64 
PrintTimeResults65   void Print(const std::string &description) const {
66     if (g_print_json) {
67       PrintJSON(description);
68     } else {
69       printf("Did %u %s operations in %uus (%.1f ops/sec)\n", num_calls,
70              description.c_str(), us,
71              (static_cast<double>(num_calls) / us) * 1000000);
72     }
73   }
74 
PrintWithBytesTimeResults75   void PrintWithBytes(const std::string &description,
76                       size_t bytes_per_call) const {
77     if (g_print_json) {
78       PrintJSON(description, bytes_per_call);
79     } else {
80       printf("Did %u %s operations in %uus (%.1f ops/sec): %.1f MB/s\n",
81              num_calls, description.c_str(), us,
82              (static_cast<double>(num_calls) / us) * 1000000,
83              static_cast<double>(bytes_per_call * num_calls) / us);
84     }
85   }
86 
87  private:
PrintJSONTimeResults88   void PrintJSON(const std::string &description,
89                  size_t bytes_per_call = 0) const {
90     if (first_json_printed) {
91       puts(",");
92     }
93 
94     printf("{\"description\": \"%s\", \"numCalls\": %u, \"microseconds\": %u",
95            description.c_str(), num_calls, us);
96 
97     if (bytes_per_call > 0) {
98       printf(", \"bytesPerCall\": %zu", bytes_per_call);
99     }
100 
101     printf("}");
102     first_json_printed = true;
103   }
104 
105   // first_json_printed is true if |g_print_json| is true and the first item in
106   // the JSON results has been printed already. This is used to handle the
107   // commas between each item in the result list.
108   static bool first_json_printed;
109 };
110 
111 bool TimeResults::first_json_printed = false;
112 
113 #if defined(OPENSSL_WINDOWS)
time_now()114 static uint64_t time_now() { return GetTickCount64() * 1000; }
115 #elif defined(OPENSSL_APPLE)
time_now()116 static uint64_t time_now() {
117   struct timeval tv;
118   uint64_t ret;
119 
120   gettimeofday(&tv, NULL);
121   ret = tv.tv_sec;
122   ret *= 1000000;
123   ret += tv.tv_usec;
124   return ret;
125 }
126 #else
time_now()127 static uint64_t time_now() {
128   struct timespec ts;
129   clock_gettime(CLOCK_MONOTONIC, &ts);
130 
131   uint64_t ret = ts.tv_sec;
132   ret *= 1000000;
133   ret += ts.tv_nsec / 1000;
134   return ret;
135 }
136 #endif
137 
138 static uint64_t g_timeout_seconds = 1;
139 static std::vector<size_t> g_chunk_lengths = {16, 256, 1350, 8192, 16384};
140 
TimeFunction(TimeResults * results,std::function<bool ()> func)141 static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
142   // total_us is the total amount of time that we'll aim to measure a function
143   // for.
144   const uint64_t total_us = g_timeout_seconds * 1000000;
145   uint64_t start = time_now(), now, delta;
146   unsigned done = 0, iterations_between_time_checks;
147 
148   if (!func()) {
149     return false;
150   }
151   now = time_now();
152   delta = now - start;
153   if (delta == 0) {
154     iterations_between_time_checks = 250;
155   } else {
156     // Aim for about 100ms between time checks.
157     iterations_between_time_checks =
158         static_cast<double>(100000) / static_cast<double>(delta);
159     if (iterations_between_time_checks > 1000) {
160       iterations_between_time_checks = 1000;
161     } else if (iterations_between_time_checks < 1) {
162       iterations_between_time_checks = 1;
163     }
164   }
165 
166   for (;;) {
167     for (unsigned i = 0; i < iterations_between_time_checks; i++) {
168       if (!func()) {
169         return false;
170       }
171       done++;
172     }
173 
174     now = time_now();
175     if (now - start > total_us) {
176       break;
177     }
178   }
179 
180   results->us = now - start;
181   results->num_calls = done;
182   return true;
183 }
184 
SpeedRSA(const std::string & selected)185 static bool SpeedRSA(const std::string &selected) {
186   if (!selected.empty() && selected.find("RSA") == std::string::npos) {
187     return true;
188   }
189 
190   static const struct {
191     const char *name;
192     const uint8_t *key;
193     const size_t key_len;
194   } kRSAKeys[] = {
195     {"RSA 2048", kDERRSAPrivate2048, kDERRSAPrivate2048Len},
196     {"RSA 4096", kDERRSAPrivate4096, kDERRSAPrivate4096Len},
197   };
198 
199   for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kRSAKeys); i++) {
200     const std::string name = kRSAKeys[i].name;
201 
202     bssl::UniquePtr<RSA> key(
203         RSA_private_key_from_bytes(kRSAKeys[i].key, kRSAKeys[i].key_len));
204     if (key == nullptr) {
205       fprintf(stderr, "Failed to parse %s key.\n", name.c_str());
206       ERR_print_errors_fp(stderr);
207       return false;
208     }
209 
210     std::unique_ptr<uint8_t[]> sig(new uint8_t[RSA_size(key.get())]);
211     const uint8_t fake_sha256_hash[32] = {0};
212     unsigned sig_len;
213 
214     TimeResults results;
215     if (!TimeFunction(&results,
216                       [&key, &sig, &fake_sha256_hash, &sig_len]() -> bool {
217           // Usually during RSA signing we're using a long-lived |RSA| that has
218           // already had all of its |BN_MONT_CTX|s constructed, so it makes
219           // sense to use |key| directly here.
220           return RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
221                           sig.get(), &sig_len, key.get());
222         })) {
223       fprintf(stderr, "RSA_sign failed.\n");
224       ERR_print_errors_fp(stderr);
225       return false;
226     }
227     results.Print(name + " signing");
228 
229     if (!TimeFunction(&results,
230                       [&key, &fake_sha256_hash, &sig, sig_len]() -> bool {
231           return RSA_verify(
232               NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
233               sig.get(), sig_len, key.get());
234         })) {
235       fprintf(stderr, "RSA_verify failed.\n");
236       ERR_print_errors_fp(stderr);
237       return false;
238     }
239     results.Print(name + " verify (same key)");
240 
241     if (!TimeFunction(&results,
242                       [&key, &fake_sha256_hash, &sig, sig_len]() -> bool {
243           // Usually during RSA verification we have to parse an RSA key from a
244           // certificate or similar, in which case we'd need to construct a new
245           // RSA key, with a new |BN_MONT_CTX| for the public modulus. If we
246           // were to use |key| directly instead, then these costs wouldn't be
247           // accounted for.
248           bssl::UniquePtr<RSA> verify_key(RSA_new());
249           if (!verify_key) {
250             return false;
251           }
252           verify_key->n = BN_dup(key->n);
253           verify_key->e = BN_dup(key->e);
254           if (!verify_key->n ||
255               !verify_key->e) {
256             return false;
257           }
258           return RSA_verify(NID_sha256, fake_sha256_hash,
259                             sizeof(fake_sha256_hash), sig.get(), sig_len,
260                             verify_key.get());
261         })) {
262       fprintf(stderr, "RSA_verify failed.\n");
263       ERR_print_errors_fp(stderr);
264       return false;
265     }
266     results.Print(name + " verify (fresh key)");
267   }
268 
269   return true;
270 }
271 
SpeedRSAKeyGen(const std::string & selected)272 static bool SpeedRSAKeyGen(const std::string &selected) {
273   // Don't run this by default because it's so slow.
274   if (selected != "RSAKeyGen") {
275     return true;
276   }
277 
278   bssl::UniquePtr<BIGNUM> e(BN_new());
279   if (!BN_set_word(e.get(), 65537)) {
280     return false;
281   }
282 
283   const std::vector<int> kSizes = {2048, 3072, 4096};
284   for (int size : kSizes) {
285     const uint64_t start = time_now();
286     unsigned num_calls = 0;
287     unsigned us;
288     std::vector<unsigned> durations;
289 
290     for (;;) {
291       bssl::UniquePtr<RSA> rsa(RSA_new());
292 
293       const uint64_t iteration_start = time_now();
294       if (!RSA_generate_key_ex(rsa.get(), size, e.get(), nullptr)) {
295         fprintf(stderr, "RSA_generate_key_ex failed.\n");
296         ERR_print_errors_fp(stderr);
297         return false;
298       }
299       const uint64_t iteration_end = time_now();
300 
301       num_calls++;
302       durations.push_back(iteration_end - iteration_start);
303 
304       us = iteration_end - start;
305       if (us > 30 * 1000000 /* 30 secs */) {
306         break;
307       }
308     }
309 
310     std::sort(durations.begin(), durations.end());
311     const std::string description =
312         std::string("RSA ") + std::to_string(size) + std::string(" key-gen");
313     const TimeResults results = {num_calls, us};
314     results.Print(description);
315     const size_t n = durations.size();
316     assert(n > 0);
317 
318     // Distribution information is useful, but doesn't fit into the standard
319     // format used by |g_print_json|.
320     if (!g_print_json) {
321       // |min| and |max| must be stored in temporary variables to avoid an MSVC
322       // bug on x86. There, size_t is a typedef for unsigned, but MSVC's printf
323       // warning tries to retain the distinction and suggest %zu for size_t
324       // instead of %u. It gets confused if std::vector<unsigned> and
325       // std::vector<size_t> are both instantiated. Being typedefs, the two
326       // instantiations are identical, which somehow breaks the size_t vs
327       // unsigned metadata.
328       unsigned min = durations[0];
329       unsigned median = n & 1 ? durations[n / 2]
330                               : (durations[n / 2 - 1] + durations[n / 2]) / 2;
331       unsigned max = durations[n - 1];
332       printf("  min: %uus, median: %uus, max: %uus\n", min, median, max);
333     }
334   }
335 
336   return true;
337 }
338 
align(uint8_t * in,unsigned alignment)339 static uint8_t *align(uint8_t *in, unsigned alignment) {
340   return reinterpret_cast<uint8_t *>(
341       (reinterpret_cast<uintptr_t>(in) + alignment) &
342       ~static_cast<size_t>(alignment - 1));
343 }
344 
ChunkLenSuffix(size_t chunk_len)345 static std::string ChunkLenSuffix(size_t chunk_len) {
346   char buf[32];
347   snprintf(buf, sizeof(buf), " (%zu byte%s)", chunk_len,
348            chunk_len != 1 ? "s" : "");
349   return buf;
350 }
351 
SpeedAEADChunk(const EVP_AEAD * aead,std::string name,size_t chunk_len,size_t ad_len,evp_aead_direction_t direction)352 static bool SpeedAEADChunk(const EVP_AEAD *aead, std::string name,
353                            size_t chunk_len, size_t ad_len,
354                            evp_aead_direction_t direction) {
355   static const unsigned kAlignment = 16;
356 
357   name += ChunkLenSuffix(chunk_len);
358   bssl::ScopedEVP_AEAD_CTX ctx;
359   const size_t key_len = EVP_AEAD_key_length(aead);
360   const size_t nonce_len = EVP_AEAD_nonce_length(aead);
361   const size_t overhead_len = EVP_AEAD_max_overhead(aead);
362 
363   std::unique_ptr<uint8_t[]> key(new uint8_t[key_len]);
364   OPENSSL_memset(key.get(), 0, key_len);
365   std::unique_ptr<uint8_t[]> nonce(new uint8_t[nonce_len]);
366   OPENSSL_memset(nonce.get(), 0, nonce_len);
367   std::unique_ptr<uint8_t[]> in_storage(new uint8_t[chunk_len + kAlignment]);
368   // N.B. for EVP_AEAD_CTX_seal_scatter the input and output buffers may be the
369   // same size. However, in the direction == evp_aead_open case we still use
370   // non-scattering seal, hence we add overhead_len to the size of this buffer.
371   std::unique_ptr<uint8_t[]> out_storage(
372       new uint8_t[chunk_len + overhead_len + kAlignment]);
373   std::unique_ptr<uint8_t[]> in2_storage(
374       new uint8_t[chunk_len + overhead_len + kAlignment]);
375   std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
376   OPENSSL_memset(ad.get(), 0, ad_len);
377   std::unique_ptr<uint8_t[]> tag_storage(
378       new uint8_t[overhead_len + kAlignment]);
379 
380 
381   uint8_t *const in = align(in_storage.get(), kAlignment);
382   OPENSSL_memset(in, 0, chunk_len);
383   uint8_t *const out = align(out_storage.get(), kAlignment);
384   OPENSSL_memset(out, 0, chunk_len + overhead_len);
385   uint8_t *const tag = align(tag_storage.get(), kAlignment);
386   OPENSSL_memset(tag, 0, overhead_len);
387   uint8_t *const in2 = align(in2_storage.get(), kAlignment);
388 
389   if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
390                                         EVP_AEAD_DEFAULT_TAG_LENGTH,
391                                         evp_aead_seal)) {
392     fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
393     ERR_print_errors_fp(stderr);
394     return false;
395   }
396 
397   TimeResults results;
398   if (direction == evp_aead_seal) {
399     if (!TimeFunction(&results,
400                       [chunk_len, nonce_len, ad_len, overhead_len, in, out, tag,
401                        &ctx, &nonce, &ad]() -> bool {
402                         size_t tag_len;
403                         return EVP_AEAD_CTX_seal_scatter(
404                             ctx.get(), out, tag, &tag_len, overhead_len,
405                             nonce.get(), nonce_len, in, chunk_len, nullptr, 0,
406                             ad.get(), ad_len);
407                       })) {
408       fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
409       ERR_print_errors_fp(stderr);
410       return false;
411     }
412   } else {
413     size_t out_len;
414     EVP_AEAD_CTX_seal(ctx.get(), out, &out_len, chunk_len + overhead_len,
415                       nonce.get(), nonce_len, in, chunk_len, ad.get(), ad_len);
416 
417     ctx.Reset();
418     if (!EVP_AEAD_CTX_init_with_direction(ctx.get(), aead, key.get(), key_len,
419                                           EVP_AEAD_DEFAULT_TAG_LENGTH,
420                                           evp_aead_open)) {
421       fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
422       ERR_print_errors_fp(stderr);
423       return false;
424     }
425 
426     if (!TimeFunction(&results,
427                       [chunk_len, overhead_len, nonce_len, ad_len, in2, out,
428                        out_len, &ctx, &nonce, &ad]() -> bool {
429                         size_t in2_len;
430                         // N.B. EVP_AEAD_CTX_open_gather is not implemented for
431                         // all AEADs.
432                         return EVP_AEAD_CTX_open(ctx.get(), in2, &in2_len,
433                                                  chunk_len + overhead_len,
434                                                  nonce.get(), nonce_len, out,
435                                                  out_len, ad.get(), ad_len);
436                       })) {
437       fprintf(stderr, "EVP_AEAD_CTX_open failed.\n");
438       ERR_print_errors_fp(stderr);
439       return false;
440     }
441   }
442 
443   results.PrintWithBytes(
444       name + (direction == evp_aead_seal ? " seal" : " open"), chunk_len);
445   return true;
446 }
447 
SpeedAEAD(const EVP_AEAD * aead,const std::string & name,size_t ad_len,const std::string & selected)448 static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
449                       size_t ad_len, const std::string &selected) {
450   if (!selected.empty() && name.find(selected) == std::string::npos) {
451     return true;
452   }
453 
454   for (size_t chunk_len : g_chunk_lengths) {
455     if (!SpeedAEADChunk(aead, name, chunk_len, ad_len, evp_aead_seal)) {
456       return false;
457     }
458   }
459   return true;
460 }
461 
SpeedAEADOpen(const EVP_AEAD * aead,const std::string & name,size_t ad_len,const std::string & selected)462 static bool SpeedAEADOpen(const EVP_AEAD *aead, const std::string &name,
463                           size_t ad_len, const std::string &selected) {
464   if (!selected.empty() && name.find(selected) == std::string::npos) {
465     return true;
466   }
467 
468   for (size_t chunk_len : g_chunk_lengths) {
469     if (!SpeedAEADChunk(aead, name, chunk_len, ad_len, evp_aead_open)) {
470       return false;
471     }
472   }
473 
474   return true;
475 }
476 
SpeedAESBlock(const std::string & name,unsigned bits,const std::string & selected)477 static bool SpeedAESBlock(const std::string &name, unsigned bits,
478                           const std::string &selected) {
479   if (!selected.empty() && name.find(selected) == std::string::npos) {
480     return true;
481   }
482 
483   static const uint8_t kZero[32] = {0};
484 
485   {
486     TimeResults results;
487     if (!TimeFunction(&results, [&]() -> bool {
488           AES_KEY key;
489           return AES_set_encrypt_key(kZero, bits, &key) == 0;
490         })) {
491       fprintf(stderr, "AES_set_encrypt_key failed.\n");
492       return false;
493     }
494     results.Print(name + " encrypt setup");
495   }
496 
497   {
498     AES_KEY key;
499     if (AES_set_encrypt_key(kZero, bits, &key) != 0) {
500       return false;
501     }
502     uint8_t block[16] = {0};
503     TimeResults results;
504     if (!TimeFunction(&results, [&]() -> bool {
505           AES_encrypt(block, block, &key);
506           return true;
507         })) {
508       fprintf(stderr, "AES_encrypt failed.\n");
509       return false;
510     }
511     results.Print(name + " encrypt");
512   }
513 
514   {
515     TimeResults results;
516     if (!TimeFunction(&results, [&]() -> bool {
517           AES_KEY key;
518           return AES_set_decrypt_key(kZero, bits, &key) == 0;
519         })) {
520       fprintf(stderr, "AES_set_decrypt_key failed.\n");
521       return false;
522     }
523     results.Print(name + " decrypt setup");
524   }
525 
526   {
527     AES_KEY key;
528     if (AES_set_decrypt_key(kZero, bits, &key) != 0) {
529       return false;
530     }
531     uint8_t block[16] = {0};
532     TimeResults results;
533     if (!TimeFunction(&results, [&]() -> bool {
534           AES_decrypt(block, block, &key);
535           return true;
536         })) {
537       fprintf(stderr, "AES_decrypt failed.\n");
538       return false;
539     }
540     results.Print(name + " decrypt");
541   }
542 
543   return true;
544 }
545 
SpeedHashChunk(const EVP_MD * md,std::string name,size_t chunk_len)546 static bool SpeedHashChunk(const EVP_MD *md, std::string name,
547                            size_t chunk_len) {
548   bssl::ScopedEVP_MD_CTX ctx;
549   uint8_t scratch[16384];
550 
551   if (chunk_len > sizeof(scratch)) {
552     return false;
553   }
554 
555   name += ChunkLenSuffix(chunk_len);
556   TimeResults results;
557   if (!TimeFunction(&results, [&ctx, md, chunk_len, &scratch]() -> bool {
558         uint8_t digest[EVP_MAX_MD_SIZE];
559         unsigned int md_len;
560 
561         return EVP_DigestInit_ex(ctx.get(), md, NULL /* ENGINE */) &&
562                EVP_DigestUpdate(ctx.get(), scratch, chunk_len) &&
563                EVP_DigestFinal_ex(ctx.get(), digest, &md_len);
564       })) {
565     fprintf(stderr, "EVP_DigestInit_ex failed.\n");
566     ERR_print_errors_fp(stderr);
567     return false;
568   }
569 
570   results.PrintWithBytes(name, chunk_len);
571   return true;
572 }
573 
SpeedHash(const EVP_MD * md,const std::string & name,const std::string & selected)574 static bool SpeedHash(const EVP_MD *md, const std::string &name,
575                       const std::string &selected) {
576   if (!selected.empty() && name.find(selected) == std::string::npos) {
577     return true;
578   }
579 
580   for (size_t chunk_len : g_chunk_lengths) {
581     if (!SpeedHashChunk(md, name, chunk_len)) {
582       return false;
583     }
584   }
585 
586   return true;
587 }
588 
SpeedRandomChunk(std::string name,size_t chunk_len)589 static bool SpeedRandomChunk(std::string name, size_t chunk_len) {
590   uint8_t scratch[16384];
591 
592   if (chunk_len > sizeof(scratch)) {
593     return false;
594   }
595 
596   name += ChunkLenSuffix(chunk_len);
597   TimeResults results;
598   if (!TimeFunction(&results, [chunk_len, &scratch]() -> bool {
599         RAND_bytes(scratch, chunk_len);
600         return true;
601       })) {
602     return false;
603   }
604 
605   results.PrintWithBytes(name, chunk_len);
606   return true;
607 }
608 
SpeedRandom(const std::string & selected)609 static bool SpeedRandom(const std::string &selected) {
610   if (!selected.empty() && selected != "RNG") {
611     return true;
612   }
613 
614   for (size_t chunk_len : g_chunk_lengths) {
615     if (!SpeedRandomChunk("RNG", chunk_len)) {
616       return false;
617     }
618   }
619 
620   return true;
621 }
622 
SpeedECDHCurve(const std::string & name,int nid,const std::string & selected)623 static bool SpeedECDHCurve(const std::string &name, int nid,
624                            const std::string &selected) {
625   if (!selected.empty() && name.find(selected) == std::string::npos) {
626     return true;
627   }
628 
629   bssl::UniquePtr<EC_KEY> peer_key(EC_KEY_new_by_curve_name(nid));
630   if (!peer_key ||
631       !EC_KEY_generate_key(peer_key.get())) {
632     return false;
633   }
634 
635   size_t peer_value_len = EC_POINT_point2oct(
636       EC_KEY_get0_group(peer_key.get()), EC_KEY_get0_public_key(peer_key.get()),
637       POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, nullptr);
638   if (peer_value_len == 0) {
639     return false;
640   }
641   std::unique_ptr<uint8_t[]> peer_value(new uint8_t[peer_value_len]);
642   peer_value_len = EC_POINT_point2oct(
643       EC_KEY_get0_group(peer_key.get()), EC_KEY_get0_public_key(peer_key.get()),
644       POINT_CONVERSION_UNCOMPRESSED, peer_value.get(), peer_value_len, nullptr);
645   if (peer_value_len == 0) {
646     return false;
647   }
648 
649   TimeResults results;
650   if (!TimeFunction(&results, [nid, peer_value_len, &peer_value]() -> bool {
651         bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
652         if (!key ||
653             !EC_KEY_generate_key(key.get())) {
654           return false;
655         }
656         const EC_GROUP *const group = EC_KEY_get0_group(key.get());
657         bssl::UniquePtr<EC_POINT> point(EC_POINT_new(group));
658         bssl::UniquePtr<EC_POINT> peer_point(EC_POINT_new(group));
659         bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new());
660 
661         bssl::UniquePtr<BIGNUM> x(BN_new());
662         bssl::UniquePtr<BIGNUM> y(BN_new());
663 
664         if (!point || !peer_point || !ctx || !x || !y ||
665             !EC_POINT_oct2point(group, peer_point.get(), peer_value.get(),
666                                 peer_value_len, ctx.get()) ||
667             !EC_POINT_mul(group, point.get(), NULL, peer_point.get(),
668                           EC_KEY_get0_private_key(key.get()), ctx.get()) ||
669             !EC_POINT_get_affine_coordinates_GFp(group, point.get(), x.get(),
670                                                  y.get(), ctx.get())) {
671           return false;
672         }
673 
674         return true;
675       })) {
676     return false;
677   }
678 
679   results.Print(name);
680   return true;
681 }
682 
SpeedECDSACurve(const std::string & name,int nid,const std::string & selected)683 static bool SpeedECDSACurve(const std::string &name, int nid,
684                             const std::string &selected) {
685   if (!selected.empty() && name.find(selected) == std::string::npos) {
686     return true;
687   }
688 
689   bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
690   if (!key ||
691       !EC_KEY_generate_key(key.get())) {
692     return false;
693   }
694 
695   uint8_t signature[256];
696   if (ECDSA_size(key.get()) > sizeof(signature)) {
697     return false;
698   }
699   uint8_t digest[20];
700   OPENSSL_memset(digest, 42, sizeof(digest));
701   unsigned sig_len;
702 
703   TimeResults results;
704   if (!TimeFunction(&results, [&key, &signature, &digest, &sig_len]() -> bool {
705         return ECDSA_sign(0, digest, sizeof(digest), signature, &sig_len,
706                           key.get()) == 1;
707       })) {
708     return false;
709   }
710 
711   results.Print(name + " signing");
712 
713   if (!TimeFunction(&results, [&key, &signature, &digest, sig_len]() -> bool {
714         return ECDSA_verify(0, digest, sizeof(digest), signature, sig_len,
715                             key.get()) == 1;
716       })) {
717     return false;
718   }
719 
720   results.Print(name + " verify");
721 
722   return true;
723 }
724 
SpeedECDH(const std::string & selected)725 static bool SpeedECDH(const std::string &selected) {
726   return SpeedECDHCurve("ECDH P-224", NID_secp224r1, selected) &&
727          SpeedECDHCurve("ECDH P-256", NID_X9_62_prime256v1, selected) &&
728          SpeedECDHCurve("ECDH P-384", NID_secp384r1, selected) &&
729          SpeedECDHCurve("ECDH P-521", NID_secp521r1, selected);
730 }
731 
SpeedECDSA(const std::string & selected)732 static bool SpeedECDSA(const std::string &selected) {
733   return SpeedECDSACurve("ECDSA P-224", NID_secp224r1, selected) &&
734          SpeedECDSACurve("ECDSA P-256", NID_X9_62_prime256v1, selected) &&
735          SpeedECDSACurve("ECDSA P-384", NID_secp384r1, selected) &&
736          SpeedECDSACurve("ECDSA P-521", NID_secp521r1, selected);
737 }
738 
Speed25519(const std::string & selected)739 static bool Speed25519(const std::string &selected) {
740   if (!selected.empty() && selected.find("25519") == std::string::npos) {
741     return true;
742   }
743 
744   TimeResults results;
745 
746   uint8_t public_key[32], private_key[64];
747 
748   if (!TimeFunction(&results, [&public_key, &private_key]() -> bool {
749         ED25519_keypair(public_key, private_key);
750         return true;
751       })) {
752     return false;
753   }
754 
755   results.Print("Ed25519 key generation");
756 
757   static const uint8_t kMessage[] = {0, 1, 2, 3, 4, 5};
758   uint8_t signature[64];
759 
760   if (!TimeFunction(&results, [&private_key, &signature]() -> bool {
761         return ED25519_sign(signature, kMessage, sizeof(kMessage),
762                             private_key) == 1;
763       })) {
764     return false;
765   }
766 
767   results.Print("Ed25519 signing");
768 
769   if (!TimeFunction(&results, [&public_key, &signature]() -> bool {
770         return ED25519_verify(kMessage, sizeof(kMessage), signature,
771                               public_key) == 1;
772       })) {
773     fprintf(stderr, "Ed25519 verify failed.\n");
774     return false;
775   }
776 
777   results.Print("Ed25519 verify");
778 
779   if (!TimeFunction(&results, []() -> bool {
780         uint8_t out[32], in[32];
781         OPENSSL_memset(in, 0, sizeof(in));
782         X25519_public_from_private(out, in);
783         return true;
784       })) {
785     fprintf(stderr, "Curve25519 base-point multiplication failed.\n");
786     return false;
787   }
788 
789   results.Print("Curve25519 base-point multiplication");
790 
791   if (!TimeFunction(&results, []() -> bool {
792         uint8_t out[32], in1[32], in2[32];
793         OPENSSL_memset(in1, 0, sizeof(in1));
794         OPENSSL_memset(in2, 0, sizeof(in2));
795         in1[0] = 1;
796         in2[0] = 9;
797         return X25519(out, in1, in2) == 1;
798       })) {
799     fprintf(stderr, "Curve25519 arbitrary point multiplication failed.\n");
800     return false;
801   }
802 
803   results.Print("Curve25519 arbitrary point multiplication");
804 
805   return true;
806 }
807 
SpeedSPAKE2(const std::string & selected)808 static bool SpeedSPAKE2(const std::string &selected) {
809   if (!selected.empty() && selected.find("SPAKE2") == std::string::npos) {
810     return true;
811   }
812 
813   TimeResults results;
814 
815   static const uint8_t kAliceName[] = {'A'};
816   static const uint8_t kBobName[] = {'B'};
817   static const uint8_t kPassword[] = "password";
818   bssl::UniquePtr<SPAKE2_CTX> alice(SPAKE2_CTX_new(spake2_role_alice,
819                                     kAliceName, sizeof(kAliceName), kBobName,
820                                     sizeof(kBobName)));
821   uint8_t alice_msg[SPAKE2_MAX_MSG_SIZE];
822   size_t alice_msg_len;
823 
824   if (!SPAKE2_generate_msg(alice.get(), alice_msg, &alice_msg_len,
825                            sizeof(alice_msg),
826                            kPassword, sizeof(kPassword))) {
827     fprintf(stderr, "SPAKE2_generate_msg failed.\n");
828     return false;
829   }
830 
831   if (!TimeFunction(&results, [&alice_msg, alice_msg_len]() -> bool {
832         bssl::UniquePtr<SPAKE2_CTX> bob(SPAKE2_CTX_new(spake2_role_bob,
833                                         kBobName, sizeof(kBobName), kAliceName,
834                                         sizeof(kAliceName)));
835         uint8_t bob_msg[SPAKE2_MAX_MSG_SIZE], bob_key[64];
836         size_t bob_msg_len, bob_key_len;
837         if (!SPAKE2_generate_msg(bob.get(), bob_msg, &bob_msg_len,
838                                  sizeof(bob_msg), kPassword,
839                                  sizeof(kPassword)) ||
840             !SPAKE2_process_msg(bob.get(), bob_key, &bob_key_len,
841                                 sizeof(bob_key), alice_msg, alice_msg_len)) {
842           return false;
843         }
844 
845         return true;
846       })) {
847     fprintf(stderr, "SPAKE2 failed.\n");
848   }
849 
850   results.Print("SPAKE2 over Ed25519");
851 
852   return true;
853 }
854 
SpeedScrypt(const std::string & selected)855 static bool SpeedScrypt(const std::string &selected) {
856   if (!selected.empty() && selected.find("scrypt") == std::string::npos) {
857     return true;
858   }
859 
860   TimeResults results;
861 
862   static const char kPassword[] = "password";
863   static const uint8_t kSalt[] = "NaCl";
864 
865   if (!TimeFunction(&results, [&]() -> bool {
866         uint8_t out[64];
867         return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
868                                 sizeof(kSalt) - 1, 1024, 8, 16, 0 /* max_mem */,
869                                 out, sizeof(out));
870       })) {
871     fprintf(stderr, "scrypt failed.\n");
872     return false;
873   }
874   results.Print("scrypt (N = 1024, r = 8, p = 16)");
875 
876   if (!TimeFunction(&results, [&]() -> bool {
877         uint8_t out[64];
878         return !!EVP_PBE_scrypt(kPassword, sizeof(kPassword) - 1, kSalt,
879                                 sizeof(kSalt) - 1, 16384, 8, 1, 0 /* max_mem */,
880                                 out, sizeof(out));
881       })) {
882     fprintf(stderr, "scrypt failed.\n");
883     return false;
884   }
885   results.Print("scrypt (N = 16384, r = 8, p = 1)");
886 
887   return true;
888 }
889 
SpeedHRSS(const std::string & selected)890 static bool SpeedHRSS(const std::string &selected) {
891   if (!selected.empty() && selected != "HRSS") {
892     return true;
893   }
894 
895   TimeResults results;
896 
897   if (!TimeFunction(&results, []() -> bool {
898     struct HRSS_public_key pub;
899     struct HRSS_private_key priv;
900     uint8_t entropy[HRSS_GENERATE_KEY_BYTES];
901     RAND_bytes(entropy, sizeof(entropy));
902     HRSS_generate_key(&pub, &priv, entropy);
903     return true;
904   })) {
905     fprintf(stderr, "Failed to time HRSS_generate_key.\n");
906     return false;
907   }
908 
909   results.Print("HRSS generate");
910 
911   struct HRSS_public_key pub;
912   struct HRSS_private_key priv;
913   uint8_t key_entropy[HRSS_GENERATE_KEY_BYTES];
914   RAND_bytes(key_entropy, sizeof(key_entropy));
915   HRSS_generate_key(&pub, &priv, key_entropy);
916 
917   uint8_t ciphertext[HRSS_CIPHERTEXT_BYTES];
918   if (!TimeFunction(&results, [&pub, &ciphertext]() -> bool {
919     uint8_t entropy[HRSS_ENCAP_BYTES];
920     uint8_t shared_key[HRSS_KEY_BYTES];
921     RAND_bytes(entropy, sizeof(entropy));
922     HRSS_encap(ciphertext, shared_key, &pub, entropy);
923     return true;
924   })) {
925     fprintf(stderr, "Failed to time HRSS_encap.\n");
926     return false;
927   }
928 
929   results.Print("HRSS encap");
930 
931   if (!TimeFunction(&results, [&priv, &ciphertext]() -> bool {
932     uint8_t shared_key[HRSS_KEY_BYTES];
933     HRSS_decap(shared_key, &priv, ciphertext, sizeof(ciphertext));
934     return true;
935   })) {
936     fprintf(stderr, "Failed to time HRSS_encap.\n");
937     return false;
938   }
939 
940   results.Print("HRSS decap");
941 
942   return true;
943 }
944 
945 static const struct argument kArguments[] = {
946     {
947         "-filter",
948         kOptionalArgument,
949         "A filter on the speed tests to run",
950     },
951     {
952         "-timeout",
953         kOptionalArgument,
954         "The number of seconds to run each test for (default is 1)",
955     },
956     {
957         "-chunks",
958         kOptionalArgument,
959         "A comma-separated list of input sizes to run tests at (default is "
960         "16,256,1350,8192,16384)",
961     },
962     {
963         "-json",
964         kBooleanArgument,
965         "If this flag is set, speed will print the output of each benchmark in "
966         "JSON format as follows: \"{\"description\": "
967         "\"descriptionOfOperation\", \"numCalls\": 1234, "
968         "\"timeInMicroseconds\": 1234567, \"bytesPerCall\": 1234}\". When "
969         "there is no information about the bytes per call for an  operation, "
970         "the JSON field for bytesPerCall will be omitted.",
971     },
972     {
973         "",
974         kOptionalArgument,
975         "",
976     },
977 };
978 
Speed(const std::vector<std::string> & args)979 bool Speed(const std::vector<std::string> &args) {
980   std::map<std::string, std::string> args_map;
981   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
982     PrintUsage(kArguments);
983     return false;
984   }
985 
986   std::string selected;
987   if (args_map.count("-filter") != 0) {
988     selected = args_map["-filter"];
989   }
990 
991   if (args_map.count("-json") != 0) {
992     g_print_json = true;
993   }
994 
995   if (args_map.count("-timeout") != 0) {
996     g_timeout_seconds = atoi(args_map["-timeout"].c_str());
997   }
998 
999   if (args_map.count("-chunks") != 0) {
1000     g_chunk_lengths.clear();
1001     const char *start = args_map["-chunks"].data();
1002     const char *end = start + args_map["-chunks"].size();
1003     while (start != end) {
1004       errno = 0;
1005       char *ptr;
1006       unsigned long long val = strtoull(start, &ptr, 10);
1007       if (ptr == start /* no numeric characters found */ ||
1008           errno == ERANGE /* overflow */ ||
1009           static_cast<size_t>(val) != val) {
1010         fprintf(stderr, "Error parsing -chunks argument\n");
1011         return false;
1012       }
1013       g_chunk_lengths.push_back(static_cast<size_t>(val));
1014       start = ptr;
1015       if (start != end) {
1016         if (*start != ',') {
1017           fprintf(stderr, "Error parsing -chunks argument\n");
1018           return false;
1019         }
1020         start++;
1021       }
1022     }
1023   }
1024 
1025   // kTLSADLen is the number of bytes of additional data that TLS passes to
1026   // AEADs.
1027   static const size_t kTLSADLen = 13;
1028   // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
1029   // These are AEADs that weren't originally defined as AEADs, but which we use
1030   // via the AEAD interface. In order for that to work, they have some TLS
1031   // knowledge in them and construct a couple of the AD bytes internally.
1032   static const size_t kLegacyADLen = kTLSADLen - 2;
1033 
1034   if (g_print_json) {
1035     puts("[");
1036   }
1037   if (!SpeedRSA(selected) ||
1038       !SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen, selected) ||
1039       !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen, selected) ||
1040       !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen,
1041                  selected) ||
1042       !SpeedAEAD(EVP_aead_des_ede3_cbc_sha1_tls(), "DES-EDE3-CBC-SHA1",
1043                  kLegacyADLen, selected) ||
1044       !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
1045                  kLegacyADLen, selected) ||
1046       !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
1047                  kLegacyADLen, selected) ||
1048       !SpeedAEADOpen(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
1049                      kLegacyADLen, selected) ||
1050       !SpeedAEADOpen(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
1051                      kLegacyADLen, selected) ||
1052       !SpeedAEAD(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
1053                  selected) ||
1054       !SpeedAEAD(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
1055                  selected) ||
1056       !SpeedAEADOpen(EVP_aead_aes_128_gcm_siv(), "AES-128-GCM-SIV", kTLSADLen,
1057                      selected) ||
1058       !SpeedAEADOpen(EVP_aead_aes_256_gcm_siv(), "AES-256-GCM-SIV", kTLSADLen,
1059                      selected) ||
1060       !SpeedAEAD(EVP_aead_aes_128_ccm_bluetooth(), "AES-128-CCM-Bluetooth",
1061                  kTLSADLen, selected) ||
1062       !SpeedAESBlock("AES-128", 128, selected) ||
1063       !SpeedAESBlock("AES-256", 256, selected) ||
1064       !SpeedHash(EVP_sha1(), "SHA-1", selected) ||
1065       !SpeedHash(EVP_sha256(), "SHA-256", selected) ||
1066       !SpeedHash(EVP_sha512(), "SHA-512", selected) ||
1067       !SpeedRandom(selected) ||
1068       !SpeedECDH(selected) ||
1069       !SpeedECDSA(selected) ||
1070       !Speed25519(selected) ||
1071       !SpeedSPAKE2(selected) ||
1072       !SpeedScrypt(selected) ||
1073       !SpeedRSAKeyGen(selected) ||
1074       !SpeedHRSS(selected)) {
1075     return false;
1076   }
1077   if (g_print_json) {
1078     puts("\n]");
1079   }
1080 
1081   return true;
1082 }
1083