blob: cfffcb05b3c5a317e92711d2a0792b725904e2af [file] [log] [blame]
Adam Langleyc5c0c7e2014-06-20 12:00:00 -07001/* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
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>
Adam Langley006779a2014-06-20 12:00:00 -070025#include <openssl/digest.h>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070026#include <openssl/obj.h>
27#include <openssl/rsa.h>
28
29#if defined(OPENSSL_WINDOWS)
30#include <Windows.h>
Adam Langley30eda1d2014-06-24 11:15:12 -070031#elif defined(OPENSSL_APPLE)
32#include <sys/time.h>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070033#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; }
Adam Langley30eda1d2014-06-24 11:15:12 -070066#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}
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070077#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
Adam Langley543d0062015-01-15 16:05:41 -0800165template<typename T>
166struct free_functor {
167 void operator()(T* ptr) {
168 free(ptr);
169 }
170};
171
172#if defined(OPENSSL_WINDOWS)
David Benjamin384673c2015-01-21 15:56:14 -0500173uint8_t *AllocAligned(size_t size) {
174 void *ptr = malloc(size);
175 if (ptr == NULL) {
176 abort();
177 }
178 return static_cast<uint8_t*>(ptr);
179}
Adam Langley543d0062015-01-15 16:05:41 -0800180#else
181uint8_t *AllocAligned(size_t size) {
182 void *ptr;
183 if (posix_memalign(&ptr, 64, size)) {
184 abort();
185 }
186 return static_cast<uint8_t*>(ptr);
187}
188#endif
189
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700190static bool SpeedAEADChunk(const EVP_AEAD *aead, const std::string &name,
Adam Langleye7624342015-01-15 17:33:48 -0800191 size_t chunk_len, size_t ad_len) {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700192 EVP_AEAD_CTX ctx;
193 const size_t key_len = EVP_AEAD_key_length(aead);
194 const size_t nonce_len = EVP_AEAD_nonce_length(aead);
195 const size_t overhead_len = EVP_AEAD_max_overhead(aead);
196
197 std::unique_ptr<uint8_t[]> key(new uint8_t[key_len]);
198 memset(key.get(), 0, key_len);
199 std::unique_ptr<uint8_t[]> nonce(new uint8_t[nonce_len]);
200 memset(nonce.get(), 0, nonce_len);
Adam Langley543d0062015-01-15 16:05:41 -0800201 std::unique_ptr<uint8_t, free_functor<uint8_t>> in(AllocAligned(chunk_len));
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700202 memset(in.get(), 0, chunk_len);
Adam Langley543d0062015-01-15 16:05:41 -0800203 std::unique_ptr<uint8_t, free_functor<uint8_t>> out(
204 AllocAligned(chunk_len + overhead_len));
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700205 memset(out.get(), 0, chunk_len + overhead_len);
Adam Langleye7624342015-01-15 17:33:48 -0800206 std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
207 memset(ad.get(), 0, ad_len);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700208
209 if (!EVP_AEAD_CTX_init(&ctx, aead, key.get(), key_len,
210 EVP_AEAD_DEFAULT_TAG_LENGTH, NULL)) {
211 fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
212 BIO_print_errors_fp(stderr);
213 return false;
214 }
215
216 TimeResults results;
Adam Langleye7624342015-01-15 17:33:48 -0800217 if (!TimeFunction(&results, [chunk_len, overhead_len, nonce_len, ad_len, &in,
218 &out, &ctx, &nonce, &ad]() -> bool {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700219 size_t out_len;
220
Adam Langleye7624342015-01-15 17:33:48 -0800221 return EVP_AEAD_CTX_seal(
222 &ctx, out.get(), &out_len, chunk_len + overhead_len, nonce.get(),
223 nonce_len, in.get(), chunk_len, ad.get(), ad_len);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700224 })) {
225 fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
226 BIO_print_errors_fp(stderr);
227 return false;
228 }
229
230 results.PrintWithBytes(name + " seal", chunk_len);
231
232 EVP_AEAD_CTX_cleanup(&ctx);
233
234 return true;
235}
236
Adam Langleye7624342015-01-15 17:33:48 -0800237static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
238 size_t ad_len) {
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);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700242}
243
Adam Langley006779a2014-06-20 12:00:00 -0700244static 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 BIO_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}
273static bool SpeedHash(const EVP_MD *md, const std::string &name) {
274 return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
275 SpeedHashChunk(md, name + " (256 bytes)", 256) &&
276 SpeedHashChunk(md, name + " (8192 bytes)", 8192);
277}
278
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700279bool Speed(const std::vector<std::string> &args) {
280 const uint8_t *inp;
281
282 RSA *key = NULL;
283 inp = kDERRSAPrivate2048;
284 if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate2048Len)) {
285 fprintf(stderr, "Failed to parse RSA key.\n");
286 BIO_print_errors_fp(stderr);
287 return false;
288 }
289
290 if (!SpeedRSA("RSA 2048", key)) {
291 return false;
292 }
293
294 RSA_free(key);
295 key = NULL;
296
297 inp = kDERRSAPrivate4096;
298 if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate4096Len)) {
299 fprintf(stderr, "Failed to parse 4096-bit RSA key.\n");
300 BIO_print_errors_fp(stderr);
301 return 1;
302 }
303
304 if (!SpeedRSA("RSA 4096", key)) {
305 return false;
306 }
307
308 RSA_free(key);
309
Adam Langleye7624342015-01-15 17:33:48 -0800310 // kTLSADLen is the number of bytes of additional data that TLS passes to
311 // AEADs.
312 static const size_t kTLSADLen = 13;
313 // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
314 // These are AEADs that weren't originally defined as AEADs, but which we use
315 // via the AEAD interface. In order for that to work, they have some TLS
316 // knowledge in them and construct a couple of the AD bytes internally.
317 static const size_t kLegacyADLen = kTLSADLen - 2;
318
319 if (!SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen) ||
320 !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen) ||
321 !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen) ||
322 !SpeedAEAD(EVP_aead_rc4_md5_tls(), "RC4-MD5", kLegacyADLen) ||
323 !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1", kLegacyADLen) ||
324 !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1", kLegacyADLen) ||
Adam Langley006779a2014-06-20 12:00:00 -0700325 !SpeedHash(EVP_sha1(), "SHA-1") ||
326 !SpeedHash(EVP_sha256(), "SHA-256") ||
327 !SpeedHash(EVP_sha512(), "SHA-512")) {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700328 return false;
329 }
330
331 return 0;
332}