• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <string>
16 #include <functional>
17 #include <memory>
18 #include <vector>
19 
20 #include <stdint.h>
21 #include <string.h>
22 
23 #include <openssl/aead.h>
24 #include <openssl/digest.h>
25 #include <openssl/err.h>
26 #include <openssl/obj.h>
27 #include <openssl/rand.h>
28 #include <openssl/rsa.h>
29 
30 #if defined(OPENSSL_WINDOWS)
31 #pragma warning(push, 3)
32 #include <windows.h>
33 #pragma warning(pop)
34 #elif defined(OPENSSL_APPLE)
35 #include <sys/time.h>
36 #endif
37 
38 #include "../crypto/test/scoped_types.h"
39 
40 
41 extern "C" {
42 // These values are DER encoded, RSA private keys.
43 extern const uint8_t kDERRSAPrivate2048[];
44 extern size_t kDERRSAPrivate2048Len;
45 extern const uint8_t kDERRSAPrivate4096[];
46 extern size_t kDERRSAPrivate4096Len;
47 }
48 
49 // TimeResults represents the results of benchmarking a function.
50 struct TimeResults {
51   // num_calls is the number of function calls done in the time period.
52   unsigned num_calls;
53   // us is the number of microseconds that elapsed in the time period.
54   unsigned us;
55 
PrintTimeResults56   void Print(const std::string &description) {
57     printf("Did %u %s operations in %uus (%.1f ops/sec)\n", num_calls,
58            description.c_str(), us,
59            (static_cast<double>(num_calls) / us) * 1000000);
60   }
61 
PrintWithBytesTimeResults62   void PrintWithBytes(const std::string &description, size_t bytes_per_call) {
63     printf("Did %u %s operations in %uus (%.1f ops/sec): %.1f MB/s\n",
64            num_calls, description.c_str(), us,
65            (static_cast<double>(num_calls) / us) * 1000000,
66            static_cast<double>(bytes_per_call * num_calls) / us);
67   }
68 };
69 
70 #if defined(OPENSSL_WINDOWS)
time_now()71 static uint64_t time_now() { return GetTickCount64() * 1000; }
72 #elif defined(OPENSSL_APPLE)
time_now()73 static uint64_t time_now() {
74   struct timeval tv;
75   uint64_t ret;
76 
77   gettimeofday(&tv, NULL);
78   ret = tv.tv_sec;
79   ret *= 1000000;
80   ret += tv.tv_usec;
81   return ret;
82 }
83 #else
time_now()84 static uint64_t time_now() {
85   struct timespec ts;
86   clock_gettime(CLOCK_MONOTONIC, &ts);
87 
88   uint64_t ret = ts.tv_sec;
89   ret *= 1000000;
90   ret += ts.tv_nsec / 1000;
91   return ret;
92 }
93 #endif
94 
TimeFunction(TimeResults * results,std::function<bool ()> func)95 static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
96   // kTotalMS is the total amount of time that we'll aim to measure a function
97   // for.
98   static const uint64_t kTotalUS = 1000000;
99   uint64_t start = time_now(), now, delta;
100   unsigned done = 0, iterations_between_time_checks;
101 
102   if (!func()) {
103     return false;
104   }
105   now = time_now();
106   delta = now - start;
107   if (delta == 0) {
108     iterations_between_time_checks = 250;
109   } else {
110     // Aim for about 100ms between time checks.
111     iterations_between_time_checks =
112         static_cast<double>(100000) / static_cast<double>(delta);
113     if (iterations_between_time_checks > 1000) {
114       iterations_between_time_checks = 1000;
115     } else if (iterations_between_time_checks < 1) {
116       iterations_between_time_checks = 1;
117     }
118   }
119 
120   for (;;) {
121     for (unsigned i = 0; i < iterations_between_time_checks; i++) {
122       if (!func()) {
123         return false;
124       }
125       done++;
126     }
127 
128     now = time_now();
129     if (now - start > kTotalUS) {
130       break;
131     }
132   }
133 
134   results->us = now - start;
135   results->num_calls = done;
136   return true;
137 }
138 
SpeedRSA(const std::string & key_name,RSA * key,const std::string & selected)139 static bool SpeedRSA(const std::string &key_name, RSA *key,
140                      const std::string &selected) {
141   if (!selected.empty() && key_name.find(selected) == std::string::npos) {
142     return true;
143   }
144 
145   std::unique_ptr<uint8_t[]> sig(new uint8_t[RSA_size(key)]);
146   const uint8_t fake_sha256_hash[32] = {0};
147   unsigned sig_len;
148 
149   TimeResults results;
150   if (!TimeFunction(&results,
151                     [key, &sig, &fake_sha256_hash, &sig_len]() -> bool {
152         return RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
153                         sig.get(), &sig_len, key);
154       })) {
155     fprintf(stderr, "RSA_sign failed.\n");
156     ERR_print_errors_fp(stderr);
157     return false;
158   }
159   results.Print(key_name + " signing");
160 
161   if (!TimeFunction(&results,
162                     [key, &fake_sha256_hash, &sig, sig_len]() -> bool {
163         return RSA_verify(NID_sha256, fake_sha256_hash,
164                           sizeof(fake_sha256_hash), sig.get(), sig_len, key);
165       })) {
166     fprintf(stderr, "RSA_verify failed.\n");
167     ERR_print_errors_fp(stderr);
168     return false;
169   }
170   results.Print(key_name + " verify");
171 
172   return true;
173 }
174 
align(uint8_t * in,unsigned alignment)175 static uint8_t *align(uint8_t *in, unsigned alignment) {
176   return reinterpret_cast<uint8_t *>(
177       (reinterpret_cast<uintptr_t>(in) + alignment) &
178       ~static_cast<size_t>(alignment - 1));
179 }
180 
SpeedAEADChunk(const EVP_AEAD * aead,const std::string & name,size_t chunk_len,size_t ad_len)181 static bool SpeedAEADChunk(const EVP_AEAD *aead, const std::string &name,
182                            size_t chunk_len, size_t ad_len) {
183   static const unsigned kAlignment = 16;
184 
185   EVP_AEAD_CTX ctx;
186   const size_t key_len = EVP_AEAD_key_length(aead);
187   const size_t nonce_len = EVP_AEAD_nonce_length(aead);
188   const size_t overhead_len = EVP_AEAD_max_overhead(aead);
189 
190   std::unique_ptr<uint8_t[]> key(new uint8_t[key_len]);
191   memset(key.get(), 0, key_len);
192   std::unique_ptr<uint8_t[]> nonce(new uint8_t[nonce_len]);
193   memset(nonce.get(), 0, nonce_len);
194   std::unique_ptr<uint8_t[]> in_storage(new uint8_t[chunk_len + kAlignment]);
195   std::unique_ptr<uint8_t[]> out_storage(new uint8_t[chunk_len + overhead_len + kAlignment]);
196   std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
197   memset(ad.get(), 0, ad_len);
198 
199   uint8_t *const in = align(in_storage.get(), kAlignment);
200   memset(in, 0, chunk_len);
201   uint8_t *const out = align(out_storage.get(), kAlignment);
202   memset(out, 0, chunk_len + overhead_len);
203 
204   if (!EVP_AEAD_CTX_init_with_direction(&ctx, aead, key.get(), key_len,
205                                         EVP_AEAD_DEFAULT_TAG_LENGTH,
206                                         evp_aead_seal)) {
207     fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
208     ERR_print_errors_fp(stderr);
209     return false;
210   }
211 
212   TimeResults results;
213   if (!TimeFunction(&results, [chunk_len, overhead_len, nonce_len, ad_len, in,
214                                out, &ctx, &nonce, &ad]() -> bool {
215         size_t out_len;
216 
217         return EVP_AEAD_CTX_seal(
218             &ctx, out, &out_len, chunk_len + overhead_len, nonce.get(),
219             nonce_len, in, chunk_len, ad.get(), ad_len);
220       })) {
221     fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
222     ERR_print_errors_fp(stderr);
223     return false;
224   }
225 
226   results.PrintWithBytes(name + " seal", chunk_len);
227 
228   EVP_AEAD_CTX_cleanup(&ctx);
229 
230   return true;
231 }
232 
SpeedAEAD(const EVP_AEAD * aead,const std::string & name,size_t ad_len,const std::string & selected)233 static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
234                       size_t ad_len, const std::string &selected) {
235   if (!selected.empty() && name.find(selected) == std::string::npos) {
236     return true;
237   }
238 
239   return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len) &&
240          SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len) &&
241          SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len);
242 }
243 
SpeedHashChunk(const EVP_MD * md,const std::string & name,size_t chunk_len)244 static bool SpeedHashChunk(const EVP_MD *md, const std::string &name,
245                            size_t chunk_len) {
246   EVP_MD_CTX *ctx = EVP_MD_CTX_create();
247   uint8_t scratch[8192];
248 
249   if (chunk_len > sizeof(scratch)) {
250     return false;
251   }
252 
253   TimeResults results;
254   if (!TimeFunction(&results, [ctx, md, chunk_len, &scratch]() -> bool {
255         uint8_t digest[EVP_MAX_MD_SIZE];
256         unsigned int md_len;
257 
258         return EVP_DigestInit_ex(ctx, md, NULL /* ENGINE */) &&
259                EVP_DigestUpdate(ctx, scratch, chunk_len) &&
260                EVP_DigestFinal_ex(ctx, digest, &md_len);
261       })) {
262     fprintf(stderr, "EVP_DigestInit_ex failed.\n");
263     ERR_print_errors_fp(stderr);
264     return false;
265   }
266 
267   results.PrintWithBytes(name, chunk_len);
268 
269   EVP_MD_CTX_destroy(ctx);
270 
271   return true;
272 }
SpeedHash(const EVP_MD * md,const std::string & name,const std::string & selected)273 static bool SpeedHash(const EVP_MD *md, const std::string &name,
274                       const std::string &selected) {
275   if (!selected.empty() && name.find(selected) == std::string::npos) {
276     return true;
277   }
278 
279   return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
280          SpeedHashChunk(md, name + " (256 bytes)", 256) &&
281          SpeedHashChunk(md, name + " (8192 bytes)", 8192);
282 }
283 
SpeedRandomChunk(const std::string name,size_t chunk_len)284 static bool SpeedRandomChunk(const std::string name, size_t chunk_len) {
285   uint8_t scratch[8192];
286 
287   if (chunk_len > sizeof(scratch)) {
288     return false;
289   }
290 
291   TimeResults results;
292   if (!TimeFunction(&results, [chunk_len, &scratch]() -> bool {
293         RAND_bytes(scratch, chunk_len);
294         return true;
295       })) {
296     return false;
297   }
298 
299   results.PrintWithBytes(name, chunk_len);
300   return true;
301 }
302 
SpeedRandom(const std::string & selected)303 static bool SpeedRandom(const std::string &selected) {
304   if (!selected.empty() && selected != "RNG") {
305     return true;
306   }
307 
308   return SpeedRandomChunk("RNG (16 bytes)", 16) &&
309          SpeedRandomChunk("RNG (256 bytes)", 256) &&
310          SpeedRandomChunk("RNG (8192 bytes)", 8192);
311 }
312 
SpeedECDHCurve(const std::string & name,int nid,const std::string & selected)313 static bool SpeedECDHCurve(const std::string &name, int nid,
314                            const std::string &selected) {
315   if (!selected.empty() && name.find(selected) == std::string::npos) {
316     return true;
317   }
318 
319   TimeResults results;
320   if (!TimeFunction(&results, [nid]() -> bool {
321         ScopedEC_KEY key(EC_KEY_new_by_curve_name(nid));
322         if (!key ||
323             !EC_KEY_generate_key(key.get())) {
324           return false;
325         }
326         const EC_GROUP *const group = EC_KEY_get0_group(key.get());
327         ScopedEC_POINT point(EC_POINT_new(group));
328         ScopedBN_CTX ctx(BN_CTX_new());
329 
330         ScopedBIGNUM x(BN_new());
331         ScopedBIGNUM y(BN_new());
332 
333         if (!point || !ctx || !x || !y ||
334             !EC_POINT_mul(group, point.get(), NULL,
335                           EC_KEY_get0_public_key(key.get()),
336                           EC_KEY_get0_private_key(key.get()), ctx.get()) ||
337             !EC_POINT_get_affine_coordinates_GFp(group, point.get(), x.get(),
338                                                  y.get(), ctx.get())) {
339           return false;
340         }
341 
342         return true;
343       })) {
344     return false;
345   }
346 
347   results.Print(name);
348   return true;
349 }
350 
SpeedECDSACurve(const std::string & name,int nid,const std::string & selected)351 static bool SpeedECDSACurve(const std::string &name, int nid,
352                             const std::string &selected) {
353   if (!selected.empty() && name.find(selected) == std::string::npos) {
354     return true;
355   }
356 
357   ScopedEC_KEY key(EC_KEY_new_by_curve_name(nid));
358   if (!key ||
359       !EC_KEY_generate_key(key.get())) {
360     return false;
361   }
362 
363   uint8_t signature[256];
364   if (ECDSA_size(key.get()) > sizeof(signature)) {
365     return false;
366   }
367   uint8_t digest[20];
368   memset(digest, 42, sizeof(digest));
369   unsigned sig_len;
370 
371   TimeResults results;
372   if (!TimeFunction(&results, [&key, &signature, &digest, &sig_len]() -> bool {
373         return ECDSA_sign(0, digest, sizeof(digest), signature, &sig_len,
374                           key.get()) == 1;
375       })) {
376     return false;
377   }
378 
379   results.Print(name + " signing");
380 
381   if (!TimeFunction(&results, [&key, &signature, &digest, sig_len]() -> bool {
382         return ECDSA_verify(0, digest, sizeof(digest), signature, sig_len,
383                             key.get()) == 1;
384       })) {
385     return false;
386   }
387 
388   results.Print(name + " verify");
389 
390   return true;
391 }
392 
SpeedECDH(const std::string & selected)393 static bool SpeedECDH(const std::string &selected) {
394   return SpeedECDHCurve("ECDH P-224", NID_secp224r1, selected) &&
395          SpeedECDHCurve("ECDH P-256", NID_X9_62_prime256v1, selected) &&
396          SpeedECDHCurve("ECDH P-384", NID_secp384r1, selected) &&
397          SpeedECDHCurve("ECDH P-521", NID_secp521r1, selected);
398 }
399 
SpeedECDSA(const std::string & selected)400 static bool SpeedECDSA(const std::string &selected) {
401   return SpeedECDSACurve("ECDSA P-224", NID_secp224r1, selected) &&
402          SpeedECDSACurve("ECDSA P-256", NID_X9_62_prime256v1, selected) &&
403          SpeedECDSACurve("ECDSA P-384", NID_secp384r1, selected) &&
404          SpeedECDSACurve("ECDSA P-521", NID_secp521r1, selected);
405 }
406 
Speed(const std::vector<std::string> & args)407 bool Speed(const std::vector<std::string> &args) {
408   std::string selected;
409   if (args.size() > 1) {
410     fprintf(stderr, "Usage: bssl speed [speed test selector, i.e. 'RNG']\n");
411     return false;
412   }
413   if (args.size() > 0) {
414     selected = args[0];
415   }
416 
417   RSA *key = NULL;
418   const uint8_t *inp = kDERRSAPrivate2048;
419   if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate2048Len)) {
420     fprintf(stderr, "Failed to parse RSA key.\n");
421     ERR_print_errors_fp(stderr);
422     return false;
423   }
424 
425   if (!SpeedRSA("RSA 2048", key, selected)) {
426     return false;
427   }
428 
429   RSA_free(key);
430   key = NULL;
431 
432   inp = kDERRSAPrivate4096;
433   if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate4096Len)) {
434     fprintf(stderr, "Failed to parse 4096-bit RSA key.\n");
435     ERR_print_errors_fp(stderr);
436     return 1;
437   }
438 
439   if (!SpeedRSA("RSA 4096", key, selected)) {
440     return false;
441   }
442 
443   RSA_free(key);
444 
445   // kTLSADLen is the number of bytes of additional data that TLS passes to
446   // AEADs.
447   static const size_t kTLSADLen = 13;
448   // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
449   // These are AEADs that weren't originally defined as AEADs, but which we use
450   // via the AEAD interface. In order for that to work, they have some TLS
451   // knowledge in them and construct a couple of the AD bytes internally.
452   static const size_t kLegacyADLen = kTLSADLen - 2;
453 
454   if (!SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen, selected) ||
455       !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen, selected) ||
456       !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen,
457                  selected) ||
458       !SpeedAEAD(EVP_aead_rc4_md5_tls(), "RC4-MD5", kLegacyADLen, selected) ||
459       !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
460                  kLegacyADLen, selected) ||
461       !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
462                  kLegacyADLen, selected) ||
463       !SpeedHash(EVP_sha1(), "SHA-1", selected) ||
464       !SpeedHash(EVP_sha256(), "SHA-256", selected) ||
465       !SpeedHash(EVP_sha512(), "SHA-512", selected) ||
466       !SpeedRandom(selected) ||
467       !SpeedECDH(selected) ||
468       !SpeedECDSA(selected)) {
469     return false;
470   }
471 
472   return true;
473 }
474