You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

603 regels
18 KiB

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