blob: 2df6f90142af2958bfe820e519402ff008cded2f [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>
Adam Langley2b2d66d2015-01-30 17:08:37 -080021#include <string.h>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070022#include <time.h>
23
24#include <openssl/aead.h>
25#include <openssl/bio.h>
Adam Langley006779a2014-06-20 12:00:00 -070026#include <openssl/digest.h>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070027#include <openssl/obj.h>
28#include <openssl/rsa.h>
29
30#if defined(OPENSSL_WINDOWS)
Brian Smithefed2212015-01-28 16:20:02 -080031#pragma warning(push, 3)
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070032#include <Windows.h>
Brian Smithefed2212015-01-28 16:20:02 -080033#pragma warning(pop)
Adam Langley30eda1d2014-06-24 11:15:12 -070034#elif defined(OPENSSL_APPLE)
35#include <sys/time.h>
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070036#endif
37
Adam Langley2b2d66d2015-01-30 17:08:37 -080038
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070039extern "C" {
40// These values are DER encoded, RSA private keys.
41extern const uint8_t kDERRSAPrivate2048[];
42extern size_t kDERRSAPrivate2048Len;
43extern const uint8_t kDERRSAPrivate4096[];
44extern size_t kDERRSAPrivate4096Len;
45}
46
47// TimeResults represents the results of benchmarking a function.
48struct TimeResults {
49 // num_calls is the number of function calls done in the time period.
50 unsigned num_calls;
51 // us is the number of microseconds that elapsed in the time period.
52 unsigned us;
53
54 void Print(const std::string &description) {
55 printf("Did %u %s operations in %uus (%.1f ops/sec)\n", num_calls,
56 description.c_str(), us,
57 (static_cast<double>(num_calls) / us) * 1000000);
58 }
59
60 void PrintWithBytes(const std::string &description, size_t bytes_per_call) {
61 printf("Did %u %s operations in %uus (%.1f ops/sec): %.1f MB/s\n",
62 num_calls, description.c_str(), us,
63 (static_cast<double>(num_calls) / us) * 1000000,
64 static_cast<double>(bytes_per_call * num_calls) / us);
65 }
66};
67
68#if defined(OPENSSL_WINDOWS)
69static uint64_t time_now() { return GetTickCount64() * 1000; }
Adam Langley30eda1d2014-06-24 11:15:12 -070070#elif defined(OPENSSL_APPLE)
71static uint64_t time_now() {
72 struct timeval tv;
73 uint64_t ret;
74
75 gettimeofday(&tv, NULL);
76 ret = tv.tv_sec;
77 ret *= 1000000;
78 ret += tv.tv_usec;
79 return ret;
80}
Adam Langleyc5c0c7e2014-06-20 12:00:00 -070081#else
82static uint64_t time_now() {
83 struct timespec ts;
84 clock_gettime(CLOCK_MONOTONIC, &ts);
85
86 uint64_t ret = ts.tv_sec;
87 ret *= 1000000;
88 ret += ts.tv_nsec / 1000;
89 return ret;
90}
91#endif
92
93static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
94 // kTotalMS is the total amount of time that we'll aim to measure a function
95 // for.
96 static const uint64_t kTotalUS = 3000000;
97 uint64_t start = time_now(), now, delta;
98 unsigned done = 0, iterations_between_time_checks;
99
100 if (!func()) {
101 return false;
102 }
103 now = time_now();
104 delta = now - start;
105 if (delta == 0) {
106 iterations_between_time_checks = 250;
107 } else {
108 // Aim for about 100ms between time checks.
109 iterations_between_time_checks =
110 static_cast<double>(100000) / static_cast<double>(delta);
111 if (iterations_between_time_checks > 1000) {
112 iterations_between_time_checks = 1000;
113 } else if (iterations_between_time_checks < 1) {
114 iterations_between_time_checks = 1;
115 }
116 }
117
118 for (;;) {
119 for (unsigned i = 0; i < iterations_between_time_checks; i++) {
120 if (!func()) {
121 return false;
122 }
123 done++;
124 }
125
126 now = time_now();
127 if (now - start > kTotalUS) {
128 break;
129 }
130 }
131
132 results->us = now - start;
133 results->num_calls = done;
134 return true;
135}
136
137static bool SpeedRSA(const std::string& key_name, RSA *key) {
138 TimeResults results;
139
140 std::unique_ptr<uint8_t[]> sig(new uint8_t[RSA_size(key)]);
141 const uint8_t fake_sha256_hash[32] = {0};
142 unsigned sig_len;
143
144 if (!TimeFunction(&results,
145 [key, &sig, &fake_sha256_hash, &sig_len]() -> bool {
146 return RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
147 sig.get(), &sig_len, key);
148 })) {
149 fprintf(stderr, "RSA_sign failed.\n");
150 BIO_print_errors_fp(stderr);
151 return false;
152 }
153 results.Print(key_name + " signing");
154
155 if (!TimeFunction(&results,
156 [key, &fake_sha256_hash, &sig, sig_len]() -> bool {
157 return RSA_verify(NID_sha256, fake_sha256_hash,
158 sizeof(fake_sha256_hash), sig.get(), sig_len, key);
159 })) {
160 fprintf(stderr, "RSA_verify failed.\n");
161 BIO_print_errors_fp(stderr);
162 return false;
163 }
164 results.Print(key_name + " verify");
165
166 return true;
167}
168
Adam Langley543d0062015-01-15 16:05:41 -0800169template<typename T>
170struct free_functor {
171 void operator()(T* ptr) {
172 free(ptr);
173 }
174};
175
Adam Langley26725342015-01-28 15:52:57 -0800176static uint8_t *align(uint8_t *in, unsigned alignment) {
177 return reinterpret_cast<uint8_t *>(
178 (reinterpret_cast<uintptr_t>(in) + alignment) & ~(alignment - 1));
David Benjamin384673c2015-01-21 15:56:14 -0500179}
Adam Langley543d0062015-01-15 16:05:41 -0800180
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700181static bool SpeedAEADChunk(const EVP_AEAD *aead, const std::string &name,
Adam Langleye7624342015-01-15 17:33:48 -0800182 size_t chunk_len, size_t ad_len) {
Adam Langley26725342015-01-28 15:52:57 -0800183 static const unsigned kAlignment = 16;
184
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700185 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);
Adam Langley26725342015-01-28 15:52:57 -0800194 std::unique_ptr<uint8_t, free_functor<uint8_t>> in_storage(
195 new uint8_t[chunk_len + kAlignment]);
196 std::unique_ptr<uint8_t, free_functor<uint8_t>> out_storage(
197 new uint8_t[chunk_len + overhead_len + kAlignment]);
Adam Langleye7624342015-01-15 17:33:48 -0800198 std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
199 memset(ad.get(), 0, ad_len);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700200
Adam Langley26725342015-01-28 15:52:57 -0800201 uint8_t *const in = align(in_storage.get(), kAlignment);
202 memset(in, 0, chunk_len);
203 uint8_t *const out = align(out_storage.get(), kAlignment);
204 memset(out, 0, chunk_len + overhead_len);
205
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700206 if (!EVP_AEAD_CTX_init(&ctx, aead, key.get(), key_len,
207 EVP_AEAD_DEFAULT_TAG_LENGTH, NULL)) {
208 fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
209 BIO_print_errors_fp(stderr);
210 return false;
211 }
212
213 TimeResults results;
Adam Langley26725342015-01-28 15:52:57 -0800214 if (!TimeFunction(&results, [chunk_len, overhead_len, nonce_len, ad_len, in,
215 out, &ctx, &nonce, &ad]() -> bool {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700216 size_t out_len;
217
Adam Langleye7624342015-01-15 17:33:48 -0800218 return EVP_AEAD_CTX_seal(
Adam Langley26725342015-01-28 15:52:57 -0800219 &ctx, out, &out_len, chunk_len + overhead_len, nonce.get(),
220 nonce_len, in, chunk_len, ad.get(), ad_len);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700221 })) {
222 fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
223 BIO_print_errors_fp(stderr);
224 return false;
225 }
226
227 results.PrintWithBytes(name + " seal", chunk_len);
228
229 EVP_AEAD_CTX_cleanup(&ctx);
230
231 return true;
232}
233
Adam Langleye7624342015-01-15 17:33:48 -0800234static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
235 size_t ad_len) {
236 return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len) &&
237 SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len) &&
238 SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len);
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700239}
240
Adam Langley006779a2014-06-20 12:00:00 -0700241static bool SpeedHashChunk(const EVP_MD *md, const std::string &name,
242 size_t chunk_len) {
243 EVP_MD_CTX *ctx = EVP_MD_CTX_create();
244 uint8_t scratch[8192];
245
246 if (chunk_len > sizeof(scratch)) {
247 return false;
248 }
249
250 TimeResults results;
251 if (!TimeFunction(&results, [ctx, md, chunk_len, &scratch]() -> bool {
252 uint8_t digest[EVP_MAX_MD_SIZE];
253 unsigned int md_len;
254
255 return EVP_DigestInit_ex(ctx, md, NULL /* ENGINE */) &&
256 EVP_DigestUpdate(ctx, scratch, chunk_len) &&
257 EVP_DigestFinal_ex(ctx, digest, &md_len);
258 })) {
259 fprintf(stderr, "EVP_DigestInit_ex failed.\n");
260 BIO_print_errors_fp(stderr);
261 return false;
262 }
263
264 results.PrintWithBytes(name, chunk_len);
265
266 EVP_MD_CTX_destroy(ctx);
267
268 return true;
269}
270static bool SpeedHash(const EVP_MD *md, const std::string &name) {
271 return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
272 SpeedHashChunk(md, name + " (256 bytes)", 256) &&
273 SpeedHashChunk(md, name + " (8192 bytes)", 8192);
274}
275
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700276bool Speed(const std::vector<std::string> &args) {
277 const uint8_t *inp;
278
279 RSA *key = NULL;
280 inp = kDERRSAPrivate2048;
281 if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate2048Len)) {
282 fprintf(stderr, "Failed to parse RSA key.\n");
283 BIO_print_errors_fp(stderr);
284 return false;
285 }
286
287 if (!SpeedRSA("RSA 2048", key)) {
288 return false;
289 }
290
291 RSA_free(key);
292 key = NULL;
293
294 inp = kDERRSAPrivate4096;
295 if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate4096Len)) {
296 fprintf(stderr, "Failed to parse 4096-bit RSA key.\n");
297 BIO_print_errors_fp(stderr);
298 return 1;
299 }
300
301 if (!SpeedRSA("RSA 4096", key)) {
302 return false;
303 }
304
305 RSA_free(key);
306
Adam Langleye7624342015-01-15 17:33:48 -0800307 // kTLSADLen is the number of bytes of additional data that TLS passes to
308 // AEADs.
309 static const size_t kTLSADLen = 13;
310 // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
311 // These are AEADs that weren't originally defined as AEADs, but which we use
312 // via the AEAD interface. In order for that to work, they have some TLS
313 // knowledge in them and construct a couple of the AD bytes internally.
314 static const size_t kLegacyADLen = kTLSADLen - 2;
315
316 if (!SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen) ||
317 !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen) ||
318 !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen) ||
319 !SpeedAEAD(EVP_aead_rc4_md5_tls(), "RC4-MD5", kLegacyADLen) ||
320 !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1", kLegacyADLen) ||
321 !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1", kLegacyADLen) ||
Adam Langley006779a2014-06-20 12:00:00 -0700322 !SpeedHash(EVP_sha1(), "SHA-1") ||
323 !SpeedHash(EVP_sha256(), "SHA-256") ||
324 !SpeedHash(EVP_sha512(), "SHA-512")) {
Adam Langleyc5c0c7e2014-06-20 12:00:00 -0700325 return false;
326 }
327
328 return 0;
329}