speed.cc 33 KB

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