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 <time.h>
22
23#include <openssl/aead.h>
24#include <openssl/bio.h>
25#include <openssl/digest.h>
26#include <openssl/obj.h>
27#include <openssl/rsa.h>
28
29#if defined(OPENSSL_WINDOWS)
30#include <Windows.h>
31#elif defined(OPENSSL_APPLE)
32#include <sys/time.h>
33#endif
34
35extern "C" {
36// These values are DER encoded, RSA private keys.
37extern const uint8_t kDERRSAPrivate2048[];
38extern size_t kDERRSAPrivate2048Len;
39extern const uint8_t kDERRSAPrivate4096[];
40extern size_t kDERRSAPrivate4096Len;
41}
42
43// TimeResults represents the results of benchmarking a function.
44struct TimeResults {
45  // num_calls is the number of function calls done in the time period.
46  unsigned num_calls;
47  // us is the number of microseconds that elapsed in the time period.
48  unsigned us;
49
50  void Print(const std::string &description) {
51    printf("Did %u %s operations in %uus (%.1f ops/sec)\n", num_calls,
52           description.c_str(), us,
53           (static_cast<double>(num_calls) / us) * 1000000);
54  }
55
56  void PrintWithBytes(const std::string &description, size_t bytes_per_call) {
57    printf("Did %u %s operations in %uus (%.1f ops/sec): %.1f MB/s\n",
58           num_calls, description.c_str(), us,
59           (static_cast<double>(num_calls) / us) * 1000000,
60           static_cast<double>(bytes_per_call * num_calls) / us);
61  }
62};
63
64#if defined(OPENSSL_WINDOWS)
65static uint64_t time_now() { return GetTickCount64() * 1000; }
66#elif defined(OPENSSL_APPLE)
67static uint64_t time_now() {
68  struct timeval tv;
69  uint64_t ret;
70
71  gettimeofday(&tv, NULL);
72  ret = tv.tv_sec;
73  ret *= 1000000;
74  ret += tv.tv_usec;
75  return ret;
76}
77#else
78static uint64_t time_now() {
79  struct timespec ts;
80  clock_gettime(CLOCK_MONOTONIC, &ts);
81
82  uint64_t ret = ts.tv_sec;
83  ret *= 1000000;
84  ret += ts.tv_nsec / 1000;
85  return ret;
86}
87#endif
88
89static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
90  // kTotalMS is the total amount of time that we'll aim to measure a function
91  // for.
92  static const uint64_t kTotalUS = 3000000;
93  uint64_t start = time_now(), now, delta;
94  unsigned done = 0, iterations_between_time_checks;
95
96  if (!func()) {
97    return false;
98  }
99  now = time_now();
100  delta = now - start;
101  if (delta == 0) {
102    iterations_between_time_checks = 250;
103  } else {
104    // Aim for about 100ms between time checks.
105    iterations_between_time_checks =
106        static_cast<double>(100000) / static_cast<double>(delta);
107    if (iterations_between_time_checks > 1000) {
108      iterations_between_time_checks = 1000;
109    } else if (iterations_between_time_checks < 1) {
110      iterations_between_time_checks = 1;
111    }
112  }
113
114  for (;;) {
115    for (unsigned i = 0; i < iterations_between_time_checks; i++) {
116      if (!func()) {
117        return false;
118      }
119      done++;
120    }
121
122    now = time_now();
123    if (now - start > kTotalUS) {
124      break;
125    }
126  }
127
128  results->us = now - start;
129  results->num_calls = done;
130  return true;
131}
132
133static bool SpeedRSA(const std::string& key_name, RSA *key) {
134  TimeResults results;
135
136  std::unique_ptr<uint8_t[]> sig(new uint8_t[RSA_size(key)]);
137  const uint8_t fake_sha256_hash[32] = {0};
138  unsigned sig_len;
139
140  if (!TimeFunction(&results,
141                    [key, &sig, &fake_sha256_hash, &sig_len]() -> bool {
142        return RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
143                        sig.get(), &sig_len, key);
144      })) {
145    fprintf(stderr, "RSA_sign failed.\n");
146    BIO_print_errors_fp(stderr);
147    return false;
148  }
149  results.Print(key_name + " signing");
150
151  if (!TimeFunction(&results,
152                    [key, &fake_sha256_hash, &sig, sig_len]() -> bool {
153        return RSA_verify(NID_sha256, fake_sha256_hash,
154                          sizeof(fake_sha256_hash), sig.get(), sig_len, key);
155      })) {
156    fprintf(stderr, "RSA_verify failed.\n");
157    BIO_print_errors_fp(stderr);
158    return false;
159  }
160  results.Print(key_name + " verify");
161
162  return true;
163}
164
165static bool SpeedAEADChunk(const EVP_AEAD *aead, const std::string &name,
166                           size_t chunk_len) {
167  EVP_AEAD_CTX ctx;
168  const size_t key_len = EVP_AEAD_key_length(aead);
169  const size_t nonce_len = EVP_AEAD_nonce_length(aead);
170  const size_t overhead_len = EVP_AEAD_max_overhead(aead);
171
172  std::unique_ptr<uint8_t[]> key(new uint8_t[key_len]);
173  memset(key.get(), 0, key_len);
174  std::unique_ptr<uint8_t[]> nonce(new uint8_t[nonce_len]);
175  memset(nonce.get(), 0, nonce_len);
176  std::unique_ptr<uint8_t[]> in(new uint8_t[chunk_len]);
177  memset(in.get(), 0, chunk_len);
178  std::unique_ptr<uint8_t[]> out(new uint8_t[chunk_len + overhead_len]);
179  memset(out.get(), 0, chunk_len + overhead_len);
180
181  if (!EVP_AEAD_CTX_init(&ctx, aead, key.get(), key_len,
182                         EVP_AEAD_DEFAULT_TAG_LENGTH, NULL)) {
183    fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
184    BIO_print_errors_fp(stderr);
185    return false;
186  }
187
188  TimeResults results;
189  if (!TimeFunction(&results, [chunk_len, overhead_len, nonce_len, &in, &out,
190                               &ctx, &nonce]() -> bool {
191        size_t out_len;
192
193        return EVP_AEAD_CTX_seal(&ctx, out.get(), &out_len,
194                                 chunk_len + overhead_len, nonce.get(),
195                                 nonce_len, in.get(), chunk_len, NULL, 0);
196      })) {
197    fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
198    BIO_print_errors_fp(stderr);
199    return false;
200  }
201
202  results.PrintWithBytes(name + " seal", chunk_len);
203
204  EVP_AEAD_CTX_cleanup(&ctx);
205
206  return true;
207}
208
209static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name) {
210  return SpeedAEADChunk(aead, name + " (16 bytes)", 16) &&
211         SpeedAEADChunk(aead, name + " (1350 bytes)", 1350) &&
212         SpeedAEADChunk(aead, name + " (8192 bytes)", 8192);
213}
214
215static bool SpeedHashChunk(const EVP_MD *md, const std::string &name,
216                           size_t chunk_len) {
217  EVP_MD_CTX *ctx = EVP_MD_CTX_create();
218  uint8_t scratch[8192];
219
220  if (chunk_len > sizeof(scratch)) {
221    return false;
222  }
223
224  TimeResults results;
225  if (!TimeFunction(&results, [ctx, md, chunk_len, &scratch]() -> bool {
226        uint8_t digest[EVP_MAX_MD_SIZE];
227        unsigned int md_len;
228
229        return EVP_DigestInit_ex(ctx, md, NULL /* ENGINE */) &&
230               EVP_DigestUpdate(ctx, scratch, chunk_len) &&
231               EVP_DigestFinal_ex(ctx, digest, &md_len);
232      })) {
233    fprintf(stderr, "EVP_DigestInit_ex failed.\n");
234    BIO_print_errors_fp(stderr);
235    return false;
236  }
237
238  results.PrintWithBytes(name, chunk_len);
239
240  EVP_MD_CTX_destroy(ctx);
241
242  return true;
243}
244static bool SpeedHash(const EVP_MD *md, const std::string &name) {
245  return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
246         SpeedHashChunk(md, name + " (256 bytes)", 256) &&
247         SpeedHashChunk(md, name + " (8192 bytes)", 8192);
248}
249
250bool Speed(const std::vector<std::string> &args) {
251  const uint8_t *inp;
252
253  RSA *key = NULL;
254  inp = kDERRSAPrivate2048;
255  if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate2048Len)) {
256    fprintf(stderr, "Failed to parse RSA key.\n");
257    BIO_print_errors_fp(stderr);
258    return false;
259  }
260
261  if (!SpeedRSA("RSA 2048", key)) {
262    return false;
263  }
264
265  RSA_free(key);
266  key = NULL;
267
268  inp = kDERRSAPrivate4096;
269  if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate4096Len)) {
270    fprintf(stderr, "Failed to parse 4096-bit RSA key.\n");
271    BIO_print_errors_fp(stderr);
272    return 1;
273  }
274
275  if (!SpeedRSA("RSA 4096", key)) {
276    return false;
277  }
278
279  RSA_free(key);
280
281  if (!SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM") ||
282      !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM") ||
283      !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305") ||
284      !SpeedAEAD(EVP_aead_rc4_md5_tls(), "RC4-MD5") ||
285      !SpeedHash(EVP_sha1(), "SHA-1") ||
286      !SpeedHash(EVP_sha256(), "SHA-256") ||
287      !SpeedHash(EVP_sha512(), "SHA-512")) {
288    return false;
289  }
290
291  return 0;
292}
293